devxlogo

Upgrade Your Website with Google Charts

Upgrade Your Website with Google Charts

With Google charts, displaying chart data on web pages has become very easy and stress-free. Many types of charts can be used, such as pie charts, line charts, histograms, scatter charts and many more. This web service is easily customizable and free. In this article, you will learn how to use to customize charts for your website.

Getting Started

The first step is to import the Charts API JavaScript:

            

The code above loads the required JavaScript files and initializes the API and should be placed inside the head element in HTML document. You will notice the drawChart callback function — that function contains the code which actually creates the chart. Finally, the div is created in the HTML part of the code at the place where you want to show the chart.

Pie Chart

In order to create any of the charts, we need to prepare the data that will be shown on the website. Each chart is actually a visualization of a table with multiple rows and columns. So, the data would be added to the chart as a table using Google charts API predefined functions. If we take the following table for example:

Then the data would be added to the chart like this:

// Initialize DataTable objectvar data = new google.visualization.DataTable();        // Create two columns – Beverage and Sold// String and number are column values’ data types        data.addColumn('string', 'Beverage');data.addColumn('number', 'Sold');// Add rows// Each line represents one row, where the first value is the first column’s value and the second value is the second column’s value        data.addRows([   ['Beer', 10],   ['Wine', 5],   ['Whiskey', 2],   ['Juice', 7],   ['Water', 6]]); 

Next step is to set chart options:

// Set chart optionsvar options = {'title': 'Today’s beverage sales',                'width': 700,                'height': 300};

After that, we need to draw the chart and show it on the web page:

// Draw the chart// Note that the data and options variables represent data and options set in the code above// chart_wrap is the id of the div where the chart will be displayedvar chart = new google.visualization.PieChart(document.getElementById('chart_wrap'));chart.draw(data, options); 

At this point, the chart is fully functioning and will be shown on the page. The complete code would look like this:

function drawChart() {       // Add the data to the chart       var data = new google.visualization.DataTable();              // Add columns      data.addColumn('string', 'Beverage');      data.addColumn('number', 'Sold');     // Add rows    data.addRows([       ['Beer', 10],       ['Wine', 5],       ['Whiskey', 2],       ['Juice', 7],       ['Water', 6]    ]);    // Set chart options    var options = {'title': 'Today’s beverage sales',                'width': 700,                'height': 300    };    // Draw the chart    var chart = new google.visualization.PieChart(document.getElementById('chart_wrap'));    chart.draw(data, options);}

The pie chart can have many additional options, such as creating a 3D chart, rotating it, creating a donut chart and many more. Check the list of all available options here.

Bar Chart

Creating a bar chart is very similar to creating a pie chart. Everything is the same, except the last two lines, which should be replaced with the following code:

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

Line Chart

Line chart is created by using the following drawChart function:

function drawChart() {        // Add the data to the chart        // First column are x axis values        // Second column are blue line y axis values        // Third column are red line y axis values        var data = google.visualization.arrayToDataTable([          ['Year', 'Profits', 'Expenses'],          ['2004',  1000,      400],          ['2005',  1170,      460],          ['2006',  660,       1120],          ['2007',  1030,      540]        ]);        // Set chart options        var options = {          title: 'Shop Performance'        };        // Draw the chart        var chart = new google.visualization.LineChart(document.getElementById('chart_wrap'));        chart.draw(data, options);}

Loading Data from JSON

Chart data can also be loaded from an external URL, whose response should be formatted in JSON. In that case, the drawChart function will be slightly different:

function drawChart() {      var jsonData = $.ajax({          url: "http://www.example.com/beverage_sales.json",          dataType:"json",          async: false }).responseText;       // Add the data to the chart       var data = new google.visualization.DataTable(jsonData);            // Set chart options    var options = {'title': 'Today’s beverage sales',                'width': 700,                'height': 300    };    // Draw the chart    var chart = new google.visualization.PieChart(document.getElementById('chart_wrap'));    chart.draw(data, options);}

This example uses the same data as the pie chart example above. The corresponding JSON file should look like this:

{  "cols": [        {"id":"","label":"Beverage","pattern":"","type":"string"},        {"id":"","label":"Sold","pattern":"","type":"number"}      ],  "rows": [        {"c":[{"v":"Beer","f":null},{"v":10,"f":null}]},        {"c":[{"v":"Wine","f":null},{"v":5,"f":null}]},        {"c":[{"v":"Whiskey","f":null},{"v":2,"f":null}]},        {"c":[{"v":"Juice","f":null},{"v":7,"f":null}]},        {"c":[{"v":"Water","f":null},{"v":6,"f":null}]}      ]}

Click Events

Google charts can detect click events on chart items and execute some code whenever an event occurs. This is done by adding a listener handle before drawing the chart:

function doSomethingOnClick() {                  // Get selected data row  var selectedItem = chart.getSelection()[0];    if (selectedItem) {    // Get first column value    var beverage_name = data.getValue(selectedItem.row, 0);    // Get second solumn value    var order_num = data.getValue(selectedItem.row, 1);       alert('Today ordered: ' + order_num + ' bottles of ' + beverage_name +  ' .');  }}// Add on click listener// Whenever someone clicks on a chart item, doSomethingOnClick function is executed				var listenerHandle = google.visualization.events.addListener(chart, 'select', doSomethingOnClick); 

Conclusion

Google charts is a very powerful web service. Examples that are shown in this article represent only basic functionality. For advanced usage, check the following site.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist