Larry Martell
Larry Martell

Reputation: 3756

google stacked bar chart do not want to display 0 bar

In a google stacked bar chart is there any way to have it not display a bar with a zero value? enter image description here

I do not want the thin red line on the first bar or the hover to show.

Here is my code:

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 '';
}

Upvotes: 1

Views: 1095

Answers (1)

WhiteHat
WhiteHat

Reputation: 61212

convert the zero value to null,
this will hide the line and tooltip.

if needed, you can use a DataView and calculated columns,
to dynamically change the zeroes to null

see following working snippet...

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>

Upvotes: 1

Related Questions