当图表的所有数据均为0时,将vaxis Google折线图最小值设置为0

时间:2019-06-07 08:35:20

标签: javascript charts google-visualization

当图表的所有数据均为0时,我试图将vaxis Google折线图的最小值设置为0。这是我用来绘制图表的代码:

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  0,      0],
          ['2005',  0,      0],
          ['2006',  0,       0],
          ['2007',  0,      0]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' }


        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>

这是输出  https://i.stack.imgur.com/V5Rww.png

我尝试了一些类似这样的代码:

vAxis: {
                minValue:0,
                viewWindow: {
                    min: 0
                }
            }

并这样:

vAxis: { viewWindow: { min: 0 }, viewWindowMode: "explicit" }

但是这些都不起作用。

1 个答案:

答案 0 :(得分:0)

奇怪,所有值均为零时,图表似乎忽略了minValueviewWindow.min

但是,我们仍然可以使用ticks-> ticks: [0]-或-ticks: [0, 1]

请参阅以下工作片段...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', 'Expenses'],
    ['2004',  0,      0],
    ['2005',  0,      0],
    ['2006',  0,      0],
    ['2007',  0,      0]
  ]);

  var options = {
    title: 'Company Performance',
    curveType: 'function',
    legend: {
      position: 'bottom'
    }
  };

  if (zeroAxis())  {
    options.vAxis = {};
    options.vAxis.ticks = [0];
  }

  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);

  // determine if all y-axis values are zero
  function zeroAxis() {
    var yAxisRange = {
      max: null,
      min: null
    };
    for (var i = 1; i < data.getNumberOfColumns(); i++) {
      var range = data.getColumnRange(i);
      yAxisRange.max = yAxisRange.max || range.max;
      yAxisRange.max = Math.max(yAxisRange.max, range.max);
      yAxisRange.min = yAxisRange.min || range.min;
      yAxisRange.min = Math.min(yAxisRange.min, range.min);
    }
    return ((yAxisRange.max === 0) && (yAxisRange.min === 0));
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>