0👍
✅
Unlike with line charts the doughnut chart is not hiding datasets when you click on the legend so you can’t use the helper method chart.isDatasetVisible
but you can access the meta data chartjs uses internally about the data points to find out if it is hidden
data.datasets[DATASET_INDEX]._meta[0].data[DATA_ITEM_INDEX].hidden
using this in the loop which creates the total you can exclude any data items that are hidden
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [
"Marche",
"Course",
"Natation",
"Vélo"
],
datasets: [{
data: [65.45, 10, 10, 14.55],
backgroundColor: [
"#00ff00",
"#008fb3",
"#ff0000",
"#ffff00",
],
borderWidth: 1
}]
},
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) {
if (!data.datasets[tooltipItem.datasetIndex]._meta[0].data[i].hidden) {
total += allData[i];
}
}
var tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipPercentage + ' %';
}
}
},
title: {
display: true,
text: 'Récapitulatif des séances de sport',
fontColor: "#000"
},
legend: {
display: true,
labels: {
fontColor: '#000',
}
}
}
});
.graphsize {
width: 500px;
height: 500px;
border: solid black 5px;
border-radius: 15px;
}
body {
margin-left: 27%;
margin-right: 25%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.js"></script>
<div class="graphsize">
<canvas id="myChart"></canvas>
</div>
Source:stackexchange.com