简体   繁体   中英

How to set x-axis values in d3 Javascript graph?

I'm using the d3 JS library to plot some graphs. It works fine, but I'm stuck on a weird problem which I've been struggling with for an hour - I can't set the x-axis values. Here is the graph (I added an alert that will show you the data format):

http://jovansfreelance.com/bikestats/d3/tipsy.php

I want the x-axis to show years, but for some reason that I can't see anywhere in the code, it's using decimal values instead, so instead of 2006 it has .006 - I have no idea where this is coming form, like it takes out the first digit and divides the rest by 100?!

If someone can point me to the lines of code that are doing this, that would be fine, I can take it from there.

As pointed out in another answer, a better way of handling time values is to explicitly use time scales. However, to achieve what you want it is sufficient to specify the format for the x axis explicitly. That is, to

var xAxis = d3.svg.axis()
        .scale(x)
        .tickSize(h - margin * 2)
        .tickPadding(10)
        .ticks(7)

add

.tickFormat(d3.format("d"));

Could be related to this parseDate = d3.time.format("%Y") not working

If so, you might need

d3.svg.axis()
   .scale(x)
   .tickSize(h - margin * 2).tickPadding(10).ticks(7)
   .tickFormat(function(d) { return d.toString(); }); // force the date value into a string

or, if you need the parse the date

   .tickFormat(function(d) { 
      var fmt = d3.time.format("%Y"); 
      return format.parse(d).toString() 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM