2D and 3D HTML5 charts using Google Charts API

Posted by: Suprotim Agarwal , on 9/2/2015, in Category HTML5 & JavaScript
Views: 41974
Abstract: Using Google Charts API to draw interactive 2D and 3D HTML5 charts

Charts help visualize data on your website. With the advancement in web technologies, you can create advanced charts using HTML5/JavaScript/SVG without the need to install any plugin in your browser. Not only are these charts interactive, you can even manipulate them on the fly, add notes, zoom in or out and perform many similar operations that are found in desktop versions.

 

A charting library makes all this and much more, very easy for us to implement in our applications.

Google provides a nice visualization library called Google Charts. It has a wide array of charts available to convey just about any data you can think of. The best part is the Google Chart API is free to use and most of the charts generated with the API are cross-browser compatible.

Here are some features of Google Charts:

  • Google Chart Types are JavaScript classes
  • There are many default Chart Types to use, some of them are – Bar, Pie, Scatter, Geo, Column, Histogram, Combo, Area, Stepped Area, Line, Bubble, Donut, Candlestick, Org chart and many more.
  • You can completely customize a chart by changing its look and feel
  • Google Charts expose events which can be exploited to make the Charts interactive
  • Since Google Charts are rendered using HTML5, they are cross-browser and cross-platform compatible.
  • Google Charts can be connected to any data source that supports the Chart Tools Datasource protocol. For any other data source, you can convert the data into csv and then use Google Charts to plot the data.

Creating a Bar Chart using Google Charts API

In this article we will create a Bar Chart using Google Charts. We will follow these steps:

1. Load the JSAPI AJAX API

2. Load some Google Chart libraries (Visualization API)

3. Set a callback to run when the Visualization API gets loaded

4. Create a callback function, list the data to be charted, instantiate the chart and load the chart with the data

5. Set Chart Options to customize your chart

6. Create a chart object with a div id and draw the chart with the data and options

7. In the web page, create a <div> with that id to display the Google Chart.

Let us get started. Create an empty HTML file called GoogleBarChart.html.

Step 1: Load the JSAPI Ajax API

The most common way to use Google Charts is using its simple JavaScript library that you can embed in your web page. We usually load a JavaScript API by referring to it in the <script> element. Google provides another way which is more efficient when compared to loading individual scripts. JSAPI is a powerful tool that allows you to load only those APIs that your page needs. Let us start by creating a <head> element and linking it to Google JSAPI.

<head>
    <title>Google Charts</title>
    <script src="https://www.google.com/jsapi"></script>
</head>

Once the Google AJAX API is loaded, its load() method becomes available which allows you to load additional APIs.

Step 2: Load Google Chart libraries

To load the chart libraries, we will use google.load() to programmatically loads only those libraries that your page needs. To do so, create an empty JavaScript file called chart.js inside ‘scripts’ folder and reference the file in your HTML as follows:

<head>
    <title>Google Charts</title>
    <script src="https://www.google.com/jsapi"></script>
    <script src="./scripts/chart.js"></script>
</head>

Now add the following code in chart.js

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

This piece of code requests the Visualization API from Google JSAPI and the CoreChart package.

The second parameter of google.load() is the version of the API which is in the form of VERSION.REVISION denoting a major version and revision number. Whenever a new feature or bug is fixed, the revision number increases. So if an API is currently on version 1.1.1, and the team does an update, the next version becomes 1.1.2. We are using 1.0 as it is the current production version and the most stable build.

The third parameter is the package. We are using corechart as it contains all the basic charts, including Bar and Pie. If you want to pass a chart not in the basic package for eg: the Guage chart, then all you need to do is the following:

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

Step 3: Set a callback to run when the Visualization API gets loaded

google.setOnLoadCallback(plotChart);

Step 4: Create a callback function, list the data to be charted, instantiate the chart and load the chart with the data.

We will define the callback function as follows:

function plotChart(){
..
}

Inside the callback function, now create the DataTable which will act as the Data Source for the chart. DataTables are 2D arrays. Just think of them as a Table in a Database having rows and columns. We will create two columns Country and Population and add some rows to it.

function plotChart(){
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Country');
    data.addColumn('number', 'Population');
    data.addRows([
        ['China', 1361512535],
        ['India', 1251695584],
        ['US', 321362789],
        ['Indonesia', 255993674],
        ['Brazil', 204259812]
    ]);
}

Step 5: Once the DataTable is created, inside the same callback function, set Chart Options to customize your chart. Over here we are specifying the title, width and height of the chart.

var options = {'title':'Population, 2015', 'width':800, 'height': 600};

Step 6: Create a chart object with a div id and draw the chart with the data and options

var chart = new google.visualization.BarChart(document.getElementById('googlechart'));
chart.draw(data,options);

Step 7: In the web page, create a <div> with that id to display the Google Chart.

<body>
    <div id="googlechart">
    </div>
</body>

Load the HTML File in the browser and you will find an interactive Bar chart in front of you, created effortlessly, with just a few lines of code.

google-bar-chart

Hover your mouse over one of the bars and you will find that the Chart is interactive

google-interactive-chart

Live Demo: https://www.dotnetcurry.com/demos/googlecharts/googlebarchart.html

 

Convert Bar Chart to Pie Chart

In order to convert this Bar chart into a Pie chart, just change this piece of code from:

var chart = new google.visualization.BarChart(document.getElementById('googlechart'));

to

var chart = new google.visualization.PieChart(document.getElementById('googlechart'));

And you have a nice interactive Pie chart

google-pie-chart

Similarly we can convert this chart into a Line chart. I leave this as an exercise for you to complete.

Convert a 2D chart to 3D chart

In order to convert this 2D chart to 3D, all you need to do is pass in “is3D” to true in options

var options = {'title':'Population, 2015', 
        'width':800, 'height': 600, 'is3D': true};

..and boom! You have an interactive 3D chart.

google-3d-chart

Live Demo: https://www.dotnetcurry.com/demos/googlecharts/google3dpiechart.html

 

Conclusion

We have barely scratched the surface of Google Charts and its capabilities. In future articles, I will demonstrate some exciting stuff we can do using Google Charts, like reading data from a spreadsheet and plotting it on a Chart, dynamically loading charts in a tab and so on.

If there is a feature you are looking to incorporate in your charts, make a request in the comments section and if possible, I will accommodate them in my upcoming articles.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!