Reputation: 1616
Is it possible to show only percentage in Google Visualization Chart API?
I can't find anything about that in docs
I have pieSliceText: 'percentage'
, but I also want to show only % when I hover over.
Upvotes: 3
Views: 1032
Reputation: 61275
you can provide your own custom tooltip
here, the group
method is used to find the total of all the rows...
var total = google.visualization.data.group(
data,
[{column: 0, modifier: function () {return 'total'}, type:'string'}],
[{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
);
then a data view is used to add the tooltip column, where the percent is calculated...
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}
}]);
see following working snippet...
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>
Upvotes: 1