gpt4 book ai didi

javascript - 如何在 Chart.js v2 中使用两个 Y 轴?

转载 作者:IT王子 更新时间:2023-10-29 03:05:49 26 4
gpt4 key购买 nike

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

这是我的代码(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)。我需要更改什么?

最佳答案

对于 ChartJs 2.x,只需要进行一些更改(看起来您已尝试将 2.x 选项与我的 fork 中的多轴选项结合使用?),

  • yAxes 字段需要在 scales 对象中
  • yAxis 由 id 而不是 name 引用。
  • 对于比例步长/大小,您只需将这些选项包装在 ticks 对象中。
  • 不需要scalePositionLeft 这被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
}
}]
}
}
});

fiddle example

关于javascript - 如何在 Chart.js v2 中使用两个 Y 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com