如何在 Chart.js v2 中使用两个 Y 轴? [英] How to use two Y axes in Chart.js v2?

查看:35
本文介绍了如何在 Chart.js v2 中使用两个 Y 轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Chart.js 创建一个包含两个数据集的折线图,每个数据集都有自己的 Y 比例尺/轴(一个在图表的左侧,一个在图表的右侧).

I am trying to create a line chart with two datasets, each with its own Y scale / axis (one to the left, one to the right of the graph) using Chart.js.

这是我的代码(jsfiddle):

var canvas = document.getElementById('chart');
new Chart(canvas, {
  type: 'line',
  data: {
    labels: [ '1', '2', '3', '4', '5' ],
    datasets: [
      {
        label: 'A',
        yAxesGroup: 'A',
        data: [ 100, 96, 84, 76, 69 ]
      },
      {
        label: 'B',
        yAxesGroup: 'B',
        data: [ 1, 1, 1, 1, 0 ]
      }
    ]
  },
  options: {
    yAxes: [
      {
        name: 'A',
        type: 'linear',
        position: 'left',
        scalePositionLeft: true
      },
      {
        name: 'B',
        type: 'linear',
        position: 'right',
        scalePositionLeft: false,
        min: 0,
        max: 1
      }
    ]
  }
});

但是,第二个轴不可见,第二个数据集的缩放比例仍与第一个完全相同(0 到 100,而不是 0 到 1).我需要改变什么?

However, the second axis is not visible and the second dataset is still scaled exactly as the first (0 to 100 instead of 0 to 1). What do I need to change?

推荐答案

对于 ChartJs 2.x 只需要进行一些更改(看起来您已经尝试将 2.x 选项与来自我的叉子?),

For ChartJs 2.x only a couple changes need to be made (it looks like you have tried to combine 2.x options with the multi-axes options from my fork?),

  • yAxes 字段需要在 scales 对象中
  • yAxis 是由 id 而不是名称引用的.
  • 对于缩放步长/大小,您只需要将这些选项包装在 ticks 对象中.
  • 不需要scalePositionLeft这被position
  • 覆盖
  • The yAxes field needs to be in a scales object
  • the yAxis is referenced by id not name.
  • For the scale steps/size you just need to wrap these options in a ticks object.
  • No need forscalePositionLeft this is covered by position

示例:

var canvas = document.getElementById('chart');
new Chart(canvas, {
  type: 'line',
  data: {
    labels: ['1', '2', '3', '4', '5'],
    datasets: [{
      label: 'A',
      yAxisID: 'A',
      data: [100, 96, 84, 76, 69]
    }, {
      label: 'B',
      yAxisID: 'B',
      data: [1, 1, 1, 1, 0]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        id: 'A',
        type: 'linear',
        position: 'left',
      }, {
        id: 'B',
        type: 'linear',
        position: 'right',
        ticks: {
          max: 1,
          min: 0
        }
      }]
    }
  }
});

小提琴示例

这篇关于如何在 Chart.js v2 中使用两个 Y 轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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