Chartsjs多轴,启用/禁用数据集时显示/消失比例 [英] Chartsjs multi-axis, make the scale appear/disappear when the dataset is activated/deactivated

查看:31

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.

解决方案

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>

这篇关于Chartsjs多轴,启用/禁用数据集时显示/消失比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