A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://developers.google.com/chart/interactive/docs/reference below:

Google Visualization API Reference | Charts

Skip to main content Google Visualization API Reference

Stay organized with collections Save and categorize content based on your preferences.

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.*

A Note on Arrays

Some browsers don't properly handle trailing commas in JavaScript arrays, so don't use them. Empty values in the middle of an array are fine. So, for example:

data = ['a','b','c', ,]; // BAD
data = ['a','b','c'];   // OK
data = ['a','b', ,'d']; // Also OK. The third value is undefined.

DataTable Class

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. Some visualizations support specific custom properties; for example the Table visualization supports a cell property called 'style', which lets you assign an inline CSS style string to the rendered table cell. A visualization should describe in its documentation any custom properties that it supports.

See also: QueryResponse.getDataTable

Constructor

Syntax

DataTable(opt_data, opt_version)

opt_data
[Optional] Data used to initialize the table. This can either be the JSON returned by calling DataTable.toJSON() on a populated table, or a JavaScript object containing data used to initialize the table. The structure of the JavaScript literal object is described here. If this parameter is not supplied, a new, empty data table will be returned.
opt_version
[Optional] A numeric value specifying the version of the wire protocol used. This is only used by Chart Tools Datasource implementors. The current version is 0.6.

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.

If you change values in a DataTable after it is passed into a visualization's draw() method, the changes will not immediately change the chart. You must call draw() again to reflect any changes.

Note: Google Charts does not perform any validation on datatables. (If it did, charts would be slower to render.) If you provide a number where your column is expecting a string, or vice versa, Google Charts will do its level best to interpret the value in a way that makes sense, but will not flag mistakes.

Examples

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);

The following example creates a new, empty DataTable and then populates it manually with the same data as above:

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'}]
]);
Should I create my DataTable in JavaScript or object literal notation?

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?

Methods Method Return Value Description

addColumn(type, opt_label, opt_id)

OR

addColumn(description_object)

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 null value. This method has two signatures:

First signature has the following parameters:

Second signature has a single object parameter with the following members:

See also: getColumnId, getColumnLabel, getColumnType, insertColumn, getColumnRole

addRow(opt_cellArray) 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'}
]);

data.addRow(['Col1Val', null, 'Col3Val']); // Second column is undefined.
data.addRow(['Col1Val', , 'Col3Val']);     // Same as previous.
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)],
  ['Bob', null] // No date set for Bob.
]);

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; this means that non-primitive properties are copied by reference, but primitive properties are copied by value. 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 getColumnIndex(columnIdentifier) String, Number Returns the index of a given column specified by the column index, id, or label if it exists in this table, otherwise -1. When columnIdentifier is a string, it is used to find the column by its id first, then by its label.
See also: getColumnId, getColumnLabel 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 format clause of the query language. An example of a pattern is '#,##0.00'. For more on patterns see the query language reference.

getColumnProperties(columnIndex) Object

Returns a map of all properties for the specified column. Note that the properties object is returned by reference, so changing values in the retrieved object changes them in the DataTable.

getColumnProperty(columnIndex, name) Auto

Returns the value of a named property, or null if no such property is set for the specified column. The return type varies, depending on the property.

See also: setColumnProperty setColumnProperties

getColumnRange(columnIndex) Object

Returns the minimal and maximal values of values in a specified column. The returned object has properties min and max. If the range has no values, min and max will contain null.

columnIndex should be a number greater than or equal to zero, and less than the number of columns as returned by the getNumberOfColumns() method.

getColumnRole(columnIndex) String Returns the role of the specified column. 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: 'string', 'number', 'boolean', 'date', 'datetime', and 'timeofday'

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 getValue method.

getFilteredRows(filters) Array of objects

Returns the row indexes for rows that match all of the given filters. The indexes are returned in ascending order. The output of this method can be used as input to DataView.setRows() to change the displayed set of rows in a visualization.

filters - An array of objects that describe an acceptable cell value. A row index is returned by this method if it matches all of the given filters. Each filter is an object with a numeric column property that specifies the index of the column in the row to assess, plus one of the following:

Another optional property, test, specifies a function to be combined with value or range filtering. The function is called with the cell value, the row and column indices, and the datatable. It should return false if the row should be excluded from the result.

Example: getFilteredRows([{column: 3, value: 42}, {column: 2, minValue: 'bar', maxValue: 'foo'}, {column: 1, test: (value, rowId, columnId, datatable) => { return value == "baz"; }}]) returns an array containing, in ascending order, the indexes of all rows for which the fourth column (column index 3) is exactly 42, and the third column (column index 2) is between 'bar' and 'foo' (inclusive).

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: setFormattedValue

getNumberOfColumns() Number Returns the number of columns in the table. getNumberOfRows() Number Returns the number of rows in the table. getProperties(rowIndex, columnIndex) Object

Returns a map of all the properties for the specified cell. Note that the properties object is returned by reference, so changing values in the retrieved object changes them in the DataTable.

getProperty(rowIndex, columnIndex, name) Auto

Returns the value of a named property, or null if no such property is set for the specified cell. The return type varies, depending on the property.

See also: setCell setProperties setProperty

getRowProperties(rowIndex) Object

Returns a map of all properties for the specified row. Note that the properties object is returned by reference, so changing values in the retrieved object changes them in the DataTable.

getRowProperty(rowIndex, name) Auto

Returns the value of a named property, or null if no such property is set for the specified row. The return type varies, depending on the property.

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 sort(). You can specify sorting in a number of ways, depending on the type you pass in to the sortColumns parameter:

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 sortColumns. The output can be used as input to DataView.setRows() to quickly change the displayed set of rows in a visualization.

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.
See also: sort

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);
}
getTableProperties Object Returns a map of all properties for the table. getTableProperty(name) Auto

Returns the value of a named property, or null if no such property is set for the table. The return type varies, depending on the property.

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, formatted value, and/or properties, of a cell.

See also: setValue(), setFormattedValue(), setProperty(), setProperties().

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 properties. 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}]); toJSON() String Returns a JSON representation of the DataTable that can be passed into the DataTable constructor. For example:
{"cols":[{"id":"Col1","label":"","type":"date"}],
 "rows":[
   {"c":[{"v":"a"},{"v":"Date(2010,10,6)"}]},
   {"c":[{"v":"b"},{"v":"Date(2010,10,7)"}]}
 ]
}
Format of the Constructor's JavaScript Literal data Parameter

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):

cols Example

cols: [{id: 'A', label: 'NEW A', type: 'string'},
       {id: 'B', label: 'B-label', type: 'number'},
       {id: 'C', label: 'C-label', type: 'date'}]

rows Property

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.

Cell Objects

Each cell in the table is described by an object with the following properties:

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 table-level 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 available for application use. Example: p:{className: 'myDataTable'}.

DataView Class

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 must be careful when changing the structure of the table itself, as described here:

It is also possible to create a DataView from another 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.

DataView also supports calculated columns; these are columns whose value is calculated on the fly using a function that you supply. So, for example, you can include a column that is a sum of two preceding columns, or a column that calculates and shows the calendar quarter of a date from another column. See setColumns() for more details.

When you modify a DataView by hiding or showing rows or columns, the visualization will not be affected until you call draw() on the visualization again.

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});
Constructors

There are two ways to create a new DataView instance:

Constructor 1

var myView = new google.visualization.DataView(data)
data
A DataTable 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().

Constructor 2

This constructor creates a new DataView by assigning a serialized DataView to a DataTable. It helps you recreate the DataView that you serialized using DataView.toJSON().

var myView = google.visualization.DataView.fromJSON(data, viewAsJson)
data
The DataTable object that you used to create the DataView, on which you called DataView.toJSON(). If this table is any different from the original table, you will get unpredictable results.
viewAsJson
The JSON string returned by DataView.toJSON(). This is a description of which rows to show or hide from the data DataTable.
Methods Method Return Value Description See descriptions in DataTable. Same as the equivalent DataTable methods, except that row/column indexes refer to the index in the view and not in the underlying table/view. getTableColumnIndex(viewColumnIndex) Number

Returns the index in the underlying table (or view) of a given column specified by its index in this view. viewColumnIndex should be a number greater than or equal to zero, and less than the number of columns as returned by the getNumberOfColumns() method. Returns -1 if this is a generated column.

Example: If setColumns([3, 1, 4]) was previously called, then getTableColumnIndex(2) will return 4.

getTableRowIndex(viewRowIndex) Number

Returns the index in the underlying table (or view) of a given row specified by its index in this view. viewRowIndex should be a number greater than or equal to zero, and less than the number of rows as returned by the getNumberOfRows() method.

Example: If setRows([3, 1, 4]) was previously called, then getTableRowIndex(2) will return 4.

getViewColumnIndex(tableColumnIndex) Number

Returns the index in this view that maps to a given column specified by its index in the underlying table (or view). If more than one such index exists, returns the first (smallest) one. If no such index exists (the specified column is not in the view), returns -1. tableColumnIndex should be a number greater than or equal to zero, and less than the number of columns as returned by the getNumberOfColumns() method of the underlying table/view.

Example: If setColumns([3, 1, 4]) was previously called, then getViewColumnIndex(4) will return 2.

getViewColumns() Array of numbers

Returns the columns in this view, in order. That is, if you call setColumns with some array, and then call getViewColumns() you should get an identical array.

getViewRowIndex(tableRowIndex) Number

Returns the index in this view that maps to a given row specified by its index in the underlying table (or view). If more than one such index exists, returns the first (smallest) one. If no such index exists (the specified row is not in the view), returns -1. tableRowIndex should be a number greater than or equal to zero, and less than the number of rows as returned by the getNumberOfRows() method of the underlying table/view.

Example: If setRows([3, 1, 4]) was previously called, then getViewRowIndex(4) will return 2.

getViewRows() Array of numbers

Returns the rows in this view, in order. That is, if you call setRows with some array, and then call getViewRows() you should get an identical array.

hideColumns(columnIndexes) none

Hides the specified columns from the current view. columnIndexes is an array of numbers representing the indexes of the columns to hide. These indexes are the index numbers in the underlying table/view. The numbers in columnIndexes do not have to be in order (that is, [3,4,1] is fine). The remaining columns retain their index order when you iterate through them. Entering an index number for a column already hidden is not an error, but entering an index that does not exist in the underlying table/view will throw an error. To unhide columns, call setColumns().

Example: If you have a table with 10 columns, and you call setColumns([2,7,1,7,9]), and then hideColumns([7,9]), the columns in the view will then be [2,1].

hideRows(min, max) None

Hides all rows with indexes that lie between min and max (inclusive) from the current view. This is a convenience syntax for hideRows(rowIndexes) above. For example, hideRows(5, 10) is equivalent to hideRows([5, 6, 7, 8, 9, 10]).

hideRows(rowIndexes) None

Hides the specified rows from the current view. rowIndexes is an array of numbers representing the indexes of the rows to hide. These indexes are the index numbers in the underlying table/view. The numbers in rowIndexes do not have to be in order (that is, [3,4,1] is fine). The remaining rows retain their index order. Entering an index number for a row already hidden is not an error, but entering an index that does not exist in the underlying table/view will throw an error. To unhide rows, call setRows().

Example: If you have a table with 10 rows, and you call setRows([2,7,1,7,9]), and then hideRows([7,9]), the rows in the view will then be [2,1].

setColumns(columnIndexes) None

Specifies which columns are visible in this view. Any columns not specified will be hidden. This is an array of column indexes in the underlying table/view, or calculated columns. If you don't call this method, the default is to show all columns. The array can also contain duplicates, to show the same column multiple times. Columns will be shown in the order specified.

Examples:

// Show some columns directly from the underlying data.
// Shows column 3 twice.
view.setColumns([3, 4, 3, 2]);

// Underlying table has a column specifying a value in centimeters.
// The view imports this directly, and creates a calculated column
// that converts the value into inches.
view.setColumns([1,{calc:cmToInches, type:'number', label:'Height in Inches'}]);
function cmToInches(dataTable, rowNum){
  return Math.floor(dataTable.getValue(rowNum, 1) / 2.54);
}
setRows(min, max) None

Sets the rows in this view to be all indexes (in the underlying table/view) that lie between min and max (inclusive). This is a convenience syntax for setRows(rowIndexes) below. For example, setRows(5, 10) is equivalent to setRows([5, 6, 7, 8, 9, 10]).

setRows(rowIndexes) None

Sets the visible rows in this view, based on index numbers from the underlying table/view. rowIndexes should be an array of index numbers specifying which rows to show in the view. The array specifies the order in which to show the rows, and rows can be duplicated. Note that only the rows specified in rowIndexes will be shown; this method clears all other rows from the view. The array can also contain duplicates, effectively duplicating the specified row in this view (for example, setRows([3, 4, 3, 2]) will cause row 3 to appear twice in this view). The array thus provides a mapping of the rows from the underlying table/view to this view. You can use getFilteredRows() or getSortedRows() to generate input for this method.

Example: To create a view with rows three and zero of an underlying table/view: view.setRows([3, 0])

toDataTable() DataTable Returns a DataTable object populated with the visible rows and columns of the DataView. toJSON() string Returns a string representation of this DataView. Thisstring does not contain the actual data; it only contains the DataView-specific settings such as visible rows and columns. You can store this string and pass it to the static DataView.fromJSON() constructor to recreate this view. This won't include generated columns. ChartWrapper Class

A ChartWrapper class is used to wrap your chart and handle all loading, drawing, and Datasource querying for your chart. The class exposes convenience methods for setting values on the chart and drawing it. This class simplifies reading from a data source, because you do not have to create a query callback handler. You can also use it to save a chart easily for reuse.

Another bonus of using ChartWrapper is that you can reduce the number of library loads by using dynamic loading. Additionally, you don't need to load the packages explicitly since ChartWrapper will handle looking up and loading the chart packages for you. See the examples below for details.

However, ChartWrapper currently only propagates a subset of events thrown by charts: select, ready, and error. Other events are not transmitted through the ChartWrapper instance; to get other events, you must call getChart() and subscribe to events directly on the chart handle, as shown here:

var wrapper;
function drawVisualization() {

  // Draw a column chart
  wrapper = new google.visualization.ChartWrapper({
    chartType: 'ColumnChart',
    dataTable: [['Germany', 'USA', 'Brazil', 'Canada', 'France', 'RU'],
                [700, 300, 400, 500, 600, 800]],
    options: {'title': 'Countries'},
    containerId: 'visualization'
  });

  // Never called.
  google.visualization.events.addListener(wrapper, 'onmouseover', uselessHandler);

  // Must wait for the ready event in order to
  // request the chart and subscribe to 'onmouseover'.
  google.visualization.events.addListener(wrapper, 'ready', onReady);

  wrapper.draw();

  // Never called
  function uselessHandler() {
    alert("I am never called!");
  }

  function onReady() {
    google.visualization.events.addListener(wrapper.getChart(), 'onmouseover', usefulHandler);
  }

  // Called
  function usefulHandler() {
    alert("Mouseover event!");
  }
}
Constructor
ChartWrapper(opt_spec)
opt_spec
[Optional] - Either a JSON object defining the chart, or a serialized string version of that object. The format of this object is shown in the drawChart() documentation. If not specified, you must set all the appropriate properties using the set... methods exposed by this object.
Methods

ChartWrapper exposes the following additional methods:

Method Return Type Description draw(opt_container_ref) None

Draws the chart. You must call this method after any changes that you make to the chart or data to show the changes.

toJSON() String Returns a string version of the JSON representation of the chart. clone() ChartWrapper Returns a deep copy of the chart wrapper. getDataSourceUrl() String If this chart gets its data from a data source, returns the URL for this data source. Otherwise, returns null. getDataTable() google.visualization.DataTable

If this chart gets its data from a locally-defined DataTable, will return a reference to the chart's DataTable. If this chart gets its data from a data source, it will return null.

Any changes that you make to the returned object will be reflected by the chart the next time you call ChartWrapper.draw().

getChartType() String The class name of the wrapped chart. If this is a Google chart, the name will not be qualified with google.visualization. So, for example, if this were a Treemap chart, it would return "Treemap" rather than "google.visualization.treemap". getChartName() String Returns the chart name assigned by setChartName(). getChart() Chart object reference Returns a reference to the chart created by this ChartWrapper, for example a google.visualization.BarChart or a google.visualization.ColumnChart . This will return null until after you have called draw() on the ChartWrapper object, and it throws a ready event. Methods called on the returned object will be reflected on the page. getContainerId() String The ID of the chart's DOM container element. getQuery() String The query string for this chart, if it has one and queries a data source. getRefreshInterval() Number Any refresh interval for this chart, if it queries a data source. Zero indicates no refresh. getOption(key, opt_default_val) Any type

Returns the specified chart option value

getOptions() Object Returns the options object for this chart. getView() Object OR Array Returns the DataView initializer object, in the same format as dataview.toJSON(), or an array of such objects. setDataSourceUrl(url) None Sets the URL of a data source to use for this chart. If you also set a data table for this object, the data source URL will be ignored. setDataTable(table) None Sets the DataTable for the chart. Pass in one of the following: null; a DataTable object; a JSON representation of a DataTable; or an array following the syntax of arrayToDataTable(). setChartType(type) None Sets the chart type. Pass in the class name of the wrapped chart. If this is a Google chart, do not qualify it with google.visualization. So, for example, for a pie chart, pass in "PieChart". setChartName(name) None Sets an arbitrary name for the chart. This is not shown anywhere on the chart, unless a custom chart is explicitly designed to use it. setContainerId(id) None Sets the ID of the containing DOM element for the chart. setQuery(query_string) None Sets a query string, if this chart queries a data source. You must also set the data source URL if specifying this value. setRefreshInterval(interval) None Sets the refresh interval for this chart, if it queries a data source. You must also set a data source URL if specifying this value. Zero indicates no refresh. setOption(key, value) None Sets a single chart option value, where key is the option name and value is the value. To unset an option, pass in null for the value. Note that key may be a qualified name, such as 'vAxis.title'. setOptions(options_obj) None Sets a complete options object for a chart. setView(view_spec) None Sets a DataView initializer object, which acts as a filter over the underlying data. The chart wrapper must have underlying data from a DataTable or a data source to apply this view to. You can pass in either a string or DataView initializer object, like that returned by dataview.toJSON(). You can also pass in an array of DataView initializer objects, in which case the first DataView in the array is applied to the underlying data to create a new data table, and the second DataView is applied to the data table resulting from application of the first DataView, and so on. Events

The ChartWrapper object throws the following events. Note that you must call ChartWrapper.draw() before any events will be thrown.

Name Description Properties error Fired when an error occurs when attempting to render the chart. id, message ready The chart is ready for external method calls. If you want to interact with the chart, and call methods after you draw it, you should set up a listener for this event before you call the draw method, and call them only after the event was fired. None select Fired when the user clicks a bar or legend. When a chart element is selected, the corresponding cell in the data table is selected; when a legend is selected, the corresponding column in the data table is selected. To learn what has been selected, call ChartWrapper.getChart(). getSelection(). Note that this will only be thrown when the underlying chart type throws a selection event. None Example

The following two snippets create an equivalent line chart. The first example uses JSON literal notation to define the chart; the second uses ChartWrapper methods to set these values.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Visualization API Sample</title>
<!--
  One script tag loads all the required libraries!
-->
<script type="text/javascript"
      src='https://www.gstatic.com/charts/loader.js'></script>
<script>
  google.charts.load('current);
  google.charts.setOnLoadCallback(drawVisualization);

  function drawVisualization() {
    var wrap = new google.visualization.ChartWrapper({
       'chartType':'LineChart',
       'dataSourceUrl':'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1',
       'containerId':'visualization',
       'query':'SELECT A,D WHERE D > 100 ORDER BY D',
       'options': {'title':'Population Density (people/km^2)', 'legend':'none'}
       });
     wrap.draw();
  }
</script>
</head>
<body>
  <div id="visualization" style="height: 400px; width: 400px;"></div>
</body>
</html>

Same chart, now using setter methods:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=utf-8'/>
<title>Google Visualization API Sample</title>
<!-- One script tag loads all the required libraries!
-->
<script type="text/javascript"
    src='https://www.gstatic.com/charts/loader.js'></script>
<script type="text/javascript">
  google.charts.load('current');
  google.charts.setOnLoadCallback(drawVisualization);
  function drawVisualization() {
    // Define the chart using setters:
    var wrap = new google.visualization.ChartWrapper();
    wrap.setChartType('LineChart');
    wrap.setDataSourceUrl('http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1');
    wrap.setContainerId('visualization');
    wrap.setQuery('SELECT A,D WHERE D > 100 ORDER BY D');
    wrap.setOptions({'title':'Population Density (people/km^2)', 'legend':'none'});
    wrap.draw();
  }
</script>
</head>
<body>
  <div id='visualization' style='height: 400px; width: 400px;'></div>
</body>
</html>
ChartEditor Class

The ChartEditor class is used to open an in-page dialog box that enables a user to customize a visualization on the fly.

To use ChartEditor:

  1. Load the charteditor package. In google.charts.load(), load the package 'charteditor'. You do not need to load the packages for the chart type that you render in the editor; the chart editor will load any package for you as needed.
  2. Create a ChartWrapper object that defines the chart for the user to customize. This chart will be shown in the dialog, and the user uses the editor to redesign the chart, change chart types, or even change the source data.
  3. Create a new ChartEditor instance, and register to listen for the "ok" event. This event is thrown when the user clicks the "OK" button on the dialog. When received, you should call ChartEditor.getChartWrapper() to retrieve the user-modified chart.
  4. Call ChartEditor.openDialog(), passing in the ChartWrapper. This opens the dialog. The dialog buttons enable the user to close the editor. The ChartEditor instance is available as long as it is in scope; it is not automatically destroyed after the user closes the dialog.
  5. To update the chart in code, call setChartWrapper().
Methods Method Return Value Description openDialog(chartWrapper, opt_options) null

Opens the chart editor as an embedded dialog box on the page. The function returns immediately; it does not wait for the dialog to be closed. If you do not lose scope of the instance, you can call openDialog() again to reopen the dialog, although you must pass in a ChartWrapper object again.

getChartWrapper() ChartWrapper Returns a ChartWrapper representing the chart, with user modifications. setChartWrapper(chartWrapper) null

Use this method to update the rendered chart on the editor.

chartWrapper - A ChartWrapper object representing the new chart to render. The chart must either have a populated DataTable, or be connected to a valid data source.

closeDialog() null Closes the chart editor dialog box. Options

The chart editor supports the following options:

Name Type Default Description dataSourceInput Element handle or 'urlbox' null

Use this to enable the user to specify a data source for the chart. This property can be one of two values:

Events

The chart editor throws the following events:

Name Description Properties ok Fired when the user clicks the "OK" button on the dialog. After receiving this method, you should call getChartWrapper() to retrieve the user-configured chart. none cancel Fired when the user clicks the "Cancel" button on the dialog. none Example

The following example code opens a chart editor dialog with a populated line chart. If the user clicks "OK", the edited chart will be saved to the specified <div> on the page.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <title>
    Google Visualization API Sample
  </title>
  <script type="text/javascript"
    src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', {packages: ['charteditor']});
  </script>
  <script type="text/javascript">
    google.charts.setOnLoadCallback(loadEditor);
    var chartEditor = null;

    function loadEditor() {
      // Create the chart to edit.
      var wrapper = new google.visualization.ChartWrapper({
         'chartType':'LineChart',
         'dataSourceUrl':'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1',
         'query':'SELECT A,D WHERE D > 100 ORDER BY D',
         'options': {'title':'Population Density (people/km^2)', 'legend':'none'}
      });

      chartEditor = new google.visualization.ChartEditor();
      google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
      chartEditor.openDialog(wrapper, {});
    }

    // On "OK" save the chart to a <div> on the page.
    function redrawChart(){
      chartEditor.getChartWrapper().draw(document.getElementById('vis_div'));
    }

  </script>
</head>
<body>
  <div id="vis_div" style="height: 400px; width: 600px;"></div>
</body>
</html>
Data Manipulation Methods

The google.visualization.data namespace holds static methods to perform SQL-like operations on DataTable objects, for example joining them or grouping by column value.

The google.visualization.data namespace exposes the following methods:

group()

Takes a populated DataTable object and performs a SQL-like GROUP BY operation, returning a table with rows grouped by the specified column values. Note that this does not modify the input DataTable.

The returned table includes one row for each combination of values in the specified key columns. Each row includes the key columns, plus one column with an aggregated column value over all rows that match the key combination (for example, a sum or count of all values in the specified column).

The google.visualization.data namespace includes several useful aggregation values (for example, sum and count), but you can define your own (for example, standardDeviation or secondHighest). Instructions on how to define your own aggregator are given after the method description.

Syntax

google.visualization.data.group(data_table, keys, columns)
data_table
The input DataTable. This will not be modified by calling group().
keys
An array of numbers and/or objects specifying which columns to group by. The result table includes every column in this array, as well as every column in columns. If a number, this is a column index of the input DataTable to group by. If an object, it will include a function that can modify the specified column (for example, add 1 to the value in that column). The object must have the following properties:
Examples: [0], [0,2], [0,{column:1, modifier:myPlusOneFunc, type:'number'},2]
columns
[Optional] Lets you specify which columns, in addition to key columns, to include in the output table. Because all rows in the row group are compressed into a single output row, you must determine what value to display for that row group. For example, you could choose to show the column value from the first row in the set, or an average of all rows in that group. columns is an array of objects, with the following properties:

Return Value

A DataTable with one column for each column listed in keys and one column for each column listed in columns. The table is sorted by key rows, from left to right.

Example

// This call will group the table by column 0 values.
// It will also show column 3, which will be a sum of
// values in that column for that row group.
var result = google.visualization.data.group(
  dt,
  [0],
  [{'column': 3, 'aggregation': google.visualization.data.sum, 'type': 'number'}]
);

*Input table*
1  'john'  'doe'            10
1  'jane'  'doe'           100
3  'jill'  'jones'          50
3  'jack'  'jones'          75
5  'al'    'weisenheimer'  500

*Output table*
1  110
3  125
5  500
Provided Modifier Functions

The API provides the following modifier functions that you can pass into the keys. modifier parameter to customize grouping behavior.

Function Input Array Type Return Type Description google.visualization.data.month Date number Given a date, it will return the zero-based month value (0, 1, 2, and so on). Provided Aggregation Functions

The API provides the following aggregation functions that you can pass into the columns. aggregation parameter array.

Function Input Array Type Return Type Description google.visualization.data.avg number number The average value of the array passed in. google.visualization.data.count any type number The count of rows in the group. Null and duplicate values are counted. google.visualization.data.max number, string, Date number, string, Date, null The maximum value in the array. For strings, this is the first item in an lexicographically sorted list; for Date values, it is the latest date. Nulls are ignored. Returns null if there is no maximum. google.visualization.data.min number, string, Date number, string, Date, null The minimum value in the array. For strings, this is the last item in an lexicographically sorted list; for Date values, it is the earliest date. Nulls are ignored. Returns null if if there is no minimum. google.visualization.data.sum number number The sum of all values in the array. Creating a modifier function

You can create a modifier function to perform a simple transformation onkey values before the group() function groups your rows. This function takes a single cell value, performs an action on it (for example, adds 1 to the value), and returns it. The input and return types need not be the same type, but the caller must know the input and output types. Here's an example of a function that accepts a date and returns the quarter:

// Input type: Date
// Return type: number (1-4)
function getQuarter(someDate) {
  return Math.floor(someDate.getMonth()/3) + 1;
}
Creating an aggregation function

You can create an aggregation function that accepts a set of column values in a row group and returns a single number: for example, returning a count or average of values. Here is an implementation of the provided count aggregation function, which returns a count of how many rows are in the row group:

// Input type: Array of any type
// Return type: number
function count(values) {
  return values.length;
}
join()

This method joins two data tables (DataTable or DataView objects) into a single results table, similar to a SQL JOIN statement. You specify one or more column pairs (key columns) between the two tables, and the output table includes the rows according to a join method that you specify: only rows where both keys match; all rows from one table; or all rows from both tables, whether or not the keys match. The results table includes only the key columns, plus any additional columns that you specify. Note that dt2 cannot have duplicate keys, but dt1 can. The term "key" means the combination of all key column values, not a specific key column value; so if a row has cell values A | B | C and columns 0 and 1 are key columns, then the key for that row is AB.

Syntax

google.visualization.data.join(dt1, dt2, joinMethod,
                                 keys, dt1Columns, dt2Columns);
dt1
A populated DataTable to join with dt2.
dt2
A populated DataTable to join with dt1. This table cannot have multiple identical keys (where a key is a combination of key column values).
joinMethod
A string specifying the join type. If dt1 has multiple rows that match a dt2 row, the output table will include all matching dt1 rows. Choose from the following values:
keys
An array of key columns to compare from both tables. Each pair is a two element array, the first is a key in dt1, the second is a key in dt2. This array can specify columns by their index, id, or label, see getColumnIndex.
Columns must be the same type in both tables. All specified keys must match according to the rule given by joinMethod in order to include a row from the table. Key columns are always included in the output table. Only dt1, the left-hand table, can include duplicate keys; keys in dt2 must be unique. The term "key" here means a unique set of key columns, not individual column values. For example, if your key columns were A and B, the following table would have only unique key values (and could thus be used as dt2): A B Jen Red Jen Blue Fred Red Example: [[0,0], [2,1]] compares values from the first column in both tables as well as the third column from dt1 with the second column from dt2.
dt1Columns
An array of columns from dt1 to include in the output table, in addition to dt1's key columns. This array can specify columns by their index, id, or label, see getColumnIndex.
dt2Columns
An array of columns from dt2 to include in the output table, in addition to dt2's key columns. This array can specify columns by their index, id, or label, see getColumnIndex.

Return Value

A DataTable with the key columns, dt1Columns, and dt2Columns. This table is sorted by the key columns, from left to right. When joinMethod is 'inner', all key cells should be populated. For other join methods, if no matching key is found, the table will have a null for any unmatched key cells.

Examples

*Tables*
dt1                        dt2
bob  | 111 | red           bob   | 111 | point
bob  | 111 | green         ellyn | 222 | square
bob  | 333 | orange        jane  | 555 | circle
fred | 555 | blue          jane  | 777 | triangle
jane | 777 | yellow        fred  | 666 | dodecahedron
* Note that right table has duplicate Jane entries, but the key we will use is
* columns 0 and 1. The left table has duplicate key values, but that is
* allowed.

*Inner join* google.visualization.data.join(dt1, dt2, 'inner', [[0,0],[1,1]], [2], [2]);
bob  | 111 | red    | point
bob  | 111 | green  | point
jane | 777 | yellow | triangle
* Note that both rows from dt1 are included and matched to
* the equivalent dt2 row.


*Full join* google.visualization.data.join(dt1, dt2, 'full', [[0,0],[1,1]], [2], [2]);
bob   | 111 | red    | point
bob   | 111 | green  | point
bob   | 333 | orange | null
ellyn | 222 | null | square
fred  | 555 | blue   | null
fred  | 666 | null | dodecahedron
jane  | 555 | null | circle
jane  | 777 | yellow | triangle


*Left join*  google.visualization.data.join(dt1, dt2, 'left', [[0,0],[1,1]], [2], [2]);
bob  | 111 | red | point
bob  | 111 | green | point
bob  | 333 | orange | null
fred | 555 | blue | null
jane | 777 | yellow | triangle


*Right join*  google.visualization.data.join(dt1, dt2, 'right', [[0,0],[1,1]], [2], [2]);
bob   | 111 | red | point
bob   | 111 | green | point
ellyn | 222 | null | square
fred  | 666 | null | dodecahedron
jane  | 555 | null | circle
jane  | 777 | yellow | triangle
Formatters

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:

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-07-10 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-07-10 UTC."],[],[]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4