准备数据

<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 和可选标签。上面的示例创建了下表:

类型:字符串
标签:浇头
类型:数字
标签:Slice
蘑菇酱汁 3
洋葱 1
橄榄 1
西奇尼 1
意大利香肠 2

您可以通过多种方式创建 DataTable;您可以在 DataTables 和 DataViews 中查看每种分析的列表和对比。您可以在添加数据后对其进行修改,以及添加、修改或移除列和行。

您必须按照图表要求的格式组织图表的 DataTable:例如,条形图饼图都需要一个两列的表,其中每一行代表一个切片或条形。第一列是切片或条形标签,第二列是切片或条形值。其他图表需要不同且可能更复杂的表格式。请参阅图表的文档,了解所需的数据格式。

您可以自行查询支持图表工具数据源协议的网站(例如 Google 电子表格页面),而不是自己填充表格。使用 google.visualization.Query 对象,您可以向网站发送查询,并收到可填充到图表中的 DataTable 对象。请参阅高级主题查询数据源,了解如何发送查询。

 

详细信息