Google Charts and CSV Part 3: Side-by-Side Bubble Charts

Introduction

If you haven’t already, go ahead and take a look at the previous two installments of this series (Easy Data Visualization with Google Charts and a CSV and More Google Charts with a CSV: Bubble Charts). Today we’re going to take the bubble chart from More Google Charts with a CSV: Bubble Charts and add another chart to the same page. It’s not exactly as simple as duplicating all the code we created last time, but it nearly is.

Setup

Begin by downloading the finished product from last time here. Also, I’ve pasted the HTML below in case that’s easier for you:

<!DOCTYPE html> <html> <head> <title>Google Chart Example</title> <style> ul {list-style-type: none;} </style> <script src="https://www.google.com/jsapi"></script> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script src="jquery.csv-0.71.js"></script> <script> // load the visualization library from Google and set a listener google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { // grab the CSV $.get("kzn1993.csv", function(csvString) { // transform the CSV string into a 2-dimensional array var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); // use arrayData to load the select elements with the appropriate options for (var i = 0; i < arrayData[0].length; i++) { // this adds the given option to both select elements $("select").append("<option value='" + i + "'>" + arrayData[0][i] + "</option"); } // set the default selection $("#domain option[value='0']").attr("selected","selected"); $("#range option[value='1']").attr("selected","selected"); // this new DataTable object holds all the data var data = new google.visualization.arrayToDataTable(arrayData); // this view can select a subset of the data at a time var view = new google.visualization.DataView(data); view.setColumns([{calc:stringID, type: "string"},1,2,3]); // this function returns the first column values as strings (by row) function stringID(dataTable, rowNum){ // return dataTable.getValue(rowNum, 0).toString(); // return an empty string instead to avoid the bubble labels return ""; } var options = { title: "KwaZulu-Natal Household Survey (1993)", hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max}, vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max}, bubble: {stroke: "transparent", opacity: 0.2}, colorAxis: {colors:['red','blue']}, }; var chart = new google.visualization.BubbleChart(document.getElementById('chart')); chart.draw(view, options); // set listener for the update button $("select").change(function(){ // determine selected domain and range var domain = +$("#domain option:selected").val(); var range = +$("#range option:selected").val(); var color = +$("#color option:selected").val(); var size = +$("#size option:selected").val(); // update the view view.setColumns([{calc:stringID, type: "string", label: "Household ID"},domain,range,color,size]); // update the options options.hAxis.title = data.getColumnLabel(domain); options.hAxis.minValue = data.getColumnRange(domain).min; options.hAxis.maxValue = data.getColumnRange(domain).max; options.vAxis.title = data.getColumnLabel(range); options.vAxis.minValue = data.getColumnRange(range).min; options.vAxis.maxValue = data.getColumnRange(range).max; options.bubble = {stroke: "transparent", opacity: 0.2}; options.colorAxis = {colors:['red','blue']}; // update the chart chart.draw(view, options); }); }); } </script> </head> <body> <div id="chart" style="width:800px; height:500px;"> </div> <ul> <li> Y-Axis <select id="range"></select> </li> <li> X-Axis <select id="domain"></select> </li> <li> Color <select id="color"></select> </li> <li> Size <select id="size"></select> </li> </ul> </body> </html> 

Data

For this tutorial I’ve split the South African data by province in 1993. File kz1993.csv contains only the households in the former KwaZulu bantustan. File n1993.csv contains only the black households in the Natal province of what was at the time “white” South Africa. For more details on the data, please see the first tutorial in this series (Easy Data Visualization with Google Charts and a CSV).

HTML

Let’s begin by modifying the HTML. First we’ll encapsulate both the chart and the list in a <div> that is floated to the left. We also need to add a class (I’m going to choose chart) to each of the <select> elements to distinguish the chart on the left from the one on the right:

 <div style="float:left;"> <div id="chart" style="width:600px; height:500px;"> </div> <ul> <li> Y-Axis <select class="chart" id="range"></select> </li> <li> X-Axis <select class="chart" id="domain"></select> </li> <li> Color <select class="chart" id="color"></select> </li> <li> Size <select class="chart" id="size"></select> </li> </ul> </div> 

So far so good. Now copy this entire <div> and paste a duplicate below. Change the ids and classes for this <div> by adding a 2. Also change the float direction to “right“:

 <div style="float:right"> <div id="chart2" style="width:600px; height:500px;"> </div> <ul> <li> Y-Axis <select class="chart2" id="range2"></select> </li> <li> X-Axis <select class="chart2" id="domain2"></select> </li> <li> Color <select class="chart2" id="color2"></select> </li> <li> Size <select class="chart2" id="size2"></select> </li> </ul> </div> 

JavaScript

Chart 1

