使用Chart.js双Y轴单图表绘制双数据集:横轴标签控制方案
问题
使用Chart.js库编写了如下代码,尝试在单个图表中以双Y轴绘制两个数据集,期望清晰展示两组数据,但需要指导如何有效控制横轴标签。
原代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <canvas id="chart" width="1920" height="1080"></canvas> <script> const ctx = document.getElementById('chart').getContext('2d'); const chart = new Chart(ctx, { type: 'line', data: { datasets: [ { yAxisID: 'yA', label: 'Data1', data: [ { x: 0.05, y: 12 }, { x: 0.15, y: 19 }, { x: 0.25, y: 3 }, { x: 0.35, y: 5 }, { x: 0.45, y: 2 }, { x: 0.55, y: 3 }, ], }, { yAxisID: 'yB', label: 'Data2', data: [ { x: 0.0, y: 20 }, { x: 0.2, y: 1 }, { x: 0.3, y: 15 }, { x: 0.4, y: 2 }, { x: 0.5, y: 31 }, { x: 0.6, y: 11 }, ], } ] }, options: { responsive: true, scales: { yA: { type: 'linear', position: 'left', ticks: { beginAtZero: true, color: 'blue' }, grid: { display: false } }, yB: { type: 'linear', position: 'left', ticks: { beginAtZero: true, color: 'green' }, grid: { display: false } }, x: { ticks: { beginAtZero: true }, } } } }); </script> </body> </html>
解决方案
在x轴的scales配置中添加type: 'linear',Chart.js会将横轴识别为线性轴,从而根据数据中的数值型x值正确生成、控制横轴标签。
修改后的代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <canvas id="chart" width="1920" height="1080"></canvas> <script> const ctx = document.getElementById('chart').getContext('2d'); const chart = new Chart(ctx, { type: 'line', data: { datasets: [ { yAxisID: 'yA', label: 'Data1', data: [ { x: 0.05, y: 12 }, { x: 0.15, y: 19 }, { x: 0.25, y: 3 }, { x: 0.35, y: 5 }, { x: 0.45, y: 2 }, { x: 0.55, y: 3 }, ], }, { yAxisID: 'yB', label: 'Data2', data: [ { x: 0.0, y: 20 }, { x: 0.2, y: 1 }, { x: 0.3, y: 15 }, { x: 0.4, y: 2 }, { x: 0.5, y: 31 }, { x: 0.6, y: 11 }, ], } ] }, options: { responsive: true, scales: { yA: { type: 'linear', position: 'left', ticks: { beginAtZero: true, color: 'blue' }, grid: { display: false } }, yB: { type: 'linear', position: 'left', ticks: { beginAtZero: true, color: 'green' }, grid: { display: false } }, x: { ticks: { beginAtZero: true }, type: 'linear',} } } }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Marco Moldenhauer
相关产品推荐
相关产品推荐

