可视化数据网页开发Google Charts(二):数据准备

<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是一个包含行和列的二维表,其中每个列都有一个数据类型、一个可选ID和一个可选标签。上面的例子创建了下面的表格:

所有图表都需要数据。谷歌图表工具图表需要将数据封装在一个名为Google . visualiz.datatable的JavaScript类中。这个类是在您之前加载的谷歌可视化库中定义的。

有几种方法可以创建数据表;您可以在DataTables和DataViews中看到每种技术的列表和比较。您可以在添加数据、添加、编辑或删除列和行之后修改数据。

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

您可以查询一个支持图表工具数据源协议的网站,而不是自己填充一个表——例如,一个谷歌电子表格页面。使用google.visualization。查询对象,您可以向网站发送一个查询,并接收一个填充的数据表对象,您可以将该对象传递到图表中。查看查询数据源的高级主题,了解如何发送查询。

猜你喜欢

转载自blog.csdn.net/Lzs1998/article/details/88343300