chart.js toggleDatasetVisibility and getDatasetVisibility doesn't work

Viewed 19

I am trying to toggle data set visibility from outside of my chart. Using setDatasetVisibility to explicitly set viability works fine with two buttons, one to set it to true and the other to false.

While setDatasetVisibility will indeed hide and show the data set, getDatasetVisibility continues to return true regardless of the current visibility.

The toggleDatasetVisibility method doesn't hide anything, but it does change the state of getDatasetVisibility which now returns the correct value.

Why is it that in order to make this work I need to do something like this? I would expect toggleDataVisibility to be sufficient.

lineChart.toggleDataVisibility(1);
lineChart.setDatasetVisibility(1, lineChart.getDataVisibility(1));
lineChart.update();

https://jsfiddle.net/oxywhtdv/

1 Answers

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>

Related