1👍
✅
You can use the toggleDataVisibility
for pie and doughnut charts and setDatasetVisibility
for all the other chart types
live example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("myBtn").addEventListener("click", () => {
const {
type
} = chart.config;
if (type === 'pie' || type === 'doughnut') {
// Pie and doughnut charts only have a single dataset and visibility is per item
chart.toggleDataVisibility(0);
} else {
chart.setDatasetVisibility(0, !chart.isDatasetVisible(0));
}
chart.update();
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<button id="myBtn">
Hide dataset
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>
Source:stackexchange.com