Reputation: 63729
How can I make programmatic toggling of datasets play together with the one from ChartJS' legend clicking?
Here's a repro of my problem:
I expect the custom logic to play nice with ChartJS' built in feature.
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");
dataset.hidden = !dataset.hidden;
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>
What am I doing wrong?
Upvotes: 1
Views: 223
Reputation: 63729
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:
indexOf
or similarchart.getDatasetMeta(index)
metadata.visible
and pass it to setDatasetVisibility(...)
chart.update()
as per usualconst 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>
Upvotes: 1