如何获取Google图表中的总数和百分比? 我只是想获得谷歌图表中的百分比和数字,是否有需要设置的选项?
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population',],
['New York City, NY', 8175000],
['Los Angeles, CA', 3792000],
['Chicago, IL', 2695000],
['Houston, TX', 2099000],
['Philadelphia, PA', 1526000]
]);
var options = {
title: 'Population of Largest U.S. Cities',
chartArea: {width: '50%'},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
以下示例输出:
答案 0 :(得分:1)
使用group方法查找总数
var groupData = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
和DataView
添加'annotation'
列
请参阅以下工作代码段...
google.charts.load('current', {
callback: drawBasic,
packages: ['corechart']
});
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population',],
['New York City, NY', 8175000],
['Los Angeles, CA', 3792000],
['Chicago, IL', 2695000],
['Houston, TX', 2099000],
['Philadelphia, PA', 1526000]
]);
var groupData = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var formatPercent = new google.visualization.NumberFormat({
pattern: '#,##0.0%'
});
var formatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var amount = formatShort.formatValue(dt.getValue(row, 1));
var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));
return amount + ' (' + percent + ')';
},
type: 'string',
role: 'annotation'
}]);
var options = {
annotations: {
alwaysOutside: true
},
title: 'Population of Largest U.S. Cities',
chartArea: {width: '50%'},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;