Generate a bar chart (with Google Chart)Tag(s): Varia


Vertical bar
It's easy to use the Google Chart API to generate a graph.

The code is located on the Google server and you build a URL with all the parameters. Once the URL is received by Google, an image is returned.

Be prepared, "trial and error" is the way to get the thing done!

  var data = [ 
      ['jan', 10], ['feb', 50], ['mar', 30] ,
      ['apr', 100], ['may', 50], ['jun', 100] ,
      ['jul', 40], ['aug', 50], ['sep', 70] , 
      ['oct', 80], ['nov', 20], ['dec', 80]
  
  ];
  
  document.write('<img src="http://chart.apis.google.com/chart?'
               + 'chs=400x200'  // graphic size
               + '&amp;cht=bvs' // bar vertical chart
               + '&amp;chco=ff0000'    // color
               + '&amp;chd=t:');       // data
  for (var i=0; i < data.length; ++i) {
    document.write(data[i][1]);
    if (i < data.length-1) document.write(",");
  }
  
  document.write('&amp;chxt=x,y');     // axis : x bottom y left 
  document.write('&amp;chxl=0:|');
  for (var i=0; i < data.length; ++i) {  // the labels
      document.write(data[i][0]);
      if (i < data.length-1) document.write("|");
  }
  document.write('&amp;chxr=1,0,100');
  document.write('">');

The result :

Horizontal bar

  var data = [ 
      ['jan', 10], ['feb', 50], ['mar', 30] ,
      ['apr', 100], ['may', 50], ['jun', 100] ,
      ['jul', 40], ['aug', 50], ['sep', 70] , 
      ['oct', 80], ['nov', 20], ['dec', 80]
  
  ];

  document.write('<img src="http://chart.apis.google.com/chart?'
               + 'chs=200x300'
               + '&amp;cht=bhs'
               + '&amp;chco=ff0000'
               + '&amp;chd=t:');
  for (var i=0; i < data.length; ++i) {
    document.write(data[i][1]);
    if (i < data.length-1) document.write(",");
  }
  
  document.write('&amp;chxt=y,x'); // left , bottom
  document.write('&amp;chxl=0:|');
  for (var i=data.length-1; i >= 0  ; --i) {
      document.write(data[i][0]);
      if (i > 0) document.write("|");
  }
  document.write('&amp;chxr=1,0,100');
  document.write('">');
The result :

Important : When you embed a URL in an HTML <img> tag, take care to use the character entity reference &amp; in place of an ampersand (&).

See this HowTo to generate a bar chart using plain Javascript.


blog comments powered by Disqus