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

前端 未结 3 1812
野性不改
野性不改 2021-01-07 00:19

I\'m using nv.models.lineWithFocusChart, where I\'m showing some hourly measurements. So the x domain is dates.

What I need is to show a tick per hour on X axis:

相关标签:
3条回答
  • 2021-01-07 00:56

    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

    0 讨论(0)
  • 2021-01-07 01:10

    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)
    
    0 讨论(0)
  • 2021-01-07 01:11

    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.

    0 讨论(0)
提交回复
热议问题