Adr*_*Bob 11 javascript visualization google-api
我想创建一个柱形图,使用Google Visualization API,我可以发送数据以数组形式填充图表的DataTable.但我需要生成具有可变数量的列/行的图表,具体取决于我的数组包含的内容,我不知道如何正确迭代它们并将它们添加到DataTable.
以下是解析STATIC数据以生成图表的示例:(所有这些都在javascript中)
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
Run Code Online (Sandbox Code Playgroud)
API具有以下用于添加列和行的方法: - 获取与上述相同数据的不同方法:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([ ['2004', 1000 , 400], ['2005', 1170, 460], ['2006', 660, 1120], ['2007',1030,540]
]);
Run Code Online (Sandbox Code Playgroud)
我需要的是for循环或双循环迭代我发送的arraylists并动态添加行内容.
更准确地说,在一种情况下我会说上面写的数据,而在其他情况下我会这样:
['Year', 'Sales', 'Expenses' , 'Other'],
['2004', 1000, 400 , 232 ],
['2005', 1170, 460 , 421 ],
['2006', 660, 1120 , 4324 ],
['2007', 1030, 540 , 4234 ],
['2008', 1530, 50 , 234 ],
Run Code Online (Sandbox Code Playgroud)
所以我会通过函数中的参数解析这些数据,让我们说(我不知道这是否是正确的想法)许多包含每一行的arraylists:Row1 = ['2004',1000,400,232] Row2 = [' 2005',1170,460,421]和....
我如何使用for循环或双循环来迭代我发送到动态生成包含数据的数据表(包含可变数量的行和列)的arraylists?
Gre*_*oss 22
这是jsfiddle中的一个有效解决方案.
看看下面的功能.这将遍历数据数组并更新图表:
// function to update the chart with new data.
function updateChart() {
dataTable = new google.visualization.DataTable();
var newData = [['Year', 'Sales', 'Expenses' , 'Other'],
['2004', 1000, 400 , 232 ],
['2005', 1170, 460 , 421 ],
['2006', 660, 1120 , 4324 ],
['2007', 1030, 540 , 4234 ],
['2008', 1530, 50 , 234 ]];
// determine the number of rows and columns.
var numRows = newData.length;
var numCols = newData[0].length;
// in this case the first column is of type 'string'.
dataTable.addColumn('string', newData[0][0]);
// all other columns are of type 'number'.
for (var i = 1; i < numCols; i++)
dataTable.addColumn('number', newData[0][i]);
// now add the rows.
for (var i = 1; i < numRows; i++)
dataTable.addRow(newData[i]);
// redraw the chart.
chart.draw(dataTable, options);
}
Run Code Online (Sandbox Code Playgroud)