谷歌图表最小maxValue

时间:2017-08-14 09:53:29

标签: charts google-visualization

我遇到了在vAxis谷歌图表中设置最小maxValue的问题。 当我有数据时,它可以完美地With Data

但是如果没有数据我就有WithoutData

我如何设置例如10的最小maxValue,当我没有数据时看到从0到10的比例,当我有数据时从数据中看到maxValue?

这是我的代码

<div  class="show_chart">
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages': ['bar']});
        google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
        var data = google.visualization.arrayToDataTable(<?= $data ?>);
        var options = {
        chart: {
        title: 'Company Performance',
        subtitle: 'Sales, Expenses, and Profit: 2014-2017',
        },
        vAxis: {

                viewWindow: {
                min: 0,
                },

                textStyle: {fontSize: 12},
                format: '0',

        },
                hAxis: {
                title: "Days",
                },
                format: '0',

        };
        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
        chart.draw(data, google.charts.Bar.convertOptions(options));
        }
    </script>
</div>

<div id="columnchart_material" style="width: 800px; height: 500px;"></div>

1 个答案:

答案 0 :(得分:0)

您可以设置默认最大值10

然后如果有数据,
使用getColumnRange查找每列中的最大值

然后使用Math.max,就像这样...

var rangeMax = 0;
if (data.getNumberOfRows() > 0) {
  for (var i = 0; i < data.getNumberOfColumns(); i++) {
    rangeMax = Math.max(rangeMax, data.getColumnRange(i).max);
  }
} else {
  rangeMax = 10;
}

请参阅以下工作代码段...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable({
      cols: [
        {label: 'x', type: 'string'},
        {label: 'y0', type: 'number'},
        {label: 'y1', type: 'number'}
      ]
    });
    drawChart(data);

    data.addRows([
      [{v: '01'}, {v: 10}, {v: 20}],
      [{v: '02'}, {v: 5}, {v: 40}],
      [{v: '03'}, {v: 1}, {v: 30}],
      [{v: '04'}, {v: 2}, {v: 60}],
      [{v: '05'}, {v: 8}, {v: 10}]
    ]);
    drawChart(data);
  },
  packages: ['corechart']
});

function drawChart(data) {
  var rangeMax = 0;
  if (data.getNumberOfRows() > 0) {
    for (var i = 0; i < data.getNumberOfColumns(); i++) {
      rangeMax = Math.max(rangeMax, data.getColumnRange(i).max);
    }
  } else {
    rangeMax = 10;
  }

  var options = {
    vAxis: {
      format: 0,
      viewWindow: {
        min: 0,
        max: rangeMax
      }
    }
  };

  var container = document.getElementById('charts').appendChild(document.createElement('div'));
  var chart = new google.visualization.LineChart(container);
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="charts"></div>