We will follow 6 steps to understand our code to draw the chart.
Load the library
Prepare data in the required format
Set the options of the chart
Instantiate the chart class
Set any event listener ( optional )
Draw the chart
Load the library
The library is hosted by google. We need to one time call this library even we have multiple charts in the same page. This is how we will link to the loader library.
To display the chart different types of data tables are used. For Pie chart and Bar chart two column tables are used.
Number of tutorials at plus2net.com
language
Nos
PHP
300
JavaScript
200
MySQL
100
JQuery
200
HTML
200
ASP
100
We can collect data from MySQL table by using PHP and then match the input data format required for Chart. We can use any Backend script and we just require to match the required format to display the charts.
We can use a two dimensional array in JavaScript to give this input data.
var tutorials = [['PHP', 300],['MySQL', 100],['JavaScript', 200],
['JQuery',200],['HTML',200],['ASP',100]]
We will match the required format by displaying the array elements.
for(i = 0; i < tutorials.length; i++)
data.addRow([tutorials[i][0], tutorials[i][1]]);
Why through array ?
We declared the array as global variable and used the same to display the chart. The array we create can be created by using data from any database ( say MySQL) or by reading a csv file or by using Json string or from user input fields. Demo of Redrawing chart with user inputs → We can modify data stored inside the array and change the chart dynamically by modifying the array data.
Pie Chart using array of data→
Options of the chart
Options can be added to chart, here based on the chart type we can set different options. Here are some common options.
var options = {'title':'plus2net',
'width':450,
'height':350};
Instantiate the chart class
In our HTML part we kept one div tag with id='chart_div'. We get a handler and using this we will pass the data and options.
var chart=new google.charts.Bar(document.getElementById('chart_div'));
Set any event listener ( optional )
On click or select of any element of the chart we will display more details. This part we will try separately by using a demo script.
Adding Event Listener to Chart →
Draw the chart
var chart=new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
We passed data and options to our Chart by using the handler.
Let us check some popular types of chart we can develop.