Show
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
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: DataTable Class
Represents a two-dimensional, mutable table of values. To make a read-only copy of a 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 ConstructorSyntax
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 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 If you change values in a 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 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 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
Methods
Format of the Constructor's JavaScript Literal data Parameter You can initialize a 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, 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:
cols: [{id: 'A', label: 'NEW A', type: 'string'}, {id: 'B', label: 'B-label', type: 'number'}, {id: 'C', label: 'C-label', type: 'date'}]
The Each row object has one required property called 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 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 DataView Class A read-only view of an underlying DataTable. A A view is a live
window on the underlying
It is also possible to create a When you modify a You can combine 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}); ConstructorsThere are two ways to create a new 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 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
ChartWrapper Class A Another bonus of using However, 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!"); } } ConstructorChartWrapper(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. MethodsChartWrapper exposes the following additional methods:
Events The ChartWrapper object throws the following events. Note that you must call
ExampleThe 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 To use ChartEditor:
Methods
OptionsThe chart editor supports the following options:
EventsThe chart editor throws the following events:
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 <!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 The
group() Takes a populated 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 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 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 FunctionsThe API provides the following modifier functions that you can pass into the keys. modifier parameter to customize grouping behavior.
Provided Aggregation FunctionsThe API provides the following aggregation functions that you can pass into the columns. aggregation parameter array.
Creating a modifier function You can create a modifier function to perform a simple transformation onkey values before the // Input type: Date // Return type: number (1-4) function getQuarter(someDate) { return Math.floor(someDate.getMonth()/3) + 1; } Creating an aggregation functionYou 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 ( Syntax google.visualization.data.join(dt1, dt2, joinMethod, keys, dt1Columns, dt2Columns);dt1A 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:
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):
[[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 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 FormattersThe 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:
The actual formatting applied to the data is derived from the locale the API has been loaded with. For more details, see loading charts with a specific locale . Important: Formatters can only be used with a Here are the general steps for using a formatter: 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:
The Google Visualization API provides the following formatters:
ArrowFormatAdds 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. Options
Sample codevar data = new google.visualization.DataTable(); data.addColumn('string', 'Department'); data.addColumn('number', 'Revenues Change'); data.addRows([ ['Shoes', {v:12, f:'12.0%'}], ['Sports', {v:-7.3, f:'-7.3%'}], ['Toys', {v:0, f:'0%'}], ['Electronics', {v:-2.1, f:'-2.1%'}], ['Food', {v:22, f:'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}); BarFormatAdds a colored bar to a numeric cell indicating whether the cell value is above or below a specified base value. Options
Sample codevar data = new google.visualization.DataTable(); data.addColumn('string', 'Department'); data.addColumn('number', 'Revenues'); data.addRows([ ['Shoes', 10700], ['Sports', -15400], ['Toys', 12500], ['Electronics', -2100], ['Food', 22600], ['Art', 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, width: '100%', height: '100%'}); ColorFormat 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 Methods
Sample codevar data = new google.visualization.DataTable(); data.addColumn('string', 'Department'); data.addColumn('number', 'Revenues'); data.addRows([ ['Shoes', 10700], ['Sports', -15400], ['Toys', 12500], ['Electronics', -2100], ['Food', 22600], ['Art', 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, width: '100%', height: '100%'}); DateFormat Formats a JavaScript Options
Methods
Sample codefunction 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([ ['Mike', new Date(2008, 1, 28, 0, 31, 26), new Date(2008, 1, 28, 0, 31, 26), new Date(2008, 1, 28, 0, 31, 26)], ['Bob', new Date(2007, 5, 1, 0), new Date(2007, 5, 1, 0), new Date(2007, 5, 1, 0)], ['Alice', new Date(2006, 7, 16), new Date(2006, 7, 16), 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, width: '100%', height: '100%'}); } 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.,
NumberFormatDescribes 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. Options
Methods
Sample codevar data = new google.visualization.DataTable(); data.addColumn('string', 'Department'); data.addColumn('number', 'Revenues'); data.addRows([ ['Shoes', 10700], ['Sports', -15400], ['Toys', 12500], ['Electronics', -2100], ['Food', 22600], ['Art', 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, width: '100%', height: '100%'}); PatternFormat 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 Methods
Here are a few example inputs and outputs for a four-column table. Row before formatting (4 columns, 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 Sample codeThe 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([ ['John Lennon', ''], ['Paul McCartney', ''], ['George Harrison', ''], ['Ringo Starr', ''] ]); var table = new google.visualization.Table(document.getElementById('patternformat_div')); var formatter = new google.visualization.PatternFormat( '<a href="mailto:{1}">{0}</a>'); // Apply formatter and set the formatted value of the first column. formatter.format(data, [0, 1]); 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, width: '100%', height: '100%'}); GadgetHelperA helper class to simplify writing Gadgets that use the Google Visualization API. Constructorgoogle.visualization.GadgetHelper() Methods
Query ClassesThe following objects are available to send queries for data to an external data source, such as Google Spreadsheets.
QueryRepresents a query that is sent to a data source. Constructorgoogle.visualization.Query(dataSourceUrl, opt_options) Parameters dataSourceUrl [Required, String] URL to send the query to. See the Charts and Spreadsheets documentation for Google Spreadsheets. opt_options [Optional, Object] A map of options for the request. Note: If you are accessing a restricted data source , you should not use this parameter. Here are the supported properties:
Methods
QueryResponseRepresents 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. Methods
Error Display The API provides several functions to help you display custom error messages to your users. To use these functions, provide a container element on the page (typically a All functions are static functions in the namespace Many visualizations can throw an error event; see error event below to learn more about that. You can see an example custom error in the Query Wrapper Example.
EventsMost visualizations fire events to indicate something has occurred. As a user of the chart, you would often want to listen to these events. If you code your own visualization, you might also want to trigger such events on your own. The following methods enable developers to listen to events, remove existing event handlers or trigger events from inside a visualization.
addListener()Call this method to register to receive events fired by a visualization hosted on your page. You should document what event arguments, if any, will be passed to the handling function. google.visualization.events.addListener(source_visualization, event_name, handling_function)source_visualization A handle to the source visualization instance.event_name The string name of the event to listen for. A visualization should document which events it throws. handling_function The name of the local JavaScript function to call when source_visualization fires the event_name event. The handling function will be passed any event arguments as parameters. Returns A listener handler for the new listener. The handler can be used to later remove this listener if needed by calling google.visualization.events.removeListener(). 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'); } addOneTimeListener() This
is identical to An example of when this is useful: every draw causes a removeListener()Call this method to unregister an existing event listener. google.visualization.events.removeListener(listener_handler)listener_handler The listener handler to remove, as returned by google.visualization.events.addListener(). removeAllListeners()Call this method to unregister all event listeners of a specific visualization instance. google.visualization.events.removeAllListeners(source_visualization)source_visualization A handle to the source visualization instance from which all event listeners should be removed. trigger()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)source_visualization A handle to the source visualization instance. If you are calling this function from within a method defined by the sending visualization, you can simply pass in the this keyword. event_name A string name to call the event. You can choose any string value that you want. event_args [optional] A map of name/value pairs to pass to the receiving method. For example: {message: "Hello there!", score: 10, name: "Fred"}. You
can pass null if no events are needed; the receiver should be prepared to accept null for this parameter. 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); } Standard Visualization Methods and PropertiesEvery 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. ConstructorThe constructor should have the name of your visualization class, and return an instance of that class. visualization_class_name(dom_element)dom_elementA pointer to a DOM element where the visualization should be embedded. Example var org = new google.visualization.OrgChart(document.getElementById('org_div')); draw()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])data A DataTable or DataView holding the data to use to draw the chart. There is no standard method for extracting a
DataTable from a chart. options [Optional] A map of name/value pairs of custom options. Examples include height and width, background colors, and captions. The visualization documentation should list which options are available, and should support default options if you do not specify this parameter. You can use the JavaScript object literal syntax to pass in an options map: e.g., {x:100, y:200, title:'An Example'} Example chart.draw(myData, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'}); getAction()This is optionally exposed by visualizations that have tooltips and allow tooltip actions. Returns the tooltip action object with the
requested Example: // Returns the action object with the ID 'alertAction'. chart.getAction('alertAction'); getSelection()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 used to create the
visualization (a Example function myClickHandler(){ var selection = myVis.getSelection(); var message = ''; 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); } removeAction()This is optionally exposed by visualizations that have tooltips and allow tooltip actions. Removes the tooltip action
object with the requested Example: // Removes an action from chart with the ID of 'alertAction'. chart.removeAction('alertAction'); setAction()This is optionally exposed by visualizations that have tooltips and allow tooltip actions. It works only for core charts (bar, column, line, area, scatter, combo, bubble, pie, donut, candlestick, histogram, stepped area). Sets a tooltip action to be executed when the user clicks on the action text. setAction(action object) The Any and all tooltip actions should be set prior to calling the chart's Example: // Sets a tooltip action which will pop an alert box on the screen when triggered. chart.setAction({ id: 'alertAction', text: 'Trigger Alert', action: function() { alert('You have triggered an alert'); } }); The Example: // The visible/enabled functions can contain any logic to determine their state // as long as they return boolean values. chart.setAction({ id: 'alertAction', text: 'Trigger Alert', action: function() { alert('You have triggered an alert'); }, visible: function() { return true; }, enabled: function() { return true; } }); setSelection() Optionally selects a data entry in the visualization—for example, a point in an area chart, or a bar in a bar chart. When this method is called, the visualization should visually indicate what the new selection is. The implementation of Every time this method is called, all selected items are deselected, and the new selection list passed in should be applied. There is no explicit way to deselect individual items; to deselect individual items, call setSelection(selection_array)selection_array An array of objects, each with a numeric row and/or column property. row and column are the zero-based row or column number of an item in the data table to select. To select a whole column, set row to null; to select a whole row, set column to null. Example: setSelection([{row:0,column:1},{row:1, column:null}]) selects the cell at (0,1) and the entire row 1. Assorted Static Methods This section contains various useful methods exposed in the arrayToDataTable()This method takes in a two-dimensional array and converts it to a DataTable. The column data types are determined automatically by the data provided.
Column data types can also be specified using the object literal notation in the first row (the column header row) of the array (i.e. Syntax google.visualization.arrayToDataTable(twoDArray, opt_firstRowIsData)twoDArray A two-dimensional array, where each row represents a row in the data table. If opt_firstRowIsData is false (the default), the first row will be interpreted as header labels. The data types of each column are interpreted automatically from the data given. If a cell has no value, specify a null or empty value as appropriate. opt_firstRowIsData Whether the first row defines a header row or not. If true, all rows are assumed to be data. If false, the first row is assumed to be a header row, and the values are assigned as column labels. Default is false. Returns A new Examples The following code demonstrates three ways to create the same // Version 1: arrayToDataTable method var data2 = google.visualization.arrayToDataTable([ [{label: 'Country', type: 'string'}, {label: 'Population', type: 'number'}, {label: 'Area', type: 'number'}, {type: 'string', role: 'annotation'}], ['CN', 1324, 9640821, 'Annotated'], ['IN', 1133, 3287263, 'Annotated'], ['US', 304, 9629091, 'Annotated'], ['ID', 232, 1904569, 'Annotated'], ['BR', 187, 8514877, 'Annotated'] ]); // Version 2: DataTable.addRows var data3 = new google.visualization.DataTable(); data3.addColumn('string','Country'); data3.addColumn('number','Population'); data3.addColumn('number','Area'); data3.addRows([ ['CN', 1324, 9640821], ['IN', 1133, 3287263], ['US', 304, 9629091], ['ID', 232, 1904569], ['BR', 187, 8514877] ]); // Version 3: DataTable.setValue var data = new google.visualization.DataTable(); data.addColumn('string','Country'); data.addColumn('number', 'Population'); data.addColumn('number', 'Area'); data.addRows(5); data.setValue(0, 0, 'CN'); data.setValue(0, 1, 1324); data.setValue(0, 2, 9640821); data.setValue(1, 0, 'IN'); data.setValue(1, 1, 1133); data.setValue(1, 2, 3287263); data.setValue(2, 0, 'US'); data.setValue(2, 1, 304); data.setValue(2, 2, 9629091); data.setValue(3, 0, 'ID'); data.setValue(3, 1, 232); data.setValue(3, 2, 1904569); data.setValue(4, 0, 'BR'); data.setValue(4, 1, 187); data.setValue(4, 2, 8514877); drawChart()This method creates a chart in a single call. The advantage of using this method is that it requires slightly less code, and you can serialize and save visualizations as text strings for reuse. This method does not return a handle to the created chart, so you cannot assign method listeners to catch chart events. Syntax google.visualization.drawChart(chart_JSON_or_object)chart_JSON_or_object Either a JSON literal string or a JavaScript object, with the following properties (case-sensitive):
Examples Creates a table chart based on a spreadsheet data source, and includes the query SELECT A,D WHERE D > 100 ORDER BY D <script type="text/javascript"> google.charts.load('current'); // Note: No need to specify chart packages. function drawVisualization() { google.visualization.drawChart({ "containerId": "visualization_div", "dataSourceUrl": "https://spreadsheets.google.com/a/google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1", "query":"SELECT A,D WHERE D > 100 ORDER BY D", "refreshInterval": 5, "chartType": "Table", "options": { "alternatingRowStyle": true, "showRowNumber" : true } }); } google.charts.setOnLoadCallback(drawVisualization); </script> This next example creates the same table, but creates a <script type='text/javascript'> google.charts.load('current'); function drawVisualization() { var dataTable = [ ["Country", "Population Density"], ["Indonesia", 117], ["China", 137], ["Nigeria", 142], ["Pakistan", 198], ["India", 336], ["Japan", 339], ["Bangladesh", 1045] ]; google.visualization.drawChart({ "containerId": "visualization_div", "dataTable": dataTable, "refreshInterval": 5, "chartType": "Table", "options": { "alternatingRowStyle": true, "showRowNumber" : true, } }); } google.charts.setOnLoadCallback(drawVisualization); </script> This example passes in a JSON string representation of the chart, which you might have loaded from a file: <script type="text/javascript"> google.charts.load('current'); var myStoredString = '{"containerId": "visualization_div",' + '"dataSourceUrl": "https://spreadsheets.google.com/a/google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1",' + '"query":"SELECT A,D WHERE D > 100 ORDER BY D",' + '"refreshInterval": 5,' + '"chartType": "Table",' + '"options": {' + ' "alternatingRowStyle": true,' + ' "showRowNumber" : true' + '}' + '}'; function drawVisualization() { google.visualization.drawChart(myStoredString); } google.charts.setOnLoadCallback(drawVisualization); </script> drawToolbar()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. 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 2021-03-22 UTC. [{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }] What dialog box displays when you click the External data tab and then click the Excel button in the Export group quizlet?Import an Excel worksheet into an Access database with the Excel button in this group on the External Data tab. Click this button in the Export group to display the Export-Excel Spreadsheet wizard dialog box.
How many database objects can you export to Excel at a time?You can export only one object at a time. To export multiple objects, repeat the export operation for each object, or do an import operation from within the destination database.
What is displayed in the three row grid in the middle of the Edit Relationships dialog box?What is displayed in the three-row grid in the middle of the Edit Relationships window? one row to display in the results datasheet for each group.
On which tab in Access will you find buttons for exporting data?To export data from Access, first select the table or other database object to export in the Navigation Pane. Then click the “External Data” tab in the Ribbon. Then click the button in the “Export” button group for the file format to which to export the object.
|