Now we need to make some adjustments to our drawChart() callback function. First we’ll change the CSV file reference from the kzn1993.csv to kz1993.csv.

 function drawChart() { // grab the first CSV $.get("kz1993.csv", function(csvString) { 

In the for loop we need to change the jQuery selection of all select elements to only those with the chart class:

 // use arrayData to load the select elements with the appropriate options for (var i = 0; i < arrayData[0].length; i++) { // this adds the given option to both select elements $("select.chart").append("<option value='" + i + "'>" + arrayData[0][i] + "</option>"); } 

The last change we need to make for the chart on the left is to modify the title:

 var options = { title: "KwaZulu-Natal Household Survey (1993) - KwaZulu", hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max}, vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max}, bubble: {stroke: "transparent", opacity: 0.2}, colorAxis: {colors:['red','blue']}, }; 

Chart 2

Now, for the chart on the right we can start by copying the $.get(); call of the first chart. We just need to change the referenced CSV, the referenced HTML ids and classes, and the title. First, change the referenced CSV:

 // grab the second CSV (this one covers Natal Province) $.get("n1993.csv", function(csvString) { 

Next, change the referenced ids and classes here:

 // use arrayData to load the select elements with the appropriate options for (var i = 0; i < arrayData[0].length; i++) { // this adds the given option to both select elements $("select.chart2").append("<option value='" + i + "'>" + arrayData[0][i] + "</option>"); } // set the default selection $("#domain2 option[value='0']").attr("selected","selected"); $("#range2 option[value='1']").attr("selected","selected"); 

and here:

 var chart = new google.visualization.BubbleChart(document.getElementById('chart2')); chart.draw(view, options); // set listener for the update button $("select.chart2").change(function(){ // determine selected domain and range var domain = +$("#domain2 option:selected").val(); var range = +$("#range2 option:selected").val(); var color = +$("#color2 option:selected").val(); var size = +$("#size2 option:selected").val(); 

The last thing to do is change the title:

 var options = { title: "KwaZulu-Natal Household Survey (1993) - Natal", hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max}, vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max}, bubble: {stroke: "transparent", opacity: 0.2}, colorAxis: {colors:['red', 'blue']}, }; 

Conclusion

The end result looks pretty nice (if your charts stack vertically, you need to make your charts smaller or your screen wider). side_by_side To play around with a live version go here. If any of this was confusing, please check the previous two tutorials (Easy Data Visualization with Google Charts and a CSV and More Google Charts with a CSV: Bubble Charts) or leave a comment below.

Comments

  1. that’s awwwwwwwwesome, I think I was stuck on the $(“select.chart”)—-did not notice to change the selection.
    —Just on the side notice:

    Have you tried this when different data sources resident in different script element
    Especially when you have 10+ data sources and display in the same page.It would make code much cleaning.

    easier to identify each element if they are in different , I have not get that to work, just wondering if you have any thought on that.

    • You could place the callback functions in an external script (just make sure to load the external script before you refer to the callback). Then you could change this:

      $.get("kz1993.csv", function(csvString) {
          // function code
      }

      to this:

      $.get("kz1993.csv", kzchart);

      where your external call back function looks like this:

      var kzchart = function(csvString) {
          // function code
      };

      A more flexible solution is to make one external function that returns the desired callbacks. Essentially your call from the internal script would look like this:

      $.get("kz1993.csv", chartCallback("2"));

      Your external callback generator would then look like this:

      var chartCallback = function(suffix) {
          var callback = function(csvString) {
              // function code
              // make sure to add the suffix to the relevant ids and classes (e.g., "chart", "domain", etc.)
          };
          return callback;
      };
  2. Awesome, a great help for new learner to understand. Thanks a lot for the post. Can I use this code?

  3. Hello Jonathan,

    Your tutorials are simple and awesome.
    I am trying to do the same and my graph is not being displayed. Both my script and csv file are both in same directories. This csv file is a an output of python script. Can you please have a look at it and let me know if there are any changes:-

    #!/usr/bin/python
    import sys, pkg_resources, imp
    import os
    import pyodbc
    import MySQLdb
    import gviz_api
    import csv
    print “”
    print ”’

    google.load(“visualization”, “1”, {packages:[“corechart”]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
    $.get(“mycsvfile.csv”,function(csvString){
    var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
    var data = new google.visualization.arrayToDataTable(arrayData);
    var view = new google.visualization.DataView(data);
    view.setColumns([0,1]);

    //set options
    var options = {
    title: ‘Company Performance’,
    is3D:true,
    hAxix:{title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
    vAxis:{title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max },
    legend: ‘none’
    };
    var chart = new google.visualization.PieChart(document.getElementById(‘piechart_3d’));
    chart.draw(view, options);
    });
    }

    ”’

Leave a Reply