Hello again, im drawing a pie chart,, and i want to show in the tooltip not the amount or the value but the percent of the pie.. i know that , theres a value called "total" but how can i show it in the tooltip tooltipTemplate, i can do the math like this #### * 100 / "total" and it should work but i dont know how to make the tooltip take it
Thanks.
Ditto. Would love to be able to know how to display % rather than the unit value in a pie/doughnut chart.
Gotta be a simple way, yeah? :-) Hmm.....
I was doing research on how to accomplish the same thing and came across this issue. I ended up looking through the source and finding that the "circumference" property is available to use within the tooltip template. The "circumference" property appears to be the number of radians for the data element. That means it can be divided by 2*pi (~6.283) to get the percentage of the pie chart that the data value represents. As an example, I'm using the following format string along with numeral.js for chart tooltips that include both the data value and the percentage of the pie chart that it represents:
<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= numeral(value).format('($0,0[.]00)') %> - <%= numeral(circumference / 6.283).format('(0[.][00]%)') %>
Hopefully that makes sense. Let me know if it doesn't work for you.
Bhasden, thanks i will try it look like a solution, but if you can acces to the circunference property, may be you can access the "total" property of the chart, how ever il try it right now and let you know, thanks again for taking your time. sorry my english! im from Argentina jaja...
one last condideration have you have try to load a chart twice in the seame canvas and when you are mouse over, it show the previos and the actual chart, i want to erase previous and i just cant!!
thanks anyway
Dear Bhasden, it works! but first i had to add the Numeral.js library here its the dsn if someone else is in need.
src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"
Sentence
tooltipTemplate: " <%=label%>: <%= numeral(value).format('($00[.]00)') %> - <%= numeral(circumference / 6.283).format('(0[.][00]%)') %>"
In Pie Chart there isnt, dataSet , instead use segment
The proposed solution poses a remaining challenge when passed in as a parameter through Angular Charts. For example:
<canvas
id="pie"
class="chart chart-pie"
chart-data="chart.data"
chart-labels="chart.labels"
chart-colours="chart.colours"
chart-legend="true"
chart-options="{tooltipTemplate: '<%=label%>: <%= numeral(value).format('($00[.]00)') %> - <%= numeral(circumference / 6.283).format('(0[.][00]%)') %>'">
</canvas>
The HTML attribute chart-options
must have its value enclosed in quotes. This HTML attribute takes a JavaScript object with multiple variables, including tooltipTemplate
. The value for tooltipTemplate
must also be enclosed in quotes, but different quotes than the HTML attribute.
When the parameter for format
is passed in, it also requires quotes. At this point, no matter what type of quote is used for its argument (single/double), it'll prematurely terminate either the HTML or JavaScript, causing the expression to break the parser/lexer. Escaping the format
parameter has also proved futile.
Any other thoughts on passing along the total so that the expression can be (value / total)
?
For Ionic, the tooltipTemplate can be modified in JavaScript as follows:
.run( function( $ionicPlatform ) {
$ionicPlatform.ready( function() {
// ... set up code ...
// Show percentages.
Chart.defaults.global.tooltipTemplate =
"<%=label%>: <%= Math.round(circumference / 6.283 * 100) %>%"
;
});
})
This will avoid the issue of nesting double and single quotes.
licPflores: I can't get this to work. Do you happen to have a working example?
I need help figuring this out as well. It is obvious we need each circumference variable (divided by 2pi to get the % ratio in total.) In the legendTemplate for a doughnut chart, I console.log(segments[i]) . This is the output. I need access to circumference right?
The problem is when I try to access "segments[i].circumference" the returned value is not "0.62831...." (which would be 10% as I expect) but "0" . I suspect it is returned from the "_saved" object. So in a way
"segments[i].circumference" returns "segments[i]._saved.circumference".
1- What is "_saved" exactly?
2- Why is it returned by default?
3- How can I return the 0.62831 value?
This solution should be added in the documentation
FYI: circumference
is only available in tooltipTemplate
not in multiTooltipTemplate
Having the same problem as @ardav. The value is zero.
I found this in the source code of chart.js:
circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
Which means that if I set animateRotate to false in the options, circumference isn't 0. I'd say this is a bug.
The solution to this has changed as the tooltip templates (tooltipTemplate, multiTooltipTemplate) have been removed. Percentages can be implemented using something like this: http://blog.cryst.co.uk/2016/06/03/adding-percentages-chart-js-pie-chart-tooltips/
Thank you @deframe !
@deframe : Bitcoin miner detected on the website
@yusren Damnit, thanks for the heads up. Site disabled until I can clean it up.
From @deframe's site (via archive.org):
Everyone loves Chart.js, but as with any library it’s interface is always subject to change.
One such change is in the handling of the tooltips that appear when you mouse over a datapoint in your chart. By default these tooltips display the data label, e.g. “Blue: ” followed by the data value, e.g. “50“. Simple stuff, and fortunately Chart.js provides a way of customizing these tooltips should you ever need something a little different. A quick Google search will produce plenty of guides on how to do so but many of them are outdated, using older template-based methods that no longer work in more recent versions of the library.
To that end I’d like to present a simple example of how to customize the tooltips of a pie chart by having them display the percentage of each data point as well as its value. To keep things familiar I’ll base this around the example pie chart usage/data configuration provided in the Chart.js documentation.
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [
{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}
]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
var total = 0;
for (var i in allData) {
total += allData[i];
}
var tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
}
}
}
}
});
The main thing to note here is the chart.options.tooltips.callbacks.label callback function. This is what ultimately determines the content of each tooltip via the return value.
The first parameter of the callback – tooltipItem – is a structure representing the tooltip we are operating on, and we make use of two of its properties: datasetIndex and index. You might have noticed in the example that chart.data.datasets is an array, therefore datasetIndex represents the index of the dataset associated with the tooltip (in this case 0, since we only have one!). Subsequently the index property is simply the index of the associated data item within that dataset.
The second callback parameter – data – contains nothing more that our chart.data configuration, i.e. the labels and datasets themselves.
By making use of these two parameters we total up all of the chart data and use this total to calculate the percentage of each data point. This percentage is then used to form the tooltip content along with the label and original data. Job done!
How can I show all the Pie chart Slices data in the single Tooltip?
@DaveJarvis your solution work's fine for me, but I have to do a parseFloat() in the add of total, because it take the item like a string. I leave the code below:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
var total = 0;
for (var i in allData) {
total += parseFloat(allData[i]);
}
var tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
}
}
}
}
Grettings.
@jdeveloper10, to be clear, the code was originally written by @deframe. I merely posted it here for convenience.
@DaveJarvis you're right, but anyway thanks and also thanks to @deframe.
With regard to displaying percent, it's worth noting that Intl.NumberFormat
is a pretty strong option nowadays and takes locale into account.
Use system locale:
const percentFormatter = n =>
Intl.NumberFormat(undefined, {
style: 'percent',
maximumFractionDigits: 2
}).format(n)
percentFormatter(0.76534) // "76.53%"
Use specific locale:
const percentFormatter = n =>
Intl.NumberFormat('fr-FR', {
style: 'percent',
maximumFractionDigits: 2
}).format(n)
percentFormatter(0.76534) // "76,53 %"
Is there a way to do this for bar charts, where the label shows the percentage of the x and y values (e.g., 16x is 94% of 17y)?
I've tried using the labels plugin, but all the percentages are 100%: https://jsbin.com/dawenetuya/edit?html,js,output
Most helpful comment
The solution to this has changed as the tooltip templates (tooltipTemplate, multiTooltipTemplate) have been removed. Percentages can be implemented using something like this: http://blog.cryst.co.uk/2016/06/03/adding-percentages-chart-js-pie-chart-tooltips/