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

前端 未结 3 1831
野性不改
野性不改 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 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.

提交回复
热议问题