主题
多 Y 轴
Chart.js 支持在同一图表中配置多个 Y 轴,方便展示不同量纲或范围的数据。每个数据集可以指定对应的 Y 轴,通过坐标轴的 id
关联。
以下示例展示了两个数据集绑定不同 Y 轴,实现左、右两侧显示不同刻度的效果。
js
(function () {
const ctx = document.getElementById('multiYAxisChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['一月', '二月', '三月', '四月'],
datasets: [
{
label: '销售额 (千元)',
data: [30, 50, 70, 60],
backgroundColor: 'rgba(75, 192, 192, 0.7)',
yAxisID: 'yLeft'
},
{
label: '访问量 (千次)',
data: [200, 300, 250, 400],
backgroundColor: 'rgba(255, 159, 64, 0.7)',
yAxisID: 'yRight'
}
]
},
options: {
responsive: true,
scales: {
yLeft: {
type: 'linear',
position: 'left',
title: {
display: true,
text: '销售额 (千元)'
}
},
yRight: {
type: 'linear',
position: 'right',
title: {
display: true,
text: '访问量 (千次)'
},
grid: {
drawOnChartArea: false
}
}
},
plugins: {
legend: { display: true }
}
}
});
})();
loading