简体   繁体   中英

Y Axes not displaying properly on Chartjs

I am trying to use ChartJS latest version and I'm getting this problem, it shows four Y Axes, three on the left. Here is my code:

 <html> <body> <canvas id="QGL_Chart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.1.1/dist/chart.min.js" integrity="sha256-lISRn4x2bHaafBiAb0H5C7mqJli7N0SH+vrapxjIz3k=" crossorigin="anonymous"></script> <script> var ctx = document.getElementById("QGL_Chart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { datasets: [{ label: 'Left dataset', yAxisID: 'first-y-axis', data: [1,2,3,4] }, { label: 'right dataset', yAxisID: 'second-y-axis', data: [4,3,2,1] }], labels: [1,2,3,4] }, options: { scales: { 'left-y-axis': { type: 'linear', position: 'left' }, 'right-y-axis': { type: 'linear', position: 'right' } } } }); </script> </body> </html>

If you run the snippet, you see that there are three Y Axes by the left, what might be the problem? Thanks.

This is because the object names of your scales become the ID, and since you try to map your datasets to non existent scale ID's it creates them for you extra. If you make the axisId prop in your dataset the same as you gave the object name it will work as inteded, see snippet:

 <html> <body> <canvas id="QGL_Chart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.1.1/dist/chart.min.js" integrity="sha256-lISRn4x2bHaafBiAb0H5C7mqJli7N0SH+vrapxjIz3k=" crossorigin="anonymous"></script> <script> var ctx = document.getElementById("QGL_Chart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { datasets: [{ label: 'Left dataset', yAxisID: 'left-y-axis', data: [1, 2, 3, 4] }, { label: 'right dataset', yAxisID: 'right-y-axis', data: [4, 3, 2, 1] } ], labels: [1, 2, 3, 4] }, options: { scales: { 'left-y-axis': { type: 'linear', position: 'left' }, 'right-y-axis': { type: 'linear', position: 'right' } } } }); </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM