从两个阵列创建Google Chart数据表数组

时间:2013-04-07 23:48:16

标签: javascript arrays google-visualization

我正在尝试使用Google的图表API:https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart

我有两个数组,我想用它来生成和标记可视化。但是,我找不到将这些数组组合并转换为适当对象结构的方法。

我的数组如下,其内容紧挨着它们:

years;   // 2014,2015,2020,2021
sales;   // 100,100,200,100

我需要动态使用这些数组来构建此对象,该对象采用Google API使用的格式:

 var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales'],
          ['2014',  100],
          ['2015',  100],
          ['2020',  200],
          ['2021',  100]
        ]);

感谢您的帮助。

2 个答案:

答案 0 :(得分:20)

您应该在for循环中使用addColumnaddRow来浏览数组。

以下是一个示例:

function drawVisualization() {
  // Create and populate the data table.
  var years = ['2001', '2002', '2003', '2004', '2005'];
  var sales = [1, 2, 3, 4, 5];

  var data = new google.visualization.DataTable();
  data.addColumn('string', 'years');
  data.addColumn('number', 'sales');

  for(i = 0; i < years.length; i++)
    data.addRow([years[i], sales[i]]);

  // Create and draw the visualization.
  new google.visualization.LineChart(document.getElementById('visualization')).
    draw(data, {});
}

答案 1 :(得分:0)

下面是完整的代码,数据填充分开。

<?php

function testing($chartId, $chartFunc, $chartTitle, $xAxisTitle, $chartData, $chartType)
{
$pageMeat =<<<EOD
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback($chartFunc);
function $chartFunc() {
var data = google.visualization.arrayToDataTable($chartData);

var options = {
title: '$chartTitle',
hAxis: {title: '$xAxisTitle', titleTextStyle: {color: 'red'}}
};
EOD;

if($chartType == "line") {
$pageMeat .=<<<EOD
var chart = new google.visualization.LineChart(document.getElementById('$chartId'));
EOD;
}
else if($chartType == "pie") {
$pageMeat .=<<<EOD
var chart = new google.visualization.PieChart(document.getElementById('$chartId'));
EOD;
}
else {
$pageMeat .=<<<EOD
var chart = new google.visualization.ColumnChart(document.getElementById('$chartId'));
EOD;
}
$pageMeat .=<<<EOD
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="$chartId" style="width: 900px; height: 500px;"></div>
</body>
</html>
EOD;
echo $pageMeat;
}

$gChartId = "vertColumns";
$gChartFn = "columnChart";
$gChartTitle = "Company Performance";
$gXAxisTitle = "Year";

$gChartData[] = array('Year', 'Sales', 'Expenses');
$gChartData[] = array('2004', 1000, 400);
$gChartData[] = array('2005', 1170, 460);
$gChartData[] = array('2006', 660, 1120);
$gChartData[] = array('2007', 1030, 540);

testing($gChartId, $gChartFn, $gChartTitle, $gXAxisTitle, json_encode($gChartData), "column");
?>