2👍
✅
I couldn’t find a direct API. But one way you could do it is to reset the hidden
property on the metadata.
function resetLegends() {
myChart.getDatasetMeta(0).data.forEach(item => item.hidden = false);
}
var chartCanvas = document.getElementById("pie-chart");
var data1 = [12, 19, 3, 5, 2, 3];
var data2 = [45, 8, 3, 1, 13, 53];
var labels1 = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];
var labels2 = ['Apple', 'Berry', 'Banana', 'Mango', 'Grapes', 'Orange'];
// chart.js initialize:
var ctx = chartCanvas.getContext("2d");
var myChart = new Chart(ctx, {
type: "pie",
data: {
labels: labels1,
datasets: [{
label: "Data 1",
data: data1,
labels: labels1,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
}],
},
options: {
legend: {
display: true,
position: "bottom"
},
title: {
display: true,
text: "Data 1"
}
}
});
// pie chart buttons:
var btn1 = document.getElementById("button1");
var btn2 = document.getElementById("button2");
btn1.addEventListener("click", function() {
myChart.data.datasets[0].label = "Data 1";
myChart.data.datasets[0].data = data1;
myChart.data.labels = labels1;
myChart.options.title.text = "Data 1";
resetLegends();
myChart.update();
});
btn2.addEventListener("click", function() {
myChart.data.datasets[0].label = "Data 2";
myChart.data.datasets[0].data = data2;
myChart.data.labels = labels2;
myChart.options.title.text = "Data 2";
resetLegends();
myChart.update();
});
function resetLegends() {
myChart.getDatasetMeta(0).data.forEach(item => item.hidden = false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<canvas id="pie-chart"></canvas>
<button id="button1">Data 1</button>
<button id="button2">Data 2</button>
Got some inspiration from the docs and the source code of the default onClick legend option.
Source:stackexchange.com