如何在Chart.js v2中使用两个Y轴? [英] How to use two Y axes in Chart.js v2?
问题描述
我试图用两个数据集创建一个折线图,每个数据集都使用Chart.js,每个数据集都有自己的Y比例/轴(图的左边一个,图的右边一个)。
这是我的代码( jsfiddle ):
var canvas = document.getElementById('chart');
新图表(canvas,{
type:'line',
data:{
labels:['1','2','3','4', '5'],
数据集:[
{
label:'A',
yAxesGroup:'A',
data:[100,96,84, 76,69]
},
{
label:'B',
yAxesGroup:'B',
data:[1,1,1,1, 0
$ b类型:'linear',
位置:'left',
scalePositionLeft:true
},
{
名称:'B',
类型:'linear',
position:'right',
scalePositionLeft:false,
min:0,
max:1
}
]
}
});
然而,第二个轴是不可见的,第二个数据集仍然按照第一个(0到100而不是0到1)。我需要改变什么?
对于ChartJs 2.x,只需要进行一些更改(看起来像您试图将2.x选项与我的fork中的多轴选项结合起来?),
-
yAxes
字段需要位于scale
对象中 - yAxis由id not name引用。
- 对于缩放步骤/大小,您只需将这些选项包装在
滴答
对象中。 - 不需要
scalePositionLeft
这包含于位置
示例:
var canvas = document。的getElementById( '图表');
新图表(canvas,{
type:'line',
data:{
labels:['1','2','3','4', '5'],
数据集:[{
标签:'A',
yAxisID:'A',
数据:[100,96,84,76,69]
},{
label:'B',
yAxisID:'B',
data:[1,1,1,1,0]
}]
},
选项:{
比例:{
yAxes:[{
id:'A',
type:'linear',
位置:'left',
},{
id:'B',
类型:'linear',
位置:'right',
ticks :{
max:1,
min:0
}
}]
}
}
});
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.
This is my code (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?
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?),
- 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
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
}
}]
}
}
});
这篇关于如何在Chart.js v2中使用两个Y轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!