Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hide all series form a pie chart from chartjs
<!DOCTYPE html>
<html lang="en">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="toggle">show/hide all</button>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
const data = {
datasets: [{
data: [
10,
5,
30,
2,
1,
],
backgroundColor: [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
]
}],
labels: [
"one",
"two",
"three",
"four",
"five"
]
};
const options = {
responsive: true,
legend: {
position: 'top',
}
};
const config = {
type: 'pie',
data: data,
options: options
};
const ctx = document.getElementById("myChart")
.getContext("2d");
const chartInstance = new Chart(ctx, config);
$("#toggle").click(function() {
var meta = chartInstance.getDatasetMeta(0);
meta.data.forEach(function(ds) {
ds.hidden = true;
});
chartInstance.update();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment