Reputation: 393
Fiddle :https://jsfiddle.net/jfft219g/
You can see here I have 3 datasets
i.e Hospital, Referral, Total. I am displaying the the dataindexes
on top of each bar.
But now when I disable one dataset
the dataIndexes
are still there for the disabled dataset
. How to manage this. Please check the fiddle for the running codes.
Any help will be appreciated.
<div id="patientsBarGraphDiv" style="border: 1px solid black">
<canvas id="patientsBarGraph"></canvas>
</div>
var paitentData = {
labels: ["Today", "Week", "Month", "Year"],
datasets: [{
label: "Hospital Patients",
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data:[ 24, 20, 30, 40] // adding data for the hospital section
}, {
label: "Referral Patients",
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data:[ 14, 24, 34, 44] // adding data for referral section
},
{
label: "Total Patients",
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data:[ 22, 32, 43, 52] // adding data for Total section
} ]
};
var opt = {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Patients Graph'
},
hover: {
animationDuration: 1
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
}
};
var ctx = document.getElementById("patientsBarGraph").getContext("2d");// getting the id of canvas
var MyNewChart = new Chart(ctx,{
type: 'bar',
data: paitentData,
options:opt
});
Upvotes: 0
Views: 650
Reputation: 32889
Add the following lines of code inside your forEach
loop, that will take care of the dataIndex
updating issue :
var isDatasetVisible = chartInstance.controller.isDatasetVisible(i);
if (!isDatasetVisible) return;
Here is the working example on JSFiddle
Upvotes: 1