How to show an Empty Google Chart when there is no data?

Vamshi Vangapally picture Vamshi Vangapally · Jun 7, 2012 · Viewed 31.3k times · Source

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?

Answer

Matt Dodge picture Matt Dodge · Jun 7, 2012

What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.

Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.

var data, options, chart;

function drawVisualization() {

  data = google.visualization.arrayToDataTable([
    ['Time', 'dummy'],
    ['', 0],
   ]);

  options = {
    title:"My Chart",
    width:600, height:400,
    hAxis: {title: "Time"},
    legend : {position: 'none'}
  };

  // Create and draw the visualization.
  chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
  chart.draw(data,options);
  setTimeout('addData("12:00",10)',2000);
  setTimeout('addData("12:10",20)',3000);
}

function addData(x,y) {
  if(data.getColumnLabel(1) == 'dummy') {
    data.addColumn('number', 'Your Values', 'col_id');
    data.removeColumn(1);
    options.legend = {position: 'right'};
  }

  data.addRow([x,y]);
  chart.draw(data,options);
}​