[Chartjs]-Chart.js toggleDatasetVisibility and getDatasetVisibility doesn't work

1👍

This is because toggleDatasetVisibility is not a function, as you show in your code you are using toggleDataVisibility and this is according to the docs only valid for chart types which support hiding single elements.

The line chart does not support to hide a single dot from a line so you can’t use the toggleDataVisibility for your use case.

You can use getDatasetMeta(datasetIndex).hidden to check if the dataset is hidden (note this prop only gets set after it gets updated once)

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

<canvas id="line-chart"></canvas>
<div>
  <input type="button" value="Show Set 2" onclick="restoreLayer2()">
  <input type="button" value="Hide Set 2" onclick="removeLayer2()">
</div>
<script>
  lineChart = new Chart(document.getElementById("line-chart"), {
    type: 'line',
    data: {
      labels: [
        '10:00 AM',
        '11:00 AM',
        '12:00 PM',
        '1:00 PM',
        '2:00 PM',
        '3:00 PM',

        '4:00 PM',
        '5:00 PM',
        '6:00 PM',
        '7:00 PM',
        '8:00 PM',
        '9:00 PM'
      ],
      datasets: [{
        label: 'Temperature',
        data: [
          74,
          77,
          80,
          82,
          86,
          85,

          83,
          79,
          72,
          68,
          66,
          66
        ],
      }, {
        label: 'Humidity',
        data: [
          44,
          44,
          45,
          45,
          45,
          46,

          46,
          46,
          45,
          44,
          44,
          44
        ],
      }],
    },
    options: {
      plugins: {
        legend: {
          display: false
        }
      }
    }
  });

  function restoreLayer2() {
    console.log(lineChart.getDatasetMeta(1).hidden);

    lineChart.setDatasetVisibility(1, true);
    lineChart.update();
  }

  function removeLayer2() {
    console.log(lineChart.getDatasetMeta(1).hidden);

    lineChart.setDatasetVisibility(1, lineChart.getDatasetMeta(1).hidden);

    lineChart.update();
  }
</script>

Leave a comment