Stay organized with collectionsSave and categorize content based on your preferences.
This page lists the different ways that you can instantiate and draw a chart on the page. Each method has advantages and disadvantages, as listed below.
This is the basic method covered in theHello Chart! examplein this documentation. Here are the basic steps:
Load the gstatic library loader, Google Visualization, and chart libraries
Prepare your data
Prepare any chart options
Instantiate the chart class, passing in a handle to the page container element.
Optionally register to receive any chart events. If you intend to call methods on the chart, you should listen for the "ready" event.
Callchart.draw(), passing in the data and options.
Advantages:
You have complete control over every step of the process.
You can register to listen for all events thrown by the chart.
Disadvantages:
Verbose
You must explicitly load all required chart libraries.
If you send queries, you must manually implement for the callback, check for success, extract the returnedDataTable, and pass it to the chart.
Example:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var data;
var chart;
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create our data table.
data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
function selectHandler() {
var selectedItem = chart.getSelection()[0];
var value = data.getValue(selectedItem.row, 0);
alert('The user selected ' + value);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
</body>
</html>
ChartWrapper
ChartWrapperis a convenience class that handles loading all the appropriate chart libraries for you and also simplifies sending queries to Chart Tools Datasources.
Advantages:
Much less code
Loads all the required chart libraries for you
Makes querying Datasources much easier by creating theQueryobject and handling the callback for you
Pass in the container element ID, and it will call getElementByID for you.
Data can be submitted in a variety of formats: as an array of values, as a JSON literal string, or as aDataTablehandle
Disadvantages:
ChartWrappercurrently propagates only the select, ready, and error events. To get other events, you must get a handle to the wrapped chart and subscribe to events there. See theChartWrapperdocumentationfor examples.
Examples:
Here's an example of a column chart with locally constructed data specified as an array. You cannot specify chart labels or datetime values using the array syntax, but you could manually create aDataTableobject with those values and pass that to thedataTableproperty.
Here's an example of a line chart that gets its data by querying a Google Spreadsheet. Note that the code doesn't need to handle the callback.
<html>
<head>
<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() {
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': 'Countries'},
containerId: 'vis_div'
});
wrapper.draw()
// No query callback handler needed!
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="vis_div" style="width: 600px; height: 400px;"></div>
</body>
</html>
Combined withautoloading, this can make for very compact code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current'); // Don't need to specify chart libraries!
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
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': 'Countries'},
containerId: 'vis_div'
});
wrapper.draw()
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="vis_div" style="width: 600px; height: 400px;"></div>
</body>
</html>
Using the Chart Editor with ChartWrapper
You can use the Chart Editor dialog built into Google
Spreadsheets to design a chart and then request the serializedChartWrapperstring that represents the chart. You can then copy and paste this string and use it as
described above inChartWrapper.
You can embed a chart editor on your own page and expose methods for users to connect to other data sources and return theChartWrapperstring. See theChartEditorreference documentationfor more information.
DrawChart()
DrawChartis a global static method that wraps aChartWrapper.
Advantages:
Same asChartWrapper, but slightly shorter to use.
Disadvantages:
Does not return a handle to the wrapper, so you cannot handle any events.
<DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current'); // Don't need to specify chart libraries!
google.charts.setOnLoadCallback(drawVisualization);
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>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization_div" style="width: 600px; height: 400px;"></div>
</body>
</html>
[[["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."],[[["\u003cp\u003eThis page explains three ways to create and display Google Charts: \u003ccode\u003echart.draw()\u003c/code\u003e, \u003ccode\u003eChartWrapper\u003c/code\u003e, and \u003ccode\u003eDrawChart()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003echart.draw()\u003c/code\u003e offers the most control but requires more code and manual library loading.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eChartWrapper\u003c/code\u003e and \u003ccode\u003eDrawChart()\u003c/code\u003e simplify chart creation, automatically loading libraries and handling data queries, but may offer less event control.\u003c/p\u003e\n"],["\u003cp\u003eEach method has advantages and disadvantages, allowing you to choose the best approach for your needs based on factors like code complexity and event handling requirements.\u003c/p\u003e\n"]]],[],null,["# Chart Drawing Techniques\n\nThis page lists the different ways that you can instantiate and draw a chart on the page. Each method has advantages and disadvantages, as listed below.\n\nContents\n--------\n\n1. [chart.draw()](#chart.draw)\n2. [ChartWrapper](#chartwrapper)\n3. [DrawChart()](#drawchart)\n4. [More Information](#moreinfo)\n\nchart.draw()\n------------\n\nThis is the basic method covered in the [Hello Chart! example](/chart/interactive/docs/quick_start) in this documentation. Here are the basic steps:\n\n1. Load the gstatic library loader, Google Visualization, and chart libraries\n2. Prepare your data\n3. Prepare any chart options\n4. Instantiate the chart class, passing in a handle to the page container element.\n5. Optionally register to receive any chart events. If you intend to call methods on the chart, you should listen for the \"ready\" event.\n6. Call `chart.draw()`, passing in the data and options.\n\n**Advantages:**\n\n- You have complete control over every step of the process.\n- You can register to listen for all events thrown by the chart.\n\n**Disadvantages:**\n\n- Verbose\n- You must explicitly load all required chart libraries.\n- If you send queries, you must manually implement for the callback, check for success, extract the returned `DataTable`, and pass it to the chart.\n\n**Example:** \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003c!--Load the AJAX API--\u003e\n \u003cscript type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript type=\"text/javascript\"\u003e\n var data;\n var chart;\n\n // Load the Visualization API and the piechart package.\n google.charts.load('current', {'packages':['corechart']});\n\n // Set a callback to run when the Google Visualization API is loaded.\n google.charts.setOnLoadCallback(drawChart);\n\n // Callback that creates and populates a data table,\n // instantiates the pie chart, passes in the data and\n // draws it.\n function drawChart() {\n\n // Create our data table.\n data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows([\n ['Mushrooms', 3],\n ['Onions', 1],\n ['Olives', 1],\n ['Zucchini', 1],\n ['Pepperoni', 2]\n ]);\n\n // Set chart options\n var options = {'title':'How Much Pizza I Ate Last Night',\n 'width':400,\n 'height':300};\n\n // Instantiate and draw our chart, passing in some options.\n chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n google.visualization.events.addListener(chart, 'select', selectHandler);\n chart.draw(data, options);\n }\n\n function selectHandler() {\n var selectedItem = chart.getSelection()[0];\n var value = data.getValue(selectedItem.row, 0);\n alert('The user selected ' + value);\n }\n\n \u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003c!--Div that will hold the pie chart--\u003e\n \u003cdiv id=\"chart_div\" style=\"width:400; height:300\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n```\n\nChartWrapper\n------------\n\n[ChartWrapper](/chart/interactive/docs/reference#chartwrapperobject) is a convenience class that handles loading all the appropriate chart libraries for you and also simplifies sending queries to Chart Tools Datasources.\n\n**Advantages:**\n\n- Much less code\n- Loads all the required chart libraries for you\n- Makes querying Datasources much easier by creating the `Query` object and handling the callback for you\n- Pass in the container element ID, and it will call getElementByID for you.\n- Data can be submitted in a variety of formats: as an array of values, as a JSON literal string, or as a `DataTable` handle\n\n**Disadvantages:**\n\n- `ChartWrapper` currently propagates only the select, ready, and error events. To get other events, you must get a handle to the wrapped chart and subscribe to events there. See the [`ChartWrapper` documentation](/chart/interactive/docs/reference#chartwrapperobject) for examples.\n\n**Examples:**\n\nHere's an example of a column chart with locally constructed data specified as an array. You cannot specify chart labels or datetime values using the array syntax, but you could manually create a `DataTable` object with those values and pass that to the `dataTable` property. \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003cscript type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript type=\"text/javascript\"\u003e\n google.charts.load('current'); // Don't need to specify chart libraries!\n google.charts.setOnLoadCallback(drawVisualization);\n\n function drawVisualization() {\n var wrapper = new google.visualization.ChartWrapper({\n chartType: 'ColumnChart',\n dataTable: [['', 'Germany', 'USA', 'Brazil', 'Canada', 'France', 'RU'],\n ['', 700, 300, 400, 500, 600, 800]],\n options: {'title': 'Countries'},\n containerId: 'vis_div'\n });\n wrapper.draw();\n }\n \u003c/script\u003e\n \u003c/head\u003e\n \u003cbody style=\"font-family: Arial;border: 0 none;\"\u003e\n \u003cdiv id=\"vis_div\" style=\"width: 600px; height: 400px;\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n```\n\nHere's an example of a line chart that gets its data by querying a Google Spreadsheet. Note that the code doesn't need to handle the callback. \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003cscript type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript type=\"text/javascript\"\u003e\n google.charts.load('current');\n google.charts.setOnLoadCallback(drawVisualization);\n\n function drawVisualization() {\n var wrapper = new google.visualization.ChartWrapper({\n chartType: 'LineChart',\n dataSourceUrl: 'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1',\n query: 'SELECT A,D WHERE D \u003e 100 ORDER BY D',\n options: {'title': 'Countries'},\n containerId: 'vis_div'\n });\n wrapper.draw()\n\n // No query callback handler needed!\n }\n \u003c/script\u003e\n \u003c/head\u003e\n \u003cbody style=\"font-family: Arial;border: 0 none;\"\u003e\n \u003cdiv id=\"vis_div\" style=\"width: 600px; height: 400px;\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n```\n\nCombined with [autoloading](/chart/interactive/docs/library_loading_enhancements#enhancedloading), this can make for very compact code: \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003cscript type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript type=\"text/javascript\"\u003e\n google.charts.load('current'); // Don't need to specify chart libraries!\n google.charts.setOnLoadCallback(drawVisualization);\n\n function drawVisualization() {\n var wrapper = new google.visualization.ChartWrapper({\n chartType: 'LineChart',\n dataSourceUrl: 'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1',\n query: 'SELECT A,D WHERE D \u003e 100 ORDER BY D',\n options: {'title': 'Countries'},\n containerId: 'vis_div'\n });\n wrapper.draw()\n }\n \u003c/script\u003e\n \u003c/head\u003e\n \u003cbody style=\"font-family: Arial;border: 0 none;\"\u003e\n \u003cdiv id=\"vis_div\" style=\"width: 600px; height: 400px;\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n``` \n\n### Using the Chart Editor with ChartWrapper\n\nYou can use the Chart Editor dialog built into Google\nSpreadsheets to design a chart and then request the serialized `ChartWrapper`\nstring that represents the chart. You can then copy and paste this string and use it as\ndescribed above in [ChartWrapper](#chartwrapper).\n\nYou can embed a chart editor on your own page and expose methods for users to connect to other data sources and return the `ChartWrapper` string. See the [`ChartEditor` reference documentation](/chart/interactive/docs/reference#google_visualization_charteditor) for more information.\n\nDrawChart()\n-----------\n\n`DrawChart` is a global static method that wraps a `ChartWrapper`.\n\n**Advantages:**\n\n- Same as `ChartWrapper`, but slightly shorter to use.\n\n**Disadvantages:**\n\n- Does not return a handle to the wrapper, so you cannot handle any events.\n\n```html\n\u003cDOCTYPE html\u003e\n\u003chtml\u003e\n \u003chead\u003e\n \u003cscript type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript type=\"text/javascript\"\u003e\n google.charts.load('current'); // Don't need to specify chart libraries!\n google.charts.setOnLoadCallback(drawVisualization);\n function drawVisualization() {\n google.visualization.drawChart({\n \"containerId\": \"visualization_div\",\n \"dataSourceUrl\": \"https://spreadsheets.google.com/a/google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1\",\n \"query\":\"SELECT A,D WHERE D \u003e 100 ORDER BY D\",\n \"refreshInterval\": 5,\n \"chartType\": \"Table\",\n \"options\": {\n \"alternatingRowStyle\": true,\n \"showRowNumber\" : true\n }\n });\n }\n google.charts.setOnLoadCallback(drawVisualization);\n \u003c/script\u003e\n \u003c/head\u003e\n \u003cbody style=\"font-family: Arial;border: 0 none;\"\u003e\n \u003cdiv id=\"visualization_div\" style=\"width: 600px; height: 400px;\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n```\n\nMore Information\n----------------\n\n- [`ChartEditor` reference documentation](/chart/interactive/docs/reference#google_visualization_charteditor)\n- Generic [`chart.draw()`](/chart/interactive/docs/reference#visdraw) documentation\n- [`ChartWrapper` reference documentation](/chart/interactive/docs/reference#chartwrapperobject)\n- [`DrawChart` reference documentation](/chart/interactive/docs/reference#google.visualization.drawchart)"]]