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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

6 Tips for Setting Up a Decentralized Exchange

6 Tips for Setting Up a Decentralized Exchange

There’s no doubt that cryptocurrency is a complex and divisive topic in the modern financial landscape. There are those who are convinced that it’s nothing more than a bubble, but both who are well-informed are able to see the ways in which cryptocurrency can help them both build their fortune

user experience with someone on their phone

5 Ways to Improve Your Customers’ User Experience

They say you can’t judge a book by its cover, but just because they say that doesn’t mean it’s true. Consider how often you choose one sort of product over another just because it appeals to you. Then think about how often you’ve stopped using something because, simply put, it

How to Manage Your Finances after Buying a Home

How to Manage Your Finances after Buying a Home

Buying a home is a milestone in the journey of life – it’s one way to invest your money and create lasting memories. Now you know everything about a home purchase, home mortgage, and what is a conventional 97 loan but do you know what’s next after you sign the

Windows Logging is one of the vital aspects of any Windows system administration. However, it is mostly overlooked until the system develops a problem. This is because logs contain important information needed to troubleshoot and resolve system issues.

The Fundamentals of Windows Logging

Windows Logging is one of the vital aspects of any Windows system administration. However, it is mostly overlooked until the system develops a problem. This is because logs contain important information needed to troubleshoot and resolve system issues. Without it, tech experts might find it difficult to track a computer’s

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns Interstitial ads are full-screen advertisements that appear to grasp the attention of on-site prospects, creating opportunities for brands seeking effective ways to communicate their proposition of value. With such an attention-grabbing format and high-impact visuals, it’s no wonder why interstitial advertising is proving