Using Google Charts [Guide]

Posted on - Last Modified on

There are a number of Web applications that require charts to better display data or increase website usability. In this article, I present some of the charts from Google’s charting library.

I created a sample application that displays chart types and the related code. The application was implemented using Node.js (related article here and here) and Express.js (article about Express.js here), and uses the Bootstrap UI kit with the Cerulean theme. Here is a screenshot of the application:

Starting the Application

The source code of the application is hosted on the google_chart_guide repository in GitHub. Use these commands to clone and start the application:

greg@earth $> git clone https://github.com/gergob/google_chart_guide.git
greg@earth $> cd google_chart_guide
greg@earth $/google_chart_guide> npm install
greg@earth $/google_chart_guide> DEBUG=google_chart_guide:* npm start

After starting the application, the menu can be used to view examples of the different chart types.

The API

To draw charts, we're going to need data. In the api.js file I implemented three methods, which return different data types. The /api/cities route returns an array of JSON objects which have cityName, population and income

router.get('/cities', function (req, res, next) {

    var cityData = [
        {
            'cityName': 'Debrecen',
            'population': 237888,
            'income': 135430
        }
        …        
    ];

    res.json(cityData);
});

The second API route is /api/population. Here I return Hungary’s population statistics from 1870 to 2011 as a JSON array:

router.get('/population', function (req, res, next) {

    var population = [
        {
            'year': 1870,
            'population': 5011310
        },
        {
            'year': 1890,
            'population': 6009351
        }
        …
    ];

    res.json(population);
});

The third API route is /api/gaugedata and this returns the JSON data for the Gauge Chart. The data array contains an object with temperature values.

router.get('/gaugedata', function (req, res, next) {

    var data = [
        {
            data: '°C',
            value: 27.3
        },
        {
            data: '°C',
            value: 32.1
        },
        {
            data: '°C',
            value: 28.5
        }
    ];

    res.json(data);
});

Basics of Google Charts

Google charts uses Google’s JSAPI library for loading the libraries needed for drawing the charts. All the charts need Google’s Visualization library, and, in some cases, a package for the chart.

Below is the code that loads the visualization library using JSAPI. This code is used in every chart example for loading the necessary modules and packages.

//load the JSAPI script on pages – jade template
script(src='https://www.google.com/jsapi')

// script for loading the visualization library plus the packages
google.load('visualization', '1', {'packages':['corechart', 'bar']});
google.setOnLoadCallback(drawChart);

Bar Chart

Bar charts are one of the simplest ways to display data. In this example, the population of the biggest Hungarian cities and the average income in those cities is displayed. Disclaimer: the data for the population was taken from Wikipedia, but random numbers were used for the average income.

The complete source code for creating the bar:

google.load('visualization', '1', {'packages':['corechart', 'bar']});
google.setOnLoadCallback(drawChart);

function drawChart() {
    $.get('/api/cities', function(response) {
        console.log(response);

        var chartData = [];
        for(var idx = 0; idx < response.length; ++idx) {
            var item = response[idx];
            chartData.push([item.cityName, item.population, item.income]);
        }

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'City Name');
        data.addColumn('number', 'Population');
        data.addColumn('number', 'Income');
        data.addRows(chartData);

        var options = {
            title: 'City population and average income',
            bars: 'horizontal', // Required for Material Bar Charts.
            series: {
                0: { axis: 'population' },
                1: { axis: 'income' }
            },
            axes: {
                x: {
                    population: {label: 'population'},
                    income: {side: 'top', label: 'income'}
                }
            }
        };

        //create and draw the chart from DIV
        var chart = new google.visualization.BarChart(document.getElementById('barchart'));
        chart.draw(data, options);

    }, 'json');
}

