是否可以在Google Visualization Chart API中仅显示百分比?
我在docs
中找不到任何相关信息答案 0 :(得分:1)
您可以提供自己的自定义工具提示
在这里,group
方法用于查找所有行的总数...
var total = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
然后使用数据视图添加工具提示列,该列用于计算百分比...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'tooltip',
calc: function (dt, row) {
var percent = (dt.getValue(row, 1) / total.getValue(0, 1)) * 100;
return '<div class="tooltip">' + dt.getValue(row, 0) + ': <span>' + percent.toFixed(1) + '%</span>';
},
p: {html: true}
}]);
请参阅以下工作片段...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
pieSliceText: 'percentage',
tooltip: {
isHtml: true
}
};
var total = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'tooltip',
calc: function (dt, row) {
var percent = (dt.getValue(row, 1) / total.getValue(0, 1)) * 100;
return '<div class="tooltip">' + dt.getValue(row, 0) + ': <span>' + percent.toFixed(1) + '%</span>';
},
p: {html: true}
}]);
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(view.toDataTable(), options);
}
.tooltip {
font-size: 12pt;
padding: 6px;
}
.tooltip span {
font-weight: bold;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>