Prepare the Data

    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">

      // Load the Visualization API and the piechart package.
      google.load('visualization', '1.0', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.

      // Callback that creates and populates a data table, 
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

      // Create the data table.
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Topping');
      data.addColumn('number', 'Slices');
        ['Mushrooms', 3],
        ['Onions', 1],
        ['Olives', 1], 
        ['Zucchini', 1],
        ['Pepperoni', 2]

      // Set chart options
      var options = {'title':'How Much Pizza I Ate Last Night',

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);

<!--Div that will hold the pie chart-->
    <div id="chart_div" style="width:400; height:300"></div>


Create a DataTable

All charts require data. Google Chart Tools charts require data to be wrapped in a JavaScript class called google.visualization.DataTable. This class is defined in the Google Visualization library that you loaded previously.

A DataTable is a two-dimensional table with rows and columns, where each column has a datatype, an optional ID, and an optional label. The example above creates the following table:

type: string
label: Topping
type: number
label: Slices
Mushrooms 3
Onions 1
Olives 1
Zucchini 1
Pepperoni 2

There are several ways to create a DataTable; you can see a list and comparison of each technique in DataTables and DataViews. You can modify your data after you add it, and add, edit, or remove columns and rows.

You must organize your chart's DataTable in a format that the chart expects: for instance, both the Bar and Pie charts require a two-column table where each row represents a slice or bar. The first column is the slice or bar label, and the second column is the slice or bar value. Other charts require different and possibly more complex table formats. See your chart's documentation to learn the required data format.

Rather than populate a table yourself, you could instead query a website that supports the Chart Tools Datasource protocol--for example, a Google Spreadsheets page. Using the google.visualization.Query object, you can send a query to a website and receive a populated DataTable object that you can pass into your chart. See the advanced topic Querying a Datasource to learn how to send a query.


More Information