在Google折线图上不显示0值

时间:2019-11-16 09:28:28

标签: angularjs charts google-visualization

        var data = google.visualization.arrayToDataTable([
          ['Year', 'Massachusetts', 'National'],
          ['2010',  88,  76],
          ['2011',  0,  82],
          ['2012',  96,  86],
          ['2013',  100,  91],
          ['2014',  0,  94],
          ['2015',  -1,  98],
          ['2016',  100,  99],
          ['2017',  124,  100],
          ['2018',  125,  102]
        ]);

这是我用来创建折线图的数据,我不想在图表上显示0和负值。我只想跳过这些值。

my current chart looks like this

Expected chart is like this

1 个答案:

答案 0 :(得分:0)

我们可以使用包含计算列的数据视图,
null

替换小于或等于零的值
  var view = new google.visualization.DataView(data);
  var viewColumns = [0];
  for (var i = 1; i < data.getNumberOfColumns(); i++) {
    addViewColumn(i);
  }
  view.setColumns(viewColumns);

  function addViewColumn(columnIndex) {
    viewColumns.push({
      calc: function (dt, row) {
        var valNew = null;
        var valOrig = dt.getValue(row, columnIndex);
        if (valOrig > 0) {
          valNew = valOrig;
        }
        return valNew;
      },
      label: data.getColumnLabel(columnIndex),
      type: data.getColumnType(columnIndex)
    });
  }

然后使用以下配置选项,该配置选项会跳过null

interpolateNulls: true

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

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Massachusetts', 'National'],
    ['2010',  88,  76],
    ['2011',  0,  82],
    ['2012',  96,  86],
    ['2013',  100,  91],
    ['2014',  0,  94],
    ['2015',  -1,  98],
    ['2016',  100,  99],
    ['2017',  124,  100],
    ['2018',  125,  102]
  ]);
  
  var view = new google.visualization.DataView(data);
  var viewColumns = [0];
  for (var i = 1; i < data.getNumberOfColumns(); i++) {
    addViewColumn(i);
  }
  view.setColumns(viewColumns);

  function addViewColumn(columnIndex) {
    viewColumns.push({
      calc: function (dt, row) {
        var valNew = null;
        var valOrig = dt.getValue(row, columnIndex);
        if (valOrig > 0) {
          valNew = valOrig;
        }
        return valNew;
      },
      label: data.getColumnLabel(columnIndex),
      type: data.getColumnType(columnIndex)
    });
  }

  var options = {
    title: 'Average Home Insurance Premium',
    interpolateNulls: true
  };

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