Use Google Charts to display csv table

Google Charts is a simple javascript package for creating a wide variety of charts. I wanted to try using it to display the same data as the d3.js example that I published in a previous post. Google Charts aren’t as powerful or flexible as the d3.js package, but they are simpler to use. Here’s similar code, but notice that I put the csv data in the code rather than reading it from disk into an array. I did this for my own convenience and expedience. Reading the data from disk is a trivial problem to solve. Here’s the code:

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1.1", {packages:["table"]});
      google.setOnLoadCallback(drawTable);

      function drawTable() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Cohort');
        data.addColumn('number', '0');
        data.addColumn('number', '1');
        data.addColumn('number', '2');
        data.addColumn('number', '3');
        data.addColumn('number', '4');
        data.addColumn('number', '5');
        data.addColumn('number', '6');
        data.addColumn('number', '7');
        data.addColumn('number', '8');
        data.addRows([
          ['2015-23', 100, 16.67, 0, 0, 0, 0, 0, 0, 0],
          ['2015-24', 100, 66.67, 83.33, 50, 50, 50, 33.33, 50, 50],
          ['2015-25', 50, 0, 50, 50, 100, 50, 0, 0, 0],
          ['2015-26', 100, 50, 50, 0, 0, 0, 0, 0, 0],
          ['2015-27', 100, 50, 50, 0, 0, 0, 0, 0, 0],
          ['2015-28', 100, 100, 0, 0, 0, 0, 0, 0, 0],
          ['2015-29', 100, 0, 0, 0, 0, 0, 0, 0, 0],
          ['2015-30', 0, 0, 0, 0, 0, 0, 0, 0, 0],
          ['2015-31', 100, 100, 0, 0, 0, 0, 0, 0, 0]
        ]);

        var table = new google.visualization.Table(document.getElementById('table_div'));

        var formatter = new google.visualization.ColorFormat();
        formatter.addGradientRange(-1, 101, 'black', 'red', 'green');
        formatter.format(data, 1);
        formatter.format(data, 2);
        formatter.format(data, 3);
        formatter.format(data, 4);
        formatter.format(data, 5);
        formatter.format(data, 6);
        formatter.format(data, 7);
        formatter.format(data, 8);
        formatter.format(data, 9);

        table.draw(data, {allowHtml: true, width: '50%', height: '33%'});
      }
    </script>
  </head>
  <body>
    <div id="table_div"></div>
  </body>
</html>

In this case, I am adding each column whereas the d3.js example dynamically determined the number of columns. Not also that in this example I am creating a formatter to create background colors that show the magnitude of the values. The outcome looks like this:

Screen Shot 2015-08-07 at 2.58.40 PM

Advertisements