1👍
Turns out hidden
works, but there’s also a property visible
which then needs to be programmatically used with setDatasetVisibility(datasetIndex, visibility)
.
So, one method would be:
- Get dataset index with
indexOf
or similar - Get metadata at that index with
chart.getDatasetMeta(index)
- Use
metadata.visible
and pass it tosetDatasetVisibility(...)
chart.update()
as per usual
const chart = new Chart(document.getElementById("chart").getContext("2d"), {
type: "bar",
data: {
labels: ["label1", "label2", "label3"],
datasets: [
{ label: "Fruit", backgroundColor: "IndianRed", data: [1,2,3] },
{ label: "Veggies", backgroundColor: "LightGreen", data: [2,5,3] },
]
}
});
function togglestuff() {
const dataset = chart.data.datasets.find(ds => ds.label === "Fruit");
const index = chart.data.datasets.indexOf(dataset);
const metadata = chart.getDatasetMeta(index);
chart.setDatasetVisibility(
index,
!metadata.visible,
);
chart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
<div><canvas id="chart" height="75px"></canvas></div>
<button id="hide" onclick="togglestuff()">
Toggle fruit programmatically
</button>
Source:stackexchange.com