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.
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.
draw() on
your visualization and pass in your data to draw your visualization on the 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! |
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>
Tip: You can develop a visualization using the Google Web Toolkit. See the GWT visualization page for more information.
Another Tip: You can download the goog.visualization API
class and method definitions to enable autocompletion in your IDE (code editor).
Download the file from http://www.google.com/uds/modules/gviz/gviz-api.js and
save it to your project. Most IDEs will index it automatically and provide
autocompletion. Note that the file might
not always be up to date; check the reference pages for
the most up to date API reference.
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:
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.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.
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.
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:
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.
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.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.<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>
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:
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:
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.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]
]);
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.
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.
Here are some optional steps you can take to add functionality or performance to your visualizations:
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;
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.
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.
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.
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.
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.
If your code doesn't seem to be working, here are some approaches that might help you solve your problems: