本文介绍了如何使用Javascript更改DataTable的Google Chart API中的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 我想在
中更改DataTable中数据的格式,以使其更加灵活,并且Chart与第一个
仍然相同。
默认值:
['Year','Sales','Expenses'],
['2004',1000,400],
['2005',1170,460],
['2006',660,1120],
['2007',1030,540]
它必须是: $ b
['Year','2004','2005 ','2006','2007'],
['Sales',1000,1170,660,1030],
['Expenses',400,460,1120,540]
HTML:
< div id =chart_divstyle =width:450px; height:300px;><< ; / DIV>
Javascript:
google.load(visualization,1,{packages:[corechart]});
google.setOnLoadCallback(drawChart);
函数drawChart(){
var data = google.visualization.arrayToDataTable([
['Year','Sales','Expenses'],
['2004', 1000',400],
['2005',1170,460],
['2006',660,1120],
['2007',1030,540]
]);
var options = {
title:'公司表现'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options);
解决方案
var data = google.visualization.arrayToDataTable(transposeArray([
['Year','2004','2005','2006' ,'2007'],
['Sales',1000,1170,660,1030],
['Expenses',400,460,1120,540]
]));
函数transposeArray(array){
return array [0] .map(function(col,i){
return array.map(function(row){
return row [i];
});
});
}
在将数据传递给 arrayToDataTable $ c $
移调 -
方法 map
-
- I would like to change the format of the data in the DataTable inorder to make it more flexible and the Chart is still the same withthe first one.
Default:
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
It must be:
['Year', '2004', '2005', '2006', '2007'],
['Sales', 1000, 1170, 660, 1030],
['Expenses', 400 ,460, 1120, 540]
HTML:
<div id="chart_div" style="width: 450px; height: 300px;"></div>
Javascript:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
解决方案
You must transpose array like: http://jsfiddle.net/krzysztof_safjanowski/Mw398/1/
var data = google.visualization.arrayToDataTable(transposeArray([
['Year', '2004', '2005', '2006', '2007'],
['Sales', 1000, 1170, 660, 1030],
['Expenses', 400, 460, 1120, 540]
]));
function transposeArray(array) {
return array[0].map(function (col, i) {
return array.map(function (row) {
return row[i];
});
});
}
Before pass data to arrayToDataTable
you mast prepare it in format that google charts will understand.
Transpose – http://en.wikipedia.org/wiki/Transpose
Method map
– https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
这篇关于如何使用Javascript更改DataTable的Google Chart API中的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!