With NVD3.js (nv.models.lineWithFocusChart), how do you set specific ticks on X-axis, when x values are dates?

萝らか妹 提交于 2019-12-01 00:44:03

Ok, this is really old, but I will answer to help out anyone else who is having this issue.

The problem is that in the nvd3 framework, no matter what you set the ticks() to, it will be automatically overwritten when the chart is generated. See the following code within lineWithFocusChart [dev version of nv.d3.js, 1.1.15b]:

6526        xAxis
6527            .scale(x)
6528            .ticks( availableWidth / 100 ) // <-- this is the problem
6529            .tickSize(-availableHeight1, 0);

My solution was to make a minor edit to nvd3. When the xAxis is created, the ticks value is null. So simply have nvd3 check to see if ticks is null before overwriting with the default code (above). That gives you the chance to provide an alternate ticks function which will not be overwritten. Here's what mine edited version looked like:

6526        xAxis
6527            .scale(x)
6528            .tickSize(-availableHeight1, 0);
6529
6530        if (xAxis.ticks() == null) // <-- ignores default if you already set ticks()
6531            xAxis.ticks( availableWidth / 100 ) 

After making this change, you can use the code suggested by @Lars Kotthoff above to set the ticks format to a time interval, e.g.,

chart.xAxis.ticks(d3.time.hours);

One other note...if you haven't already...you need to make sure that you explicitly set the xScale on the chart to use the time scale:

chart.xScale(d3.time.scale());

This problem also occurs stackedAreaChart and lineChart...and probably other charts as well.

The other solutions did not work for me. Also, I did not want to modify the source code for nvd3, because then future updates to nvd3 will break my code. Instead what did work for setting tick counts in nvd3 was sending the times as integers and specifying the specific values that I wanted displayed.

In my case I needed to do this:

chart.xAxis.tickValues([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]);

It turns out that setting tickValues overrides the ticks automatic generation per: https://github.com/mbostock/d3/wiki/SVG-Axes#tickValues

D3 offers a convenience function for doing specific time intervals (see the documentation). You should be able to simply do

chart.xAxis.ticks(d3.time.hours, 1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!