How do I display dates on the x-axis for nvd3 / d3.js?

前端 未结 2 1304
太阳男子
太阳男子 2020-12-13 03:42

I\'m using nvd3, but I think this is a general d3.js question about time scale and formatting. I\'ve created a simple example that illustrates the problem (see code below):<

相关标签:
2条回答
  • 2020-12-13 04:10

    Try creating a new Date object before the tick for the x-axis gets passed to the formatter:

    .tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })
    

    See the documentation for d3.time.format to see how you can customize the formatting string.

    0 讨论(0)
  • 2020-12-13 04:27

    Adding on to seliopou's answer, to correctly align the dates with the x-axis, try this:

    chart.xAxis
          .tickFormat(function(d) {
              return d3.time.format('%d-%m-%y')(new Date(d))
          });
    
      chart.xScale(d3.time.scale()); //fixes misalignment of timescale with line graph
    
    0 讨论(0)
提交回复
热议问题