Chartjs-Combine Chart.js programmatic and legend based dataset toggling

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:

  1. Get dataset index with indexOf or similar
  2. Get metadata at that index with chart.getDatasetMeta(index)
  3. Use metadata.visible and pass it to setDatasetVisibility(...)
  4. 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>

Leave a comment