Javascript 如何在 Chart.js v2 中使用两个 Y 轴?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38085352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use two Y axes in Chart.js v2?
提问by just.me
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.
我正在尝试使用 Chart.js 创建一个包含两个数据集的折线图,每个数据集都有自己的 Y 比例尺/轴(一个在图表的左侧,一个在图表的右侧)。
This is my code (jsfiddle):
这是我的代码(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
}
]
}
});
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?
但是,第二个轴不可见,第二个数据集仍与第一个数据集完全相同(0 到 100,而不是 0 到 1)。我需要改变什么?
回答by Quince
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?),
对于 ChartJs 2.x,只需要进行一些更改(看起来您已经尝试将 2.x 选项与我的 fork 中的多轴选项结合起来?),
- The
yAxes
field needs to be in ascales
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 for
scalePositionLeft
this is covered byposition
- 该
yAxes
字段需要在一个scales
对象中 - yAxis 由 id 而不是名称引用。
- 对于缩放步长/大小,您只需要将这些选项包装在一个
ticks
对象中。 - 不需要
scalePositionLeft
这被涵盖position
Example:
例子:
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
}
}]
}
}
});