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

34,187

Solution 1

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);
}​

Solution 2

A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.

function drawVisualization() {
  var data = google.visualization.arrayToDataTable([
      ['', { role: 'annotation' }],
      ['', '']
  ]);

  var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
  ac.draw(data, {
      title : 'Just a title...',
      width: 600,
      height: 400
  });
}

Share:
34,187

Related videos on Youtube

Vamshi Vangapally
Author by

Vamshi Vangapally

Passionate about building solutions for problems around in the form of web and mobile applications. Design thinking, Product strategy, Skill management and Ability to code are my strengths - http://vamshi.mycollect.in, http://confusedcoin.com

Updated on July 09, 2022

Comments

  • Vamshi Vangapally
    Vamshi Vangapally almost 2 years

    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"?

Related