The first two lines were already covered. Once all the dependent libraries are loaded by JSAPI, the drawChart() method is invoked. Inside the method, the data is loaded from the API using jQuery’s http get. Once I get the response, I log it to the console. The data is then transformed to the format needed by the chart. Most of the time, Google Charts uses an array of arrays as a data-source, so I create the chartData as an empty array, then iterate it over the response items before creating a new array for each item. The arrays have 3 elements: cityName, population and income.

Next, I create a new DataTable object and add three columns to the table (City Name, Population and Income). The previously created chartData array of arrays are then added as rows for the DataTable.

Each chart type has its own set of options that can be customized. For bar charts, the title and the orientation (vertical or horizontal) of the bars can be set. The series is then set, with the population values on index zero, and the income values on index one. Then I set what the x axis should display.

Once the options have been set up, the chart object from google.visualization module is created. The chart object constructor needs an HTML div element to work with. I then invoke the draw method on the chart object and pass the data (DataTable object) and the options as parameters.

Donut Chart

In the Google charts library, Donut Charts are drawn if the options object has the pieHole property set.

The data transformation for the Donut Chart is the same as it is for Bar Chart; the only difference is in the options object and the creation of the chart.

var options = {
    title: 'Hungarian Population Spread',
    pieHole: 0.4,
    slices: {
        0: {offset: 0.2},
        4: {offset: 0.1}
    }
};

//create and draw the chart from DIV
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);

The chart has a title, and the pieHole property is set to 0.4. This should have a value between 0 and 1 so a nice donut shape is drawn. A new PieChart object is created this time, and a div DOM element is provided to the constructor.

Pie Chart

Pie charts were covered in the Donut Chart section. The only difference is that Pie Charts do NOT have the pieHole option set.

In this case, I only set the title:

var options = {
    title: 'Hungarian Income Spread'
};

//create and draw the chart from DIV
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);

Google provides colors for the Pie Chart by default.

Line Chart

For the Line Chart, I used a different set of data. I stored Hungary’s population from 1870 to 2011 and displayed that on the chart.

The instantiation of a Line Chart is simple: I set the title of the chart, create a new instance of Line Chart, and draw the chart by setting the data and options.

var options = {
    title: 'Hungarian Population Change between 1870 and 2011'
};

//create and draw the chart from DIV
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(data, options);

Geo Chart

I think Geo Charts are the most interesting ones because data can be displayed on a map, which is very visually intuitive way to show regional or geographic data.

This Geo Chart displays the biggest Hungarian cities, with dot sizes and colors that differ based on the population size.

For Geo Charts, the options differ:

var options = {
    region: 'HU',
    displayMode: 'markers',
    colorAxis: {colors: ['red', 'green']}
};

//create and draw the chart from DIV
var chart = new google.visualization.GeoChart(document.getElementById('geochart'));
chart.draw(data, options);

I specified HU (for Hungary) as the region. For the region option, most of the ISO standards for country and location naming can be used. For example, typing in Hungary instead of HU will still work. I set the displayMode to be markers, which can have other values such as text and regions. I can also specify the colors that the displayed markers will use. The creation of the chart is the same, with a constructor that requires a div to work with.

Gauge Chart

Gauge charts need an extra package loaded by JSAPI called the gauge package. To load the extra dependency, I extended the list of packages for JSAPI to load:

google.load('visualization', '1', {'packages':['corechart','gauge']});

Besides the extra dependency, the creation of the Gauges can be done in the same way as with other charts. It has a wide range of options that include min and max values, as well as customizable regions (like the start and end of green, yellow and red regions). The number of ticks can also be customized.

var options = {
    width: 580,
    height: 320,
    min: 0,
    max: 65,
    greenFrom: 5,
    greenTo: 20,
    redFrom: 30,
    redTo: 60,
    yellowFrom: 20,
    yellowTo: 30,
    minorTicks: 5
};

//create and draw the chart from DIV
var chart = new google.visualization.Gauge(document.getElementById('gaugechart'));
chart.draw(data, options);

Posted 22 October, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Next Article

5 Contemporary Articles on Writing to Inspire You