how to set the domain and scale on an axis on a nvd3.js multiBarChart

前端 未结 3 578
情话喂你
情话喂你 2021-02-13 17:04

In d3.js you can set an x axis to use d3.time.scale() then set x.domain([start_date, end_date]) and it will \'fill in\' any missing dates that aren\'t

3条回答
  •  春和景丽
    2021-02-13 17:32

    You can do this in 2 ways:

    A) You either rewrite the axis component of nvd3 to use d3.time.scale() / make another axis component for this use case...

    Or the easiest way:

    B) You use the custom values for the axis. First of all you use the + operator ( +(date) ) to have the values in ms. There is a tickValues function in d3 that allows you to pass custom values for the ticks.. To force the X scale you have the forceX() method from the scatter (I assume you already know about this) and you write a simple function that takes custom values for ticks.... So if you force your scale to have values between Jan 1 2002 and Dec 31 2012 and then decide to have 4 ticks you can use either ticks directly or tickValues...

    So it goes like this (add something similar to the multiBarChart.js file):

      lines.forceX(minValue, maxValue) //where minValue and maxValue are the values
      //converted to ms already after you did +(date)
    
      //then you just rewrite the ticks - if you want a custom number of ticks you can do it like this
    
      //numberOfTicks is a method I added to the axis component (axis.js) to give the number of ticks the user would like to have
    
      //x.domain() now contains the forced values instead of the values you initially used..
      var maxTicks = xAxis.numberOfTicks()-1, xMin = x.domain()[0], xMax = x.domain()[1], 
          xDiff = (xMax - xMin)/maxTicks, tickInterval = [];
    
      tickInterval[0] = xMin;
    
      for(i=1; i

    Hope this helps... I know it's hack but it worked in my case :) And of course if you already formatted the date to be displayed as year you will get the values for the years when displaying the ticks :)

    This is how I did it for lines. For multiBarChart you will need to add an extra step: you need to deal with the reduceTicks functionality (set it to false, delete that part of the code, do whatever you like with it...)

提交回复
热议问题