我正在使用Google可视化API条形图。我需要能够使用以下代码执行一些操作:
http://jsfiddle.net/wesbos/EQ4kc/
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["dummy","Question 1", "Question 2", " Question 3"],
[0,81, 122, 10 ]
]);
var options = {
title: '',
vAxis: {
title: '',
gridlines : {
count : 5,
color: 'white'
}
},
hAxis: {
title: '',
format : '#%',
gridlines : {
count : 5,
color: 'white'
}
},
colors: ['#be1e2d', '#74b749', '#0daed3', '#ffb400', '#f63131'],
legend : {
position: 'bottom'
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
答案 0 :(得分:6)
为此,您必须将数据转换为百分比。您可以使用DataView来处理此问题:
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: data.getColumnLabel(1),
calc: function (dt, row) {
var val = dt.getValue(row, 1);
for (var i = 1, total = 0, cols = dt.getNumberOfColumns(); i < cols; i++) {
total += dt.getValue(row, i);
}
var percent = val / total;
// what you do here depends on how you want to display the data in the tooltips
// option 1: use the value of the data point:
return {v: percent, f: dt.getFormattedValue(row, 1)};
// option 2: use the percent:
return {v: percent, f: (percent * 100).toFixed(2) + '%'};
}
}, {
type: 'number',
label: data.getColumnLabel(2),
calc: function (dt, row) {
var val = dt.getValue(row, 2);
for (var i = 1, total = 0, cols = dt.getNumberOfColumns(); i < cols; i++) {
total += dt.getValue(row, i);
}
var percent = val / total;
// what you do here depends on how you want to display the data in the tooltips
// option 1: use the value of the data point:
return {v: percent, f: dt.getFormattedValue(row, 2)};
// option 2: use the percent:
return {v: percent, f: (percent * 100).toFixed(2) + '%'};
}
}, {
type: 'number',
label: data.getColumnLabel(3),
calc: function (dt, row) {
var val = dt.getValue(row, 3);
for (var i = 1, total = 0, cols = dt.getNumberOfColumns(); i < cols; i++) {
total += dt.getValue(row, i);
}
var percent = val / total;
// what you do here depends on how you want to display the data in the tooltips
// option 1: use the value of the data point:
return {v: percent, f: dt.getFormattedValue(row, 3)};
// option 2: use the percent:
return {v: percent, f: (percent * 100).toFixed(2) + '%'};
}
}]);
然后使用视图而不是数据绘制图表:
chart.draw(view, options);