This page lists the objects exposed by the Google Visualization API, and the standard methods exposed by all visualizations.
Note: The Google Visualization API namespace is google.visualization.*
Represents a two-dimensional, mutable table of values. To make a read-only copy
of a DataTable (optionally filtered to show specific values, rows,
or columns), create a DataView.
Each column is assigned a data type, plus several optional properties including an ID, label, and pattern string. In addition, you can assign custom properties (name/value pairs) to any cell, row, column, or the entire table. These custom properties are defined and consumed by some visualizations, as described in their documentation. For an example of a custom property, see the className property consumed by the Table visualization.
See also: QueryResponse.getDataTable
The DataTable class has two constructors:
google.visualization.DataTable() // Create an empty DataTable instance google.visualization.DataTable(data, version) // Create a populated DataTable instance
Parameters
Details
The DataTable object is used to hold the data passed into a visualization.
A DataTable is a basic two-dimensional table. All data in each column
must have the same data type. Each column has a descriptor that includes its data
type, a label for that column (which might be displayed by a visualization), and
an ID, which can be used to refer to a specific column (as an alternative to using
column indexes). The DataTable object also supports a map of arbitrary properties
assigned to a specific value, a row, a column, or the whole DataTable. Visualizations
can use these to support additional features; for example, the Table
visualization uses custom properties to let you assign arbitrary class
names or styles to individual cells.
Each cell in the table holds a value. Cells can have a null value, or a value of the type specified by its column. Cells optionally can take a "formatted" version of the data; this is a string version of the data, formatted for display by a visualization. A visualization can (but is not required to) use the formatted version for display, but will always use the data itself for any sorting or calculations that it makes (such as determining where on a graph to place a point). An example might be assigning the values "low" "medium", and "high" as formatted values to numeric cell values of 1, 2, and 3.
To add data rows after calling the constructor, you can call either addRow() for
a single row, or addRows() for
multiple rows. You can add columns as well by calling the addColumn() methods.
There are removal methods for rows and columns as well,
but rather than removing rows or columns, consider creating a DataView that
is a selective view of the DataTable.
You can create a DataTable either by calling the constructor
without parameters and then adding values by calling the addColumn()/addRows() methods listed below, or by passing in a populated JavaScript literal object to
initialize it. Both methods are described below. Which one should you use?
The following example demonstrates creating and populating a two column, three row DataTable in JavaScript. You might use this on a page hosting a visualization to create the data for that visualization.
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', {v:7, f:'7.000'}]
]);
You can also populate a table by passing in an object that hosts data when you
instantiate it by specifying the data object.
This object is a JavaScript object formatted in a specific way (described below
in Format of the data Parameter Object). The
following example demonstrates instantiating and populating a DataTable with a
literal string, with the same data as shown in the JavaScript example above:
var dt = new google.visualization.DataTable(
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
},
0.6
)
You can initialize a DataTable by passing a JavaScript string literal object into the data parameter. We'll call this object the data object. You can code this object by hand, according to the description below, or you can use a helper Python library if you know how to use Python, and your site can use it. However, if you want to construct the object by hand, this section will describe the syntax.
First, let's show an example of a simple JavaScript object describing a table with three rows and three columns (String, Number, and Date types):
{
cols: [{id: 'A', label: 'NEW A', type: 'string'},
{id: 'B', label: 'B-label', type: 'number'},
{id: 'C', label: 'C-label', type: 'date'}
],
rows: [{c:[{v: 'a'}, {v: 1.0, f: 'One'}, {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}]},
{c:[{v: 'b'}, {v: 2.0, f: 'Two'}, {v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}]},
{c:[{v: 'c'}, {v: 3.0, f: 'Three'}, {v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}]}
],
p: {foo: 'hello', bar: 'world!'}
}
Now let's describe the syntax:
The data object consists of two required top-level properties, cols and rows,
and an optional p property that is a map of arbitrary values.
Note: All property names and string constants
shown are case-sensitive. Also, properties described as taking a string value should
have their value enclosed in quotation marks. For example, if you wish to specify
the type property as being number, it would be expressed like this: type:
'number' but the value itself, as numeric, would be expressed like this:
v: 42
cols property
cols is
an array of objects describing the ID and type of each column.
Each property is an object with the following properties (case-sensitive):
type [Required] Data type of the data in the column.
Supports the following string values (examples include the v: property, described
later):
v:'true'v:7 , v:3.14,
v:-55v:'hello'v:new Date(2008, 0, 15)v:new
Date(2008, 0, 15, 14, 30, 45)v:[8, 15, 0], v:
[6, 12, 1, 144]id [Optional] String ID of the column. Must be unique
in the table. Use basic alphanumeric characters, so the host page does not
require fancy escapes to access the column in JavaScript. Be careful not to choose
a JavaScript keyword. Example: id:'col_1'label [Optional] String value that some visualizations
display for this column. Example: label:'Height'pattern [Optional] String pattern used to format
date or time data. The formatting syntax is the same as that exposed by the
Java SimpleDateFormat class. Example: pattern:'EEE, MMM d,
yyyy'p [Optional] An object that is a map of custom values
applied to the cell. These values can be of any JavaScript type. If your visualization
supports any cell-level properties, it will describe them; otherwise, this property
will be ignored. Example: p:{style: 'border: 1px solid
green;'}.cols Example
cols: [{id: 'A', label: 'NEW A', type: 'string'},
{id: 'B', label: 'B-label', type: 'number'},
{id: 'C', label: 'C-label', type: 'date'}]
The rows property holds an array of row objects.
Each row object has
one required property called c,
which is an array of cells in that row. It also has an optional p property
that defines a map of arbitrary custom values to assign to the whole row. If your
visualization supports any row-level properties it will describe them; otherwise,
this property will be ignored.
Each cell in the table is described by an object with the following properties:
v [Optional] The cell value. The data type should
match the column data type. If null, the whole
object should be empty and have neither v nor f properties.f [Optional] A string version of the v value,
formatted for display. The values should match, so if you specify Date(2008,
0, 1) for v,
you should specify "January 1, 2008" or some such string for this property.
This value is not checked against the v value. The visualization
will not use this value for calculation, only as a label for display. If omitted,
a string version of v will be used.p [Optional] An object that is a map of custom values
applied to the cell. These values can be of any JavaScript type. If your visualization
supports any cell-level properties, it will describe them; otherwise, this property
will be ignored. Example: p:{style: 'border:
1px solid green;'}.Cells in the row array should be in the same order as their column descriptions
in cols.
To indicate a null cell, you can specify null, leave a blank for a
cell in an array, or omit trailing array members.
So, to indicate a row with null for the first two cells, you could specify [
, , {cell_val}] or [null,
null, {cell_val}].
Here is a sample table object with three columns, filled with three rows of data:
{
cols: [{id: 'A', label: 'NEW A', type: 'string'},
{id: 'B', label: 'B-label', type: 'number'},
{id: 'C', label: 'C-label', type: 'date'}
],
rows: [{c:[{v: 'a'}, {v: 1.0, f: 'One'}, {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}]},
{c:[{v: 'b'}, {v: 2.0, f: 'Two'}, {v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}]},
{c:[{v: 'c'}, {v: 3.0, f: 'Three'}, {v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}]}
]
}
p property
The p property is a map of custom values
applied to the whole DataTable. These values can be of any JavaScript type.
If your visualization supports any datatable-level properties, it will describe
them; otherwise, this property will be ignored. Example: p:{className:
'myDataTable'}.
| Method | Return Value | Description |
|---|---|---|
addColumn(type [,label [,id]]) |
number | Adds a new column to the data table, and returns the
index of the new column.
All the cells of the new column are assigned a
See also: getColumnId getColumnLabel getColumnType insertColumn |
| number | Adds a new row to the data table, and returns the index of the new row.
Examples:
data.addRow(); // Add an empty row
data.addRow(['Hermione', new Date(1999,0,1)]); // Add a row with a string and a date value.
// Add a row with two cells, the second with a formatted value.
data.addRow(['Hermione', {v: new Date(1999,0,1),
f: 'January First, Nineteen ninety-nine'}]);
|
|
addRows(numOrArray) |
number | Adds new rows to the data table, and returns the index of the last added row. You can call this method to create new empty rows, or with data used to populate the rows, as described below.
Example: data.addRows([['Ivan', new Date(1977,2,28)], ['Igor', new Date(1962,7,5)], ['Felix', new Date(1983,11,17)]]); See also: insertRows |
clone() |
DataTable | Returns a clone of the data table. The result is a deep copy of the data table except for the cell properties, row properties, table properties and column properties, which are shallow copies. |
getColumnId(columnIndex) |
string | Returns the identifier of a given column specified by the column index in
the underlying table. For data tables that are retrieved by queries, the column identifier is set by the data source, and can be used to refer to columns when using the query language. See also: Query.setQuery |
getColumnLabel(columnIndex) |
string | Returns the label of a given column specified by the column index in the
underlying table. The column label is typically displayed as part of the visualization. For example the column label can be displayed as a column header in a table, or as the legend label in a pie chart. For data tables that are retrieved by queries, the column label is set by the data source, or by the label clause of the
query language.
See also: setColumnLabel |
getColumnPattern(columnIndex) |
string | Returns the formatting pattern used to format the values of the specified column.
For data tables that are retrieved by queries, The column pattern is set
by the data source, or by the |
getColumnProperty(columnIndex, name) |
Object | Returns the value of a named property, or
See also: setColumnProperty setColumnProperties |
getColumnRange(columnIndex) |
Object | Returns the minimal and maximal values of values in a specified column. The returned
object has properties |
getColumnType(columnIndex) |
string | Returns the type of a given column specified by the column index.
The returned column type can be one of the following: |
getDistinctValues(columnIndex) |
Array of Objects | Returns the unique values in a certain column, in ascending order.
The type of the returned objects is the same as that returned by the |
getFilteredRows(filters) |
Array of numbers |
Returns the row indexes for rows that match all of the given filters. The indexes are returned in ascending order.
Example: |
getFormattedValue(rowIndex, columnIndex) |
string | Returns the formatted value of the cell at the given row and column indexes.
For more on formatting column values see the query language reference. See also: setFormatedValue |
getNumberOfColumns() |
number | Returns the number of columns in the table. |
getNumberOfRows() |
number | Returns the number of rows in the table. |
getProperty(rowIndex, columnIndex, name) |
Object | Returns the value of a named property, or
See also: setCell setProperties setProperty |
getRowProperty(rowIndex, name) |
Object | Returns the value of a named property, or
See also: setRowProperty setRowProperties |
getSortedRows(sortColumns) |
Array of numbers | Returns a sorted version of the table without modifying the order of the
underlying data. To permanently sort the underlying data, call
The returned value is an array of numbers, each number is an index
of a DataTable row. Iterating on the DataTable rows by the order of the
returned array will result in rows ordered by the specified Note that the sorting is guaranteed to be stable: this means that if you
sort on equal values of two rows, the same sort will return the rows in
the same order every time. Example: To iterate on rows ordered by the third column, use:
var rowInds = data.getSortedRows([{column: 2}]);
for (var i = 0; i < rowInds.length; i++) {
var v = data.getValue(rowInds[i], 2);
}
|
getTableProperty(name) |
Object | Returns the value of a named property, or
See also: setTableProperties setTableProperty |
getValue(rowIndex, columnIndex) |
object | Returns the value of the cell at the given row and column indexes.
The type of the returned value depends on the column type (see getColumnType):
|
insertColumn(columnIndex, type [,label [,id]]) |
None | Inserts a new column to the data table, at the specifid index. All existing columns at or after the specified index are shifted to a higher index.
See also: addColumn |
insertRows(rowIndex, numberOrArray) |
None | Insert the specified number of rows at the specified row index.
See also: addRows |
removeColumn(columnIndex) |
None | Removes the column at the specified index.
See also: removeColumns |
removeColumns(columnIndex, numberOfColumns) |
None | Removes the specified number of columns starting from the column at the specified index.
See also: removeColumn |
removeRow(rowIndex) |
None | Removes the row at the specified index.
See also: removeRows |
removeRows(rowIndex, numberOfRows) |
None | Removes the specified number of rows starting from the row at the specified index.
See also: removeRow |
setCell(rowIndex, columnIndex, value [, formattedValue [, properties]]) |
None | Sets the value, and optionally the formatted value and properties, of a cell. To simply change the cell value, use setValue
|
setColumnLabel(columnIndex, label) |
None | Sets the label of a column.
See also: getColumnLabel |
setColumnProperty(columnIndex, name, value) |
None | Sets a single column property. Some visualizations support row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setColumnProperties getColumnProperty |
setColumnProperties(columnIndex, properties) |
None | Sets multiple column properties. Some visualizations support row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setColumnProperty getColumnProperty |
setFormattedValue(rowIndex, columnIndex, formattedValue) |
None | Sets the formatted value of a cell.
See also: getFormattedValue |
setProperty(rowIndex, columnIndex, name, value) |
None | Sets a cell property. Some visualizations support row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setCell setProperties getProperty |
setProperties(rowIndex, columnIndex, properties) |
None | Sets multiple cell properties. Some visualizations support row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setCell setProperty getProperty |
setRowProperty(rowIndex, name, value) |
None | Sets a row property. Some visualizations support row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setRowProperties getRowProperty |
setRowProperties(rowIndex, properties) |
None | Sets multiple row properties. Some visualizations support row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setRowProperty getRowProperty |
setTableProperty(name, value) |
None | Sets a single table property. Some visualizations support table, row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setTableProperties getTableProperty |
setTableProperties(properties) |
None | Sets multiple table table. Some visualizations support table, row, column, or cell properties to modify their display or behavior; see the visualization documentation to see what properties are supported.
See also: setTableProperty getTableProperty |
setValue(rowIndex, columnIndex, value) |
None | Sets the value of a cell. In addition to overwriting any existing cell value, this method will also clear out any formatted value and properties for the cell.
See also: setCell, setFormattedValue, setProperty, setProperties |
sort(sortColumns) |
None | Sorts the rows, according to the specified sort columns.
The DataTable is modified by this method.
See getSortedRows() for a description of the sorting details. This method
does not return the sorted data.See also: getSortedRows Example: To sort by the third column and then by the second column, use: data.sort([{column: 2}, {column: 1}]); |
A read-only view of an underlying DataTable.
A DataView allows selection of only a subset of the columns and/or rows. It
also allows reordering columns/rows, and duplicating columns/rows.
A view is a live window on the underlying DataTable, not a static snapshot of
data. However, you still should must be careful when changing the structure of
the table itself, as described here:
setRows() or hideRows() methods) your
behavior might be unexpected.It is also possible to create a DataView on an underlying DataView. Note that whenever an underlying table or view is mentioned, it refers to the level immediately below this level. In other words, it refers to the data object used to construct this DataView.
You can combine DataView.getFilteredRows() with DataView.setRows() to create
a DataView with an interesting subset of data, as shown here:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Employee Name');
data.addColumn('date', 'Start Date');
data.addRows(6);
data.setCell(0, 0, 'Mike');
data.setCell(0, 1, new Date(2008, 1, 28));
data.setCell(1, 0, 'Bob');
data.setCell(1, 1, new Date(2007, 5, 1));
data.setCell(2, 0, 'Alice');
data.setCell(2, 1, new Date(2006, 7, 16));
data.setCell(3, 0, 'Frank');
data.setCell(3, 1, new Date(2007, 11, 28));
data.setCell(4, 0, 'Floyd');
data.setCell(4, 1, new Date(2005, 3, 13));
data.setCell(5, 0, 'Fritz');
data.setCell(5, 1, new Date(2007, 9, 2));
// Create a view that shows everyone hired since 2007.
var view = new google.visualization.DataView(data);
view.setRows(view.getFilteredRows([{column: 1, minValue: new Date(2007, 0, 1)}]));
var table = new google.visualization.Table(document.getElementById('test_dataview'));
table.draw(view, {sortColumn: 1});
google.visualization.DataView(data)
Parameters
dataDataTable or DataView used to initialize the view.
By default, the view contains all the columns and rows in the
underlying data table or view, in the original order. To hide or show rows or
columns in this view, call the appropriate set...() or hide...() methods. See also:
setColumns(), hideColumns(), setRows(), hideRows().
The Google Visualization API provides formatters that can be used to reformat data in a visualization. These formatters change the formatted value of the specified column in all rows. Note that it does not modify the underlying values; just the formatted values. So, for example, the displayed value would be "$1,000.00" but the underlying value would still be "1000". Formatters can only affect one column at a time; to reformat multiple columns, apply a formatter to each column that you want to change.
Important: Formatters can only be used with a
DataTable; they cannot be used with a DataView (DataView objects are read-only).
Here are the general steps for using a formatter:
DataTable object.formatter.Format(table, colIndex),
passing in the DataTable and the (zero-based) column number of the data
to reformat.allowHtml option, you should set it to
true.Here is an example of changing the formatted date values of a date column to use a long date format ("January 1, 2009"):
var data = new google.visualization.DataTable();
data.addColumn('string', 'Employee Name');
data.addColumn('date', 'Start Date');
data.addRows(3);
data.setCell(0, 0, 'Mike');
data.setCell(0, 1, new Date(2008, 1, 28));
data.setCell(1, 0, 'Bob');
data.setCell(1, 1, new Date(2007, 5, 1));
data.setCell(2, 0, 'Alice');
data.setCell(2, 1, new Date(2006, 7, 16));
// Create a formatter.
// This example uses object literal notation to define the options.
var formatter = new google.visualization.DateFormat({formatType: 'long'});
// Reformat our data.
formatter.format(data, 1);
// Draw our data
var table = new google.visualization.Table(document.getElementById('dateformat_div'));
table.draw(data, {showRowNumber: true});
Most formatters expose the following two methods:
| Method | Description |
|---|---|
google.visualization.formatter_name(options) |
Constructor, where formatter_name is a specfic formatter class name.
// Object literal technique
var formatter = new google.visualization.DateFormat({formatType: 'long', timeZone: -5});
// Equivalent property setting technique
var options = new Object();
options['formatType'] = 'long';
options['timeZone'] = -5;
var formatter = new google.visualization.DateFormat(options);
|
format(data, colIndex) |
Reformats the data in the specified column.
|
The Google Visualization API provides the following formatters:
| Formatter Name | Description |
|---|---|
| ArrowFormat | Adds an up or down arrow, indicating whether the cell value is above or below a specified value. |
| BarFormat | Adds a colored bar, the direction and color of which indicates whether the cell value is above or below a specified value. |
| ColorFormat | Colors a cell according to whether the values fall within a specified range. |
| DateFormat | Formats a Date or DateTime value in several different ways, including "January 1, 2009," "1/1/09" and "Jan 1, 2009." |
| NumberFormat | Formats various aspects of numeric values. |
| PatternFormat | Concatenates cell values on the same row into a specified cell, along with arbitrary text. |
Adds an up or down arrow to a numeric cell, depending on whether the value is above or below a specified base value. If equal to the base value, no arrow is shown.
ArrowFormat supports the following options, passed in to the constructor:
| Option | Description |
|---|---|
base |
A number indicating the base value, used to compare against the cell value. If the cell value is higher, the cell will include a green up arrow; if the cell value is lower, it will include a red down arrow; if the same, no arrow. |
var data = new google.visualization.DataTable();
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues Change');
data.addRows(5);
data.setCell(0, 1, 12, '12.0%');
data.setCell(1, 0, 'Sports');
data.setCell(1, 1, -7.3, '-7.3%');
data.setCell(2, 0, 'Toys');
data.setCell(2, 1, 0, '0%');
data.setCell(3, 0, 'Electronics');
data.setCell(3, 1, -2.1, '-2.1%');
data.setCell(4, 0, 'Food');
data.setCell(4, 1, 22, '22.0%');
var table = new google.visualization.Table(document.getElementById('arrowformat_div'));
var formatter = new google.visualization.ArrowFormat();
formatter.format(data, 1); // Apply formatter to second column
table.draw(data, {allowHtml: true, showRowNumber: true});
Adds a colored bar to a numeric cell indicating whether the cell value is above or below a specified base value.
BarFormatter supports the following options, passed in to the
constructor:
| Option | Description |
|---|---|
base |
A number that is the base value to compare the cell value against. If the cell value is higher, it will be drawn to the right of the base; if lower, it will be drawn to the left. Default value is 0. |
colorNegative |
A string indicating the negative value section of bars. Possible values are 'red', 'green' and 'blue'; default value is 'red'. |
colorPositive |
A string indicating the color of the positive value section of bars. Possible values are 'red', 'green' and 'blue'. Default is 'blue'. |
drawZeroLine |
A boolean indicating if to draw a 1 pixel dark base line when negative values are present. The dark line is there to enhance visual scanning of the bars. Default is 'false'. |
max |
The maximum number value for the bar range. By default, it is the highest value in the table. |
min |
The minimum number value for the bar range. By default, it is the lowest value in the table. |
showValue |
If true, shows values and bars; if false, shows only bars. Default, it is true. |
width |
Thickness of each bar, in pixels. By default, it is 100. |
var data = new google.visualization.DataTable();
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues');
data.addRows(6);
data.setCell(0, 0, 'Shoes');
data.setCell(0, 1, 10700);
data.setCell(1, 0, 'Sports');
data.setCell(1, 1, -15400);
data.setCell(2, 0, 'Toys');
data.setCell(2, 1, 12500);
data.setCell(3, 0, 'Electronics');
data.setCell(3, 1, -2100);
data.setCell(4, 0, 'Food');
data.setCell(4, 1, 22600);
data.setCell(5, 0, 'Art');
data.setCell(5, 1, 1100);
var table = new google.visualization.Table(document.getElementById('barformat_div'));
var formatter = new google.visualization.BarFormat({width: 120});
formatter.format(data, 1); // Apply formatter to second column
table.draw(data, {allowHtml: true, showRowNumber: true});
Assigns colors to the foreground or background of a numeric cell, depending
on the cell value. This formatter is an unusual, in that it doesn't take its
options in the constructor. Instead, you should call addRange() or addGradientRange() as
many times as you want, to add color ranges, before calling format().
Colors can be specified in any acceptable HTML format, for example "black",
"#000000", or "#000".
ColorFormat supports the following methods:
| Option | Description |
|---|---|
addRange(from, to, color, bgcolor) |
Specifies a foreground color and/or background color to a cell, depending on the cell value. Any cell with a value in the specified from—to range (non-inclusive) will be assigned color and bgcolor. It is important to realize that the range is non-inclusive, because creating a range from 1—1,000 and a second from 1,000—2,000 will not cover the value 1,000!
|
addGradientRange(from, to, color, fromBgColor, toBgColor) |
Assigns a background color from a range, according to the cell value.
The color is scaled to match the cell's value within a range from a lower
boundary color to an upper boundary color. Note that this method cannot
compare string values, as
|
format(dataTable, columnIndex) |
The standard format() method to apply formatting to the specified column. |
ColorFormat() |
Constructor. Takes no arguments. |
var data = new google.visualization.DataTable();
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues');
data.addRows(6);
data.setCell(0, 0, 'Shoes');
data.setCell(0, 1, 10700);
data.setCell(1, 0, 'Sports');
data.setCell(1, 1, -15400);
data.setCell(2, 0, 'Toys');
data.setCell(2, 1, 12500);
data.setCell(3, 0, 'Electronics');
data.setCell(3, 1, -2100);
data.setCell(4, 0, 'Food');
data.setCell(4, 1, 22600);
data.setCell(5, 0, 'Art');
data.setCell(5, 1, 1100);
var table = new google.visualization.Table(document.getElementById('colorformat_div'));
var formatter = new google.visualization.ColorFormat();
formatter.addRange(-20000, 0, 'white', 'orange');
formatter.addRange(20000, null, 'red', '#33ff33');
formatter.format(data, 1); // Apply formatter to second column
table.draw(data, {allowHtml: true, showRowNumber: true});
Formats a JavaScript Date value in a variety
of ways, including "January
1, 2009," "1/1/09" and "Jan 1, 2009.
DateFormatter supports the following options, passed in to the
constructor:
| Option | Description |
|---|---|
formatType |
A quick formatting option for the date. The following string values are supported, reformatting the date February 28, 2008 as shown:
You cannot specify both |
pattern |
A custom format pattern to apply to the value, similar to the ICU
date and time format. For example: You cannot specify both |
timeZone |
The time zone in which to display the date value. This is a numeric value,
indicating GMT + this number of time zones (can be negative). Date object
are created by default with the assumed time zone of the computer on which
they are created; this option is used to display that value in a different
time zone. For example, if you created a Date object of 5pm noon
on a computer located in Greenwich, England, and specified timeZone to be
-5 (options['timeZone'] = -5, or Eastern Pacific Time in the
US), the value displayed would be 12 noon. |
function drawDateFormatTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Employee Name');
data.addColumn('date', 'Start Date (Long)');
data.addColumn('date', 'Start Date (Medium)');
data.addColumn('date', 'Start Date (Short)');
data.addRows(3);
data.setCell(0, 0, 'Mike');
data.setCell(0, 1, new Date(2008, 1, 28, 0, 31, 26));
data.setCell(0, 2, new Date(2008, 1, 28, 0, 31, 26));
data.setCell(0, 3, new Date(2008, 1, 28, 0, 31, 26));
data.setCell(1, 0, 'Bob');
data.setCell(1, 1, new Date(2007, 5, 1, 0));
data.setCell(1, 2, new Date(2007, 5, 1, 0));
data.setCell(1, 3, new Date(2007, 5, 1, 0));
data.setCell(2, 0, 'Alice');
data.setCell(2, 1, new Date(2006, 7, 16));
data.setCell(2, 2, new Date(2006, 7, 16));
data.setCell(2, 3, new Date(2006, 7, 16));
// Create three formatters in three styles.
var formatter_long = new google.visualization.DateFormat({formatType: 'long'});
var formatter_medium = new google.visualization.DateFormat({formatType: 'medium'});
var formatter_short = new google.visualization.DateFormat({formatType: 'short'});
// Reformat our data.
formatter_long.format(data, 1);
formatter_medium.format(data,2);
formatter_short.format(data, 3);
// Draw our data
var table = new google.visualization.Table(document.getElementById('dateformat_div'));
table.draw(data, {showRowNumber: true});
}
More About Date Patterns
Here are some more details on what patterns are supported:
The patterns are similar to the ICU
date and time format, but the following patterns are not
yet supported: A e D F g Y u w W. To avoid collision with patterns, any literal
text you want to appear in the output should be surrounded by single quotes,
except for the single quote, which should be doubled: e.g.,"K 'o''clock.'".
| Pattern | Description | Example Output |
|---|---|---|
| GG | Era designator. | "AD" |
| yy or yyyy | year. | 1996 |
| M | Month in year. For January:
|
"July" "07" |
| d | Day in month. Extra 'd' values will add leading zeros. | 10 |
| h | Hour in 12 hour scale. Extra 'h' values will add leading zeros. | 12 |
| H | Hour in 24 hour scale. Extra Hk' values will add leading zeros. | 0 |
| m | Minute in hour. Extra 'M' values will add leading zeros. | 30 |
| s | Second in minute. Extra 's' values will add leading zeros. | 55 |
| S | Fractional second. Extra 'S' values will be padded on the right with zeros. | 978 |
| E | Day of week. Following outputs for "Tuesday":
|
"Tues" "Tuesday" |
| aa | AM/PM | "PM" |
| k | Hour in day (1~24). Extra 'k' values will add leading zeros. | 24 |
| K | Hour in AM/PM (0~11). Extra 'k' values will add leading zeros. | 0 |
| z | Time zone. For time zone 5, produces "UTC+5" |
"UTC+5" |
| Z | Time zone in RFC 822 format. For time zone -5: Z, ZZ, ZZZ produce -0500 ZZZZ and more produce "GMT -05:00" |
"-0800" "GMT -05:00" |
| v | Time zone (generic). |
"Etc/GMT-5" |
| ' | escape for text | 'Date=' |
| '' | single quote | ''yy |
Describes how numeric columns should be formatted. Formatting options include specifying a prefix symbol (such as a dollar sign) or the punctuation to use as a thousands marker.
NumberFormat supports the following options, passed in to the constructor:
| Option | Description |
|---|---|
decimalSymbol |
A character to use as the decimal marker. The default is a dot (.). |
fractionDigits |
A number specifying how many digits to display after the decimal. The default is 2. If you specify more digits than the number contains, it will display zeros for the smaller values. Truncated values will be rounded (5 rounded up). |
groupingSymbol |
A character to be used to group digits to the left of the decimal into sets of three. Default is a comma (,). |
negativeColor |
The text color for negative values. No default value. Values can be any acceptable HTML color value, such as "red" or "#FF0000". |
negativeParens |
A boolean, where true indicates that negative values should be surrounded by parentheses. Default is true. |
prefix |
A string prefix for the value, for example "$". |
suffix |
A string suffix for the value, for example "%". |
var data = new google.visualization.DataTable();
data.addColumn('string', 'Department');
data.addColumn('number', 'Revenues');
data.addRows(6);
data.setCell(0, 0, 'Shoes');
data.setCell(0, 1, 10700);
data.setCell(1, 0, 'Sports');
data.setCell(1, 1, -15400);
data.setCell(2, 0, 'Toys');
data.setCell(2, 1, 12500);
data.setCell(3, 0, 'Electronics');
data.setCell(3, 1, -2100);
data.setCell(4, 0, 'Food');
data.setCell(4, 1, 22600);
data.setCell(5, 0, 'Art');
data.setCell(5, 1, 1100);
var table = new google.visualization.Table(document.getElementById('numberformat_div'));
var formatter = new google.visualization.NumberFormat(
{prefix: '$', negativeColor: 'red', negativeParens: true});
formatter.format(data, 1); // Apply formatter to second column
table.draw(data, {allowHtml: true, showRowNumber: true});
Enables you to merge the values of designated columns into a single column,
along with arbitrary text. So, for example, if you had a column for first name
and a column for last name, you could populate a third column with {last name},
{first name}. This formatter does not follow the conventions for the constructor
and the format() method. See the Methods section below for instructions.
PatternFormat supports the following methods:
| Option | Description |
|---|---|
google.visualization.PatternFormat(pattern) |
Constructor. Does not take an options object. Instead, it takes a string pattern parameter.
This is a string that describes which column values to put into the destination
column, along with any arbitrary text.
Embed placeholders in your string to indicate a value from another column
to embed. The placeholders are Example: The following example demonstrates a constructor
for a pattern that creates an anchor element, with the first and second
elements taken from the var formatter = new google.visualization.PatternFormat('<a href="mailto:{1}">{0}</a>'); |
format(dataTable, srcColumnIndices, opt_dstColumnIndex) |
The standard formatting call, with a few additional parameters:
See the formatting examples after the table. |
Here are a few example inputs and outputs for a four-column table.
Row before formatting (4 columnss, last is blank):
John | Paul | Jones | [empty]
var formatter = new google.visualization.PatternFormat("{0} {1} {2}");
formatter.format(data, [0,1,2], 3);
Output:
John | Paul | Jones | John Paul Jones
var formatter = new google.visualization.PatternFormat("{1}, {0}");
formatter.format(data, [0,2], 3);
Output:
John | Paul | Jones | Jones, John
The following example demonstrates how to combine data from two columns to create an email address. It uses a DataView object to hide the original source columns:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Email');
data.addRows(4);
data.setCell(0, 0, 'John Lennon');
data.setCell(0, 1, 'john@beatles.co.uk');
data.setCell(1, 0, 'Paul McCartney');
data.setCell(1, 1, 'paul@beatles.co.uk');
data.setCell(2, 0, 'George Harrison');
data.setCell(2, 1, 'george@beatles.co.uk');
data.setCell(3, 0, 'Ringo Starr');
data.setCell(3, 1, 'ringo@beatles.co.uk');
var table = new google.visualization.Table(document.getElementById('patternformat_div'));
var formatter = new google.visualization.PatternFormat('<a href="mailto:{1}">{0}</a>');
formatter.format(data, [0, 1]); // Apply formatter and set the formatted value of the first column.
var view = new google.visualization.DataView(data);
view.setColumns([0]); // Create a view with the first column only.
table.draw(view, {allowHtml: true, showRowNumber: true});
A helper class to simplify writing Gadgets that use the Google Visualization API.
google.visualization.GadgetHelper()
| Method | Return Value | Description |
|---|---|---|
createQueryFromPrefs(prefs) |
google.visualization.Query | Static. Create a new instance of google.visualization.Query and set its properties
according to values from the gadget preferences.
The type of parameter prefs is
_IG_Prefs
|
validateResponse(response) |
boolean | Static. Parameter response is of type
google.visualization.QueryResponse.
Returns true if the response contains data.
Returns false if the query execution failed and the response does not contain data.
If an error occured, this method displays an error
message. |
Represents a query that is sent to a data source.
google.visualization.Query(dataSourceUrl, opt_options)
Parameters
makeRequest()
method. If specified, you should also specify makeRequestParams.tqrt URL parameter
from the data source URL. tqrt can have the following values: 'xhr', 'scriptInjection',
or 'makeRequest'. If tqrt is
missing or has an invalid value, the default is 'xhr' for same-domain
requests and 'scriptInjection' for cross-domain
requests.makeRequest() query. Used and required only if sendMethod is
'makeRequest'. | Method | Return Value | Description |
|---|---|---|
setRefreshInterval(seconds) |
None | Sets the query to automatically call the send method
every specified duration (number of seconds), starting from the first
explicit call to send.
seconds is a number greater than or equal to zero.
If set to zero (the default), the query will not be automatically resent. This method, if used, should be called before calling the send method. |
setTimeout(seconds) |
None | Sets the number of seconds to wait for the data source to respond
before raising a timeout error.
seconds is a number greater than zero.
The default timeout is 30 seconds. This method, if used, should be called before calling the send method. |
setQuery(string) |
None | Sets the query string.
The value of the string parameter should be a valid
query.
This method, if used, should be called before calling the send method.
Learn more about the Query language |
send(callback) |
None | Sends the query to the data source.
callback should be a function that will be called when
the data source responds.
The callback function will receive a single parameter
of type google.visualization.QueryResponse. |
Represents a response of a query execution as received from the data source. An instance of this class is passed as an argument to the callback function that was set when Query.send was called.
See also: Query.send
| Method | Return Value | Description |
|---|---|---|
getDataTable() |
DataTable | Returns the data table as returned by the data source.
Returns null if the query execution failed and no data was returned. |
getDetailedMessage() |
string | Returns a detailed error message for queries that failed. If the query execution was successful, this method returns an empty string. The message returned is a message that is intended for developers, and may contain technical information, for example 'Column {salary} does not exist'. |
getMessage() |
string | Returns a short error message for queries that failed. If the query execution was successful, this method returns an empty string. The message returned is a short message that is intended for end users, for example 'Invalid Query' or 'Access Denied'. |
getReasons() |
Array of strings | Returns an array of zero of more entries. Each entry is a short string
with an error or warning code that was raised while executing the query.
Possible codes:
|
hasWarning() |
boolean | Returns true if the query execution has any warning messages. |
isError() |
boolean | Returns true if the query execution failed, and the response
does not contain any data table. Returns <false> if the query execution
was successful and the response contains a data table. |
This is the constructor for the toolbar element that can be attached to many visualizations. This toolbar enables the user to export the visualization data into different formats, or to provide an embeddable version of the visualization for use in different places. See the toolbar page for more information and a code example.
The API provides several functions to help you display nicely-formatted error
messages to your users. To use these functions, provide a container element on
the page (typically a <div>),
into which the API will draw a formatted error message. This container can be either
the visualization container element, or a container just for errors. If you specify
the visualization container element, the error message will be displayed above
the visualization. Then call the appropriate function below to show, or remove,
the error message. All functions are static functions in the namespace google.visualization.errors.
| Function | Return Value | Description |
|---|---|---|
addError(container, message, opt_detailedMessage,
opt_options) |
String ID value that identifies the error object created. This is a unique value on the page, and can be used to remove the error or find its containing element. | Adds an error display block to the specified page element, with specified text and formatting.
|
addErrorFromQueryResponse(container, response) |
String ID value that identifies the error object created, or null if the response didn't indicate an error. This is a unique value on the page, and can be used to remove the error or find its containing element. |
Pass a query response and error message container to this method: if
the query response indicates a query error, displays an error message
in the specified page element. If the query response is null, the method
will throw a JavaScript error. Pass your QueryResponse received
in your query handler to this message to display an error. It will also set
the style of the display appropriate to the type (error or warning, similar
to
|
removeError(id)
|
Boolean: true if the error was removed; false otherwise. | Removes the error specified by ID from the page.
|
removeAll(container)
|
None | Removes all error blocks from a specified container. If the specified container does not exist, this will throw an error.
|
getContainer(errorId)
|
Handle to a DOM element holding the error specified, or null if it could not be found. | Retrieves a handle to the container element holding the error specified by errorID.
|
Registering to Catch Events
Your visualizations can fire and receive events, and exposes the following two methods to enable you to do so:
Commonly Exposed Events
Visualizations can fire a number of events. Every visualization can define the details of the events it fires, but the following event should be implemented in a standard way:
Called by visualization implementers. Call this method from your visualization to fire an event with an arbitrary name and set of values.
google.visualization.events.trigger(source_visualization, event_name, event_args)
this keyword.Example
Here is an example of a visualization that throws a method named "select" when its onclick method is called. It does not pass back any values.
MyVisualization.prototype.onclick = function(rowIndex) {
this.highlightRow(this.selectedRow, false); // Clear previous selection
this.highlightRow(rowIndex, true); // Highlight new selection
// Save the selected row index in case getSelection is called.
this.selectedRow = rowIndex;
// Trigger a select event.
google.visualization.events.trigger(this, 'select', null);
};
Used by visualization users. Call this method to register to receive events fired by a visualization hosted on your page. Note that this will not work for gadget visualizations. The visualization should document what event arguments, if any, will be passed to the handling function.
google.visualization.events.addListener(source_visualization, event_name, handling_function)
Example
Here is an example of registering to receive the selection event
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, options);
google.visualization.events.addListener(table, 'select', selectHandler);
function selectHandler() {
alert('A table row was selected');
}
If your visualization is not expected to be ready for interaction immediately after it returns from its draw() implementation, consider implementing a ready event. This event should be fired when the visualization is ready to begin responding to user interaction and method calls. This event typically does not provide any parameters to the receiver. See the Firing Events page for more information.
If your visualization can fire events to the client when selected, consider implementing the select event. Details on the standard way to implement this event are given on the Firing Events page.
Every visualization should expose the following set of required and optional methods and properties. However, note that there is no type checking to enforce these standards, so you should read the documentation for each visualization.
Note: These methods are in the namespace of the visualization, not the google.visualization namespace.
The constructor should have the name of your visualization class, and return an instance of that class.
visualization_class_name(dom_element)
Example
var org = new google.visualization.OrgChart(document.getElementById('org_div'));
Draws the visualization on the page. Behind the scenes this can be fetching a graphic from a server or creating the graphic on the page using the linked visualization code. You should call this method every time the data or options change. The object should be drawn inside the DOM element passed into the constructor.
draw(data[, options])
DataTable passed into a visualization.{x:100, y:200, title:'An
Example'}Example
chart.draw(myData, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
This is optionally exposed by visualizations that want to let you access the currently selected data in the graphic.
selection_array getSelection()
Returns
selection_array An array of selected objects,
each one describing a data element in the underlying table. Each object has properties
row and/or column,
with the index of the row and/or column of the selected item in the
underlying DataTable. If the row property is null, then the selection
is a column; if the column property is null, then the selection is
a row; if both are non-null, then it is a specific data item. You can call the DataTable.getValue() method
to get the value of that element.
Example
function myClickHandler(){
var selection = myVis.getSelection();
for (var i = 0; i < selection.length; i++) {
var item = selection[i];
if (item.row != null && item.column != null) {
message += '{row:' + item.row + ',column:' + item.column + '}';
} else if (item.row != null) {
message += '{row:' + item.row + '}';
} else if (item.column != null) {
message += '{column:' + item.column + '}';
}
}
if (message == '') {
message = 'nothing';
}
alert('You selected ' + message);
}
Sets the current selection in the graphic. When this method is called, the visualization should visually indicate what the new selection is. The implementation of setSelection() should not fire a "select" event. Visualizations may ignore part of the selection. For example, a table that can show only selected rows may ignore cell or column elements in its setSelection() implementation, or it can select the entire row.
setSelection(selection_array)
row=null to select a whole column, or column=null to select a whole row.