【发布时间】:2025-12-25 03:50:11
【问题描述】:
请帮助我,我是谷歌图表脚本的新手。你能给我正确的堆积比例柱形图脚本吗?谷歌图表中没有复杂的代码?以及如何组合两个图表......如果你能帮助我,我很高兴。谢谢
这是组合图表的示例照片:
下面是复杂代码的堆积比例柱形图脚本:
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Belgium', 'Czech Republic', 'Finland', 'France', 'Germany'],
['2003', 1336060, 3817614, 974066, 1104797, 6651824, 15727003],
['2004', 1538156, 3968305, 928875, 1151983, 5940129, 17356071],
['2005', 1576579, 4063225, 1063414, 1156441, 5714009, 16716049],
['2006', 1600652, 4604684, 940478, 1167979, 6190532, 18542843],
['2007', 1968113, 4013653, 1037079, 1207029, 6420270, 19564053],
['2008', 1901067, 6792087, 1037327, 1284795, 6240921, 19830493]
]);
var view = new google.visualization.DataView(data);
var columns = [0];
for (var i = 1; i < data.getNumberOfColumns(); i++) {
// add a column that calculates the proportional value of this column to the total
columns.push({
type: 'number',
label: data.getColumnLabel(i),
calc: (function (col) {
return function (dt, row) {
var val = dt.getValue(row, col);
var total = 0;
for (var j = 1; j < dt.getNumberOfColumns(); j++) {
total += dt.getValue(row, j);
}
return (total == 0) ? null : {v: val / total, f: val.toString()};
};
})(i)
});
// add an annotation column that puts a label on the bar
columns.push({
type: 'string',
role: 'annotation',
sourceColumn: i,
calc: 'stringify'
});
}
view.setColumns(columns);
var options = {
title:"Yearly Coffee Consumption by Country",
width:1000, height:400,
isStacked: true,
hAxis: {title: "Year"},
vAxis: {
format: '#%'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(view, options);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawVisualization});
【问题讨论】:
-
该代码有效,它恰好是创建比例堆叠柱形图的最直接方法。没有比这更复杂的方法了。
-
我明白了。请你能解释一下它是如何工作的......在“var columns”里面吗?
标签: javascript charts google-visualization