谷歌堆积条形图不想显示0条

时间:2019-07-05 17:28:58

标签: charts google-visualization

在Google堆叠的条形图中,有什么方法可以使它不显示零值的条形? enter image description here

我不希望第一栏上的红色细线或悬停显示。

这是我的代码:

var data = google.visualization.arrayToDataTable([
        ['Class', 'Cost', 'Savings', { role: 'annotation' } ],
        ['Current State Run', 140999460, 0, ''],
        ['Total Future State Run', 109351526, 31647934, '']
      ]);

var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
                { calc: "stringify",
                  sourceColumn: 1,
                  type: "string",
                  role: "annotation" },
                2, 
                { calc: formatter,
                  sourceColumn: 2,
                  type: "string",
                  role: "annotation" },
                3]);

function formatter(dataTable, row) {
    if (data.getValue(row, 2))
        return parseInt(data.getValue(row, 2)).toLocaleString()
    else
        return '';
}

1 个答案:

答案 0 :(得分:1)

将零值转换为null
这将隐藏行和工具提示。

如果需要,可以使用DataView和计算列,
将零动态更改为null

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

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Class', 'Cost', 'Savings'],
    ['Current State Run', 140999460, 0],
    ['Total Future State Run', 109351526, 31647934]
  ]);

  var view = new google.visualization.DataView(data);

  var viewCols = [0];
  for (var i = 1; i < data.getNumberOfColumns(); i++) {
    addCalcs(i);
  }

  view.setColumns(viewCols);

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  var options = {
    isStacked: true
  };

  chart.draw(view, options);

  function addCalcs(col) {
    viewCols.push({
      calc: function (dt, row) {
        return getNullValue(dt, row, col);
      },
      label: data.getColumnLabel(col),
      type: data.getColumnType(col)
    });

    viewCols.push({
      calc: function (dt, row) {
        return formatter(dt, row, col);
      },
      type: 'string',
      role: 'annotation'
    });
  }

  function formatter(dataTable, row, col) {
    if (data.getValue(row, col)) {
      return parseInt(data.getValue(row, col)).toLocaleString()
    } else {
      return '';
    }
  }

  function getNullValue(dataTable, row, col) {
    var value = dataTable.getValue(row, col);
    if (value === 0) {
      return null;
    }
    return value;
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>