My favorites | English | Sign in

Try Google Chrome's developer tools New!

Google Visualization API

Using Visualizations

This page describes how to embed a non-gadgetized visualization in your web page. It assumes that you have the prerequisite knowledge listed in the Audience section of the Introduction Page.

Google visualizations can also be wrapped as Google Gadgets; to learn how to embed a gadgetized visualization in your page, see the Using Visualizations Gadgets page.

Contents

Overview

Here are the key steps for embedding a visualization in your page. You'll find a code snippet demonstrating all these steps below, followed by detailed information about each step.

  1. Add a <div> to your page. Your page must have an HTML element that will hold your visualization; typically you'll use a <div> in your page.
  2. Load your libraries. A visualization requires three libraries to be included or loaded on the page: the Google AJAX API; the Google Visualization API core; and a library for each type of visualization.
  3. Prepare your data. You'll need to prepare the data to visualize; this means either specifying the data yourself in code, or querying a remote site for data.
  4. Create an instance of your visualization. Instantiate your visualization by calling its constructor and passing in a reference to your <div> element.
  5. Draw your visualization. Call draw() on your visualization and pass in your data to draw your visualization on the page.
  6. There are various other optional steps you can take, such as handling user events or specifying visualization options. These are covered at the end of this page.

Here's a simple example of a page that loads and displays a pie chart. The resulting chart is shown below the snippet.

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    
      // Load the Visualization API and the piechart package.
      google.load('visualization', '1', {'packages':['piechart']});
      
      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawChart);
      
      // Callback that creates and populates a data table, 
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

      // Create our data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Task');
        data.addColumn('number', 'Hours per Day');
        data.addRows([
          ['Work', 11],
          ['Eat', 2],
          ['Commute', 2],
          ['Watch TV', 2],
          ['Sleep', 7]
        ]);

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
      }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Here's the visualization that this code creates.


The chart is interactive; try clicking on slices or legend entries.



Use the Code Playground's pie chart example to modify the JavaScript live, in your browser!

1. Add a <div> To Your Page

Your page must have an HTML element (typically a <div>) to hold your visualization. You must pass your visualization a reference to this element, so assign it an ID that you can use to retrieve a reference using document.getElementById(). Anything inside this element will be replaced by the visualization when it is drawn.

    <!--Div that will hold the pie chart-->
    <div id="my_chart_div"></div>

2. Load Your Libraries

A visualization requires three libraries: the Google AJAX API; the Google Visualization API; and the library for the visualization itself. Here is the general loading order:

  1. Include the Google AJAX API. This API is used to load the Google Visualization API library, the visualization libraries, and perform other importanttasks. This must always be loaded first; the next two libraries can be loaded in different orders (see the details below).
  2. Load the Google Visualization API. The Google Visualization API includes common classes and methods used to create and handle visualizations, for example: DataTable to hold your data; a query object for querying data providers; and error handlers to help you trap and display errors on the page.
  3. Load the visualization library. A specific visualization (for example, a pie chart or a line chart) is a JavaScript class that exposes methods specific to that visualization, plus a few common methods and events (such as draw() and select). Google-written visualizations and third-party visualizations are loaded differently. Your page can hold both.

Tip: The order and procedure of loading these libraries can be modified or tweaked for performance as described in the section Library Loading Enhancements below.

Include the Google AJAX API

The Google AJAX API is used to load other libraries and handle some core functionality such as event handling. This library defines the google.load() and google.setOnCallback() functions that you'll use next.

This library is loaded with the simple <script> tag shown here at the top of your page:

<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

Tip: If you want to load this API not at page load time, you must use the dynamic loading technique described in the section Library Loading Enhancements below.

Load the Google Visualization API

The Google Visualization API is a library that implements several classes and methods that you'll need to manipulate all visualizations, for example: the Query object for making data queries; the DataTable object that is used by a visualization to hold its data; error handlers, and so on. Everything in this library is in the google.visualization namespace. You can see complete documentation of this library in the Reference section.

Load the Google Visualization API by calling google.load('visualization', '1', <<google-visualization-packages>>). It must be done in a separate <script> tag after the AJAX API include. Here is a description of each of the method parameters:

  • 'visualization' - Loads the Google Visualization API.
  • '1' - Loads the current, stable version of the API. (If you are running a big web site with a lot of critical visualizations, you might occasionally want to try the experimental version; see Release Candidate for more details.)
  • <<google-package-list>> - Specifies which Google-authored visualizations to load, as described in the next section.

You must wait until the Google Visualization API is loaded before you can continue the rest of your coding. To be notified when the API is loaded, right after calling google.load(), call google.setOnloadCallback(your_callback_handler) (defined in the Google AJAX API), passing in the name of your function to call when the API is loaded. Your initialization function can be named anything you want. The AJAX API will call your function with no parameters when the Google Visualization API and the visualization libraries in google-package-list are loaded.

Here is an example of loading the Google Visualization API and a Google Pie Chart, and setting a callback function named drawChart:

<script type="text/javascript">
  // Load the Visualization API and the piechart package.
  google.load('visualization', '1', {'packages':['piechart']});

  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(drawChart);
  
  function drawChart() {
    // Everything is loaded. Lets draw our chart...
    ...
  }
<script>

Tip: You can slightly improve the performance of this load by using auto-loading as described in the section Library Loading Enhancements below.

Load the Visualization Library

Finally, you must load your visualization libraries. You can see a list of available visualizations in the Google Visualization gallery.

Visualizations can be authored by Google or by third-parties. Google-authored visualizations are loaded from the Google web site; third-party visualizations are loaded from the visualization provider's web site; however, both kinds are listed in the Google visualization gallery. Visualizations are loaded differently, depending on who authored them. A visualization's documentation should describe which technique to use.

Warning: Google highly discourages using any visualization not listed on the Google web site.

You can load any number or combination of Google and/or third-party visualizations on the same page. Note that you only need to load a library once, no matter how many times it's used on the page (that is, even if you have five pie charts on the page, you need only load the library once). Here is how to load either type of visualization:

  • Google-authored visualizations - If the visualization is authored by Google, you will load the visualization library as part of the google.load() call described earlier to load the Visualization API. The visualizations to load are listed in the <<google-package-list>> parameter in the format {'packages':[list_of_packages]}, where list_of_packages is a comma-separated list of one or more package names, in quotes. The package names are given in the documentation for a visualization.
  • Third-party visualizations - If the visualization is provided by a third party, you'll use a separate<script src="somewebsite.com">include to load that visualization library. The visualization documentation should make clear the location to use as the src attribute. Note that although third-party visualizations are hosted outside the Google domain, Google requires all third parties to sign an agreement respecting users' privacy and security in order to post their visualization to our galleries.

Here's an example of loading both a Google visualization and a third-party visualization:

<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<!--Load a third-party visualization-->
<script type="text/javascript" src="http://www.example.com/time_travel_visualization.js"></script>
<script type="text/javascript">

  //Load the Visualization API and the Google Pie Chart visualization
  google.load('visualization', '1', {'packages':['piechart']});

  // Load multiple Google packages:
  // google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']});
  ...
</script>

3. Prepare Your Data

When the Visualization API has been loaded, google.setOnLoadCallback() will call your handler function, so you know that all the required helper methods and classes will be ready for you to start preparing your data.

A visualization stores the data that it visualizes as two-dimensional data table with rows and columns. Cells are referenced by (row, column) where row is a zero-based row number, and column is either a zero-based column index or a unique ID that you can specify.

