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

前端 未结 3 568
情话喂你
情话喂你 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:15

    Based on the above answer, you can do this with numeric x values (not Date objects) as well as a forced X range and specified tickValues.... for certain types of charts.

    Bar charts do not seem to have the capability, however nvd3.lineCharts do what you'd like. The multiBarChart model does not allow the use of the forceX function to be applied (right now, ever?).

    A solution to your problem would be to fill in the 0's or to use a sequential chart type (e.g. lineChart)

    nv.addGraph(function() {
      var chart = nv.models.lineChart()
          .forceX(2001,2011);
    
      var tickMarks = [2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011]
    
      chart.xAxis
          .tickValues(tickMarks)
          .tickFormat(function(d){ return d });
    
      chart.yAxis
          .tickFormat(d3.format(',f'));
    
      var data = [{
        'key': 'GB by year',
        'values': [
          {x: 2001, y: 0.12},
          {x: 2004, y: 0.03},
          {x: 2005, y: 0.53},
          {x: 2006, y: 0.43},
          {x: 2007, y: 5.5},
          {x: 2008, y: 9.9},
          {x: 2009, y: 26.85},
          {x: 2010, y: 0.03},
          {x: 2011, y: 0.12}
        ]
      }];        
    
      d3.select('#chart svg')
        .datum(data)
        .transition().duration(500).call(chart);
    
      nv.utils.windowResize(chart1.update);
    
      return chart;
    });   
    

提交回复
热议问题