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

余生长醉 提交于 2021-01-27 06:35:46

问题


I'm using charts.js.

This is my chart:

I have 3 or more datasets in the same chart, each with a different scale, let's image that all the scales are on the left.

As default when deactivating a dataset (for example in this case clicking on "Sold Products") the scale is rescaled between [-1, +1] as here on multi-axis demo code too.

Is there a way in which I can make disappear the dataset's scale when that dataset is deactivated? For example in this case if I deactivate "Sold Products", I would like to make the scale in the middle to disappear. When I reactivate the "Sold Product" then I would like the scale to reappear.


回答1:


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>


来源:https://stackoverflow.com/questions/54308996/chartsjs-multi-axis-make-the-scale-appear-disappear-when-the-dataset-is-activat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!