A column has up to three properties:

  • Data type [Required] - The type of data in that column: for example: string or boolean. All data in every column must be the same type (null is also allowed as a cell value). The following JavaScript data types are allowed: boolean, string, number, date.
  • ID [Optional]- A unique alphanumeric ID that can be used instead of a column index to refer to this column. If you don't specify an ID, you'll have to use the column index to refer to a column.
  • Label [Optional]- A user-friendly label for the column. Many charts display the label as chart legend or axis label. For example: "Employee Name" or "Language".

Here's a representation of a populated two-column data table:

column 0      |  column 1
type: string  |  type: number
label: Task   |  label: Hours per Day
'Work'        |   11
'Eat'         |    2
'Commute'     |    2
'Watch TV'    |    2
'Sleep'       |    7

Note how these columns don't have an ID assigned; in this table, you can only refer to columns by index number, because no ID was assigned.

Different visualizations expect data tables in different formats; for example, a pie chart might expect a two-column table with a string column and a number column, where each row describes a label and a size for one slice. A line chart, however, might expect two numeric columns, where the two columns describe the X and Y values of a point. Read your visualization's documentation to know the format of the data table that it expects.

A data table is implemented in JavaScript as either a google.visualization.DataTable object or a google.visualization.DataView object (defined in the Google Visualization API). A DataTable is used to create the original data table. A DataView is a convenience class that provides a read-only view of a DataTable in which you can hide or reorder rows or columns quickly without modifying the underlying data. You can see an example of using a DataView to manipulate a DataTable in the Visualization Playground.

There are two ways to create/populate your visualization's data table:

  • Query a data provider. A data provider is another site that returns a populated DataTable in response to a request from your code. Some data providers also accept SQL-like query strings to sort or filter the data. See Data Queries for more information and an example of a query.
  • Create and populate your own DataTable by hand. You can populate your DataTable in code on your page. The simplest way to do this is to create a DataTable object without any data and populate it by calling addRows() on it. You can also pass a JavaScript literal representation of the data table into the DataTable constructor, but this is more complex and is covered on the reference page.

The following code demonstrates creating the previous table by hand, using the addRows() method:

        var data = new google.visualization.DataTable();
        // Declare columns and rows.
        data.addColumn('string', 'Task');  // Column 0 is type string and has label "Task".
        data.addColumn('number', 'Hours per Day'); // Column 1 is type number and has label "Hours per Day".
        
        // Add data.
        data.addRows([
          ['Work', 11],
          ['Eat', 2],
          ['Commute', 2],
          ['Watch TV', 2],
          ['Sleep', 7]
          ]);

4. Create an Instance of Your Visualization

After you have created your data, you can instantiate your visualization object. A visualization constructor typically takes one parameter: a reference to the DOM element in which to draw the visualization.

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

Visualizations are exposed as a JavaScript class. All visualizations exposes a few standard methods (such as draw() and a constructor), plus any number of custom methods and properties that should be described in the documentation. Although all visualization are wrapped by a JavaScript library, the visualizations are exposed on the page in a variety of different formats: for example: static HTML, GIF image, or a Flash movie. Some visualizations let you choose the format, but most don't.

After instantiating your visualization, you can perform a few optional steps such as adding event listeners (for example, user-click listeners) or error handling. See Handling Visualization Events or Displaying Errors Nicely below for more information.

5. Draw Your Visualization

Call the draw() method of the visualization to render it on your page inside the page element that you specified.

The draw() method takes two parameters: a DataTable or DataView (required) and an options parameter (optional). The options parameter is used to set useful options in your visualization, such as the visualization width, height, or colors. You can find more details about this parameter below, under Specifying Visualization Options.

You should call the draw() method every time you change the data or the options and want to update the chart.

The following example calls the piechart object's draw() method, specifying a width, height, a 3-D version, and a title:

 chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});

Again, not all visualizations support these specific options; check your visualization documentation for details.

Optional Steps

Here are some optional steps you can take to add functionality or performance to your visualizations:

 

Specifying Visualization Options

Visualizations usually support custom options appropriate to that visualization. For example, the table visualization supports a sortColumn option to specify the default sorting column, and the pie chart visualization supports a colors option that lets you specify slice colors. Each visualization's documentation should describe the options that it supports.

You will pass your options in as an optional second parameter to the visualization's draw() method described previously. You specify options by creating an object with properties specific to each visualization type. For example, the pie chart supports the following options, among others:

Option Type Description
is3D boolean If set to true, displays a three-dimensional chart.
title string Text to display above the chart.
width number Width of the chart, in pixels.
height number Height of the chart, in pixels.
... ... ...

The following example demonstrates creating an options object that specifies all of these properties. You can create an options object using either the JavaScript object literal notation, or by using standard object assignment. Both methods are shown here:

var literalOptions = {width: 400, height: 240, is3D: true, title: 'My Daily Activities'};

var assignedOptions = {};
  assignedOptions.is3D=true;
  assignedOptions.title = 'My Daily Activities';
  assignedOptions.width = 400;
  assignedOptions.height = 240;

Handling Visualization Events

Google visualizations can fire events that you can register to receive. Events can be triggered by user actions (for example, a user clicking on a chart) or self-generated (for example, a 10 second timer). You can register a JavaScript method to be called whenever a specific event is fired. To learn more about handling events, see Handling Events. One common event that you might want to listen for is the ready event, which is fired by many visualizations when they are ready to begin handling method calls.

Library Loading Enhancements

The loading sequence shown above works well if visualization load time isn't crucial to your page, or if you always want to load the libraries when the page loads. However, if you want to load the libraries only under certain conditions (for example, when the user takes a certain action), or if you have several visualizations on a page and that is causing a slow load time, there are some tricks you can do to speed things up.

  • Dynamic Loading - You can load the AJAX API (and Google visualization libraries) after page load time by using dynamic loading. For example, if you only want to show a visualization if a user clicks a tab on the page. Note that the loader keeps track of what has already been loaded, so if you try loading the same visualization package multiple times it won't bother reloading it each time.
  • Auto-Loading - If load time for your page is very important, you can reduce a round-trip request to the Google server by using auto-loading to load the Google AJAX API, the Google Visualization API, and all Google-authored visualizations. This saves the browser one round-trip call to Google, which can speed up pages a bit for the user. See the linked section for details.

Displaying Errors Nicely

If your data query returns an error, or some other error occurs, the Visualization API provides helper methods to display your errors nicely on the page. See Error Display for more information.

Custom Data Table Properties

A very few visualizations support custom properties for cells, rows, or columns in a DataTable or a DataView. As an example, see the className cell property in the table visualization.

Forcing Visualization Language Selection

Visualizations can support localized versions. Usually this means that fixed strings displayed by the visualization will be translated into other languages (for example, instead of "Close" it would display "Fermer"), but it is possible that a visualization could also support more advanced localization, such as displaying numbers in different formats used by different languages, or even different designs or color schemes.

Normally, a visualization that supports localization detects the language settings of your browser, and changes languages appropriately. However, you can override the browser choice by specifying a language in your google.load() method as shown here (this will load the French version of the Motion Chart visualization):

google.load('visualization',  '1', {'packages': ['motionchart'], 'language' : 'fr'})

The language property is a two-letter ISO 639-1 language code.

If a visualization does not support the language detected in the browser, or specified by google.load(), it will usually default to English.

Troubleshooting

If your code doesn't seem to be working, here are some approaches that might help you solve your problems:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Search the Google Visualization API discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

More Information

  • See the API Reference page for more information about what methods all visualizations expose. (Note that these are just recommendations; compliance with this model is not checked.)
  • See the Query Language reference to learn more about the query language you can use to filter or manipulate data populated by a data provider.
  • See Related Documentation Reference for links to more resources about gadgets, the Google AJAX API, and more.
  • See More Examples for more examples of embedding visualizations
  • See the Visualization Gallery for a list of visualizations that you can embed.