[Chartjs]-Chartsjs multi-axis, make the scale appear/disappear when the dataset is activated/deactivated

0👍

This can be done using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.

You could use the beforeLayout hook as shown below. The function iterates over the datasets and sets the yAxes.display option depending whether the corresponding dataset is hidden or not.

plugins: [{
  beforeLayout: chart => chart.data.datasets.forEach((ds, i) => chart.config.options.scales.yAxes[i].display = !ds._meta[0].hidden)
}],

Please have a look at the following runnable code snippet to see how it works.

new Chart('chart', {
  type: 'line',
  plugins: [{
    beforeLayout: chart => chart.data.datasets.forEach((ds, i) => chart.config.options.scales.yAxes[i].display = !ds._meta[0].hidden)
  }],
  data: {
    labels: ['A', 'B', 'C', 'D', 'E'],
    datasets: [{
        label: 'Dataset 1',
        yAxisID: 'yAxis-1',
        data: [100, 96, 84, 76, 69],
        borderColor: 'red',
        fill: false
      },
      {
        label: 'Dataset 2',
        yAxisID: 'yAxis-2',
        data: [9, 6, 8, 7, 6],
        borderColor: 'blue',
        fill: false
      },
      {
        label: 'Dataset 3',
        yAxisID: 'yAxis-3',
        data: [0.3, 0.5, 0.8, 0.4, 0.5],
        borderColor: 'green',
        fill: false
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
          id: 'yAxis-1',
          type: 'linear',
          position: 'left',
        },
        {
          id: 'yAxis-2',
          type: 'linear',
          position: 'left'
        },
        {
          id: 'yAxis-3',
          type: 'linear',
          position: 'left'
        }
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="90"></canvas>

Leave a comment