Chartjs-Chart.js hidden property

0👍

You can use the isDatasetVisible method on the chart object with the current dataset index to check if it is hidden. This returns a boolean so you can put it in there right away after inversing it.

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      labels: {
        generateLabels: (chart) =>
          chart.data.datasets.map((dataset, i) => ({
            datasetIndex: i,
            text: dataset.label,
            fillStyle: dataset.backgroundColor,
            strokeStyle: dataset.borderColor,
            hidden: !chart.isDatasetVisible(i),
          })),
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Leave a comment