Recently, I got a chance to use Google charts. The scenario was to implement Pie charts with the monthly data comparison. I had some other options like D3.js, chartjs, chartlistjs, smoothie charts etc.
Google charts are more flexible. Charts are rendered, using HTML5/SVG to provide the Cross-Browser compatibility and cross platform portability. It also includes VML for supporting older IE versions. No extra plugin is required to handle the different Browser support.
Google charts API contains a vast range of charts like Geo chart, Scatter chart, Column chart, Histogram, Bar chart, Combo chart, Area chart, Pie chart, Donut chart, Gauge etc.
Here, I would like to show some basic implementation of Google Pie chart.
- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
- <script type="text/javascript">
- google.charts.load('current', {
- 'packages': ['corechart']
- });
- google.charts.setOnLoadCallback(drawChart);
-
- function drawChart() {
- var data = google.visualization.arrayToDataTable([
- ['Task', 'Hours per Day'],
- ['Task 1', 112],
- ['Task 2', 200],
- ['Task 3', 500],
- ['Task 4', 100],
- ['Task 5', 250]
- ]);
- var options = {
- title: 'Test chart'
- };
- var chart = new google.visualization.PieChart(document.getElementById('viewchart'));
- chart.draw(data, options);
- }
- </script>
- <div id="viewchart" style="margin-top:6px;width: 540px; height: 450px;"></div>
Following steps needs to be performed for the chart implemention,
- Add the reference to JavaScript.
- We need to load corechart package along with Visualization API.
- setOnLoadCallback is a call back function, which will be called, when Google Visualization is loaded.
- drawChart function is responsible for generating the data and rendering PieChart.
Result of the code, given above is:
We can do customization on this chart like color change of the pie pieces by adding a code in the options variable:
- var options =
- {
- title: 'Test Chart',
- colors: ['#3A8FAB', '#AB563A', '#56AB3A', '#9C61B8', '#61B88F']
- };
Google charts provides an extreme level of customization. Moreover, this API doesn’t require any paid license. It supports modern as well as old Browsers like IE8.