虽然我使用Table工作,但饼图不会查看

时间:2018-03-04 08:48:05

标签: javascript charts google-visualization google-chartwrapper

我正在尝试使用JSON格式数据查看饼图当我尝试使用表格图表工作正常时

我认为问题在于解析JSON,但我不知道它究竟在哪里

我还检查了有关此主题的问题,但没有使用它,就像他们使用PHP作为服务器端但不是那样在HTML页面上使用javascript

这就是代码

<html>   
    <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

    google.charts.load('current', {
       callback: drawChart,
        packages:['table']
      });

function drawChart() {
  var jsonData = [
    {"Car":23,"Bus":2,"Motorcycle":10,"Person":7},
    {"Car":5,"Bus":6,"Motorcycle":9,"Person":8},
    {"Car":10,"Bus":20,"Motorcycle":36,"Person":13}
  ];

  var gglData = [];
  if (jsonData.length > 0) {
    // load column headings
    var colHead = [];
    Object.keys(jsonData[0]).forEach(function (key) {
      colHead.push(key);
    });
    gglData.push(colHead);

    // load data rows
    jsonData.forEach(function (row) {
      var gglRow = [];
      Object.keys(row).forEach(function (key) {
        gglRow.push(row[key]);
      });
      gglData.push(gglRow);
    });
  }


  var data = google.visualization.arrayToDataTable(gglData);
  var table = new google.visualization.Table(document.getElementById('table_div'));
  table.draw(data);
  }
</script>
    </head>        
<body>
<!--Div that will hold the pie chart-->
<div id="table_div"></div>
</body>
 </html>

1 个答案:

答案 0 :(得分:1)

首先,你必须包括包 - &gt; 'corechart'

接下来,检查data format饼图,确认 数据需要在行与列之间......

请参阅以下工作片段,
每个键/值对作为单独的行添加,
那么group()方法用于聚合......

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart', 'table']
});

function drawChart() {
  var jsonData = [
    {"Car":23,"Bus":2,"Motorcycle":10,"Person":7},
    {"Car":5,"Bus":6,"Motorcycle":9,"Person":8},
    {"Car":10,"Bus":20,"Motorcycle":36,"Person":13}
  ];

  var gglData = [['Vehicle', 'Value']];
  jsonData.forEach(function (row) {
    Object.keys(row).forEach(function (key) {
      gglData.push([key, row[key]]);
    });
  });
  var data = google.visualization.arrayToDataTable(gglData);

  var groupData = google.visualization.data.group(
    data,
    [0],
    [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
  );

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(groupData);
  var table = new google.visualization.Table(document.getElementById('table_div'));
  table.draw(groupData);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="table_div"></div>