準備資料

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // 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 the data table.
      var 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.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

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

 

建立 DataTable

所有圖表都需要資料。Google 圖表工具圖表需要將資料包裝在名為 google.visualization.DataTable 的 JavaScript 類別中。這個類別是在您先前載入的 Google 視覺化程式庫中定義。

DataTable 是包含資料列和資料欄的二維資料表,其中各資料欄含有資料類型、選用 ID 和選用的標籤。以上範例會建立下列資料表:

類型:字串
標籤:配料
type: 數字
label: Slices
蘑菇 3
洋蔥 1
橄欖 1
櫛瓜 1
義式臘腸 2

建立 DataTable 的方法有很多種,您可以在 DataTables 和 DataView 中查看每個技巧的清單和比較。您可以在新增後修改資料,以及新增、編輯或移除資料欄和資料列。

您必須以圖表預期的格式整理圖表的 DataTable,例如,「長條圖」和「圓餅圖」 需要兩個資料欄,每個資料列代表一個配量或長條圖。第一欄為 Slice 或 Bar 標籤,第二個資料欄則是 Slice 或 Bar 值。其他圖表需要不同且可能更複雜的資料表格式。請參閱圖表的說明文件,瞭解所需資料格式。

您不用自行為表格填入資料,而是改為查詢支援圖表工具資料來源通訊協定的網站 (例如 Google 試算表頁面)。使用 google.visualization.Query 物件,您可以將查詢傳送至網站,並接收填入的 DataTable 物件,並傳遞至圖表。請參閱進階主題查詢資料來源,瞭解如何傳送查詢。

 

更多資訊