Wednesday, 11 December 2013

3 Specifying Range of Data and Selecting Columns : Google Charts with Google Docs data

In the previous post, we had described how to create a basic Google Chart from data stored in a Google Doc spreadsheet. In that example, the data was picked up from the default first sheet of the spreadsheet and the data was located in the top left corner. In reality, the data could be stored in any of the other sheets and could be located in any portion of the sheet.

In this example, the Google Docs spreadsheet, has four sheets. For the purpose of drawing our chart we would like to specify that

  1. Data to be picked up from sheet named "Demo3"
  2. Within this sheet,  from the range C3:I23
  3. Within this range from the columns C, D, G, H
  4. Given the nature of the data we would like to multiply column G by 1000 before it is plotted
If you look at the spreadsheet in a browser, the URL will show up as 
https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&usp=drive_web#gid=3

For our purpose the URL will be truncated as follows and used in the program
https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE

This URL can also be obtained by going to the option File=>Publish to the Web

The chart will look as follows

Sheet 2 Chart - Sheet, Range, Cols

this chart has been generated by embedding the following code in this blog. It can also be embedded in any other HTML page.


<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});

google.setOnLoadCallback(drawChart01);


function drawChart01() {


 var query = new google.visualization.Query(
      'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&sheet=Demo3&range=C3:I12&headers=1');
      query.setQuery('select C,D,1000*G,H'); 
  query.send(handleQueryResponse01);
}

function handleQueryResponse01(response) {
  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }
  
  var options = {
          title: 'Industrial Production Index',
          vAxis: {title: 'Sector',  titleTextStyle: {color: 'red'}},
          width: 400,
          height : 600
        };


  var data = response.getDataTable();
  var chart = new google.visualization.BarChart(document.getElementById('ChartSpan4'));
  chart.draw(data, options );
}



</script>

<title>Sheet 2 Chart - Sheet, Range, Cols</title>
</head>

<body>

<span id='ChartSpan4'></span>
</body>




No comments:

Post a comment