D3 ticks() does not return value if provided scale has only 1 result

前端 未结 3 1787
借酒劲吻你
借酒劲吻你 2021-01-28 03:35

I have an x-axis that displays the days that my data occurs on. The data is dynamic and sometimes I have data for only 1 day, 2 days, n days, etc.

Here is my code for di

3条回答
  •  礼貌的吻别
    2021-01-28 04:10

    To extend the domain so that the scale starts and ends at a tick mark you use the .nice() method, as @meetamit suggested -- but "nicing" only works if you call that method after you set the domain, so that's why you might not have noticed any change. The API doesn't really make that clear, although since the method alters the domain I suppose it makes sense that changing the domain later would over-ride the effect of a previous nice() call.

    Also, be sure to use the time-scale version of the method: .nice(d3.time.day) to get a domain rounded off to the nearest day as opposed to just the nearest hour.

    Here's a fiddle:
    http://fiddle.jshell.net/4rGQq/

    The key code is simply:

    xScale.domain(d3.extent(d)) 
          //d3.extent() returns max and min of array, which become the basic domain
          .nice(d3.time.day);  
          //nice() extends the domain to nearest start/end of a day
    

    Compare what happens if you comment out the .nice() call after setting the domain, even with the other .nice() call during initialization of the scale. Also compare what happens if you don't specify the day-interval as a parameter to the nice method.

提交回复
热议问题