Chart.js散点图X轴含小数时显示异常问题求助
Solution for Chart.js Scatter Plot Decimal X-Axis Display Issue
The core problem in your code is out-of-bounds array access when calculating suggestedMax for both axes. Arrays are zero-indexed, so using xPoints[xLength] (where xLength is the array's length) returns undefined—adding 10 to that results in NaN, which corrupts the scale's rendering logic. This explains why integer values might appear to work (the default scale falls back to auto-calculating bounds) but decimal values break the chart.
Fixed Code
Here's the corrected version with key fixes highlighted:
var ctx = document.getElementById("myChart").getContext("2d"); var myChart = new Chart(ctx, { type: 'scatter', data: { datasets: [{ label: 'Points', borderColor: window.chartColors.purple, borderWidth: 2, fill: false, data: storage, backgroundColor: window.chartColors.purple, }] }, title: { display: false, text: 'Despressuration Chart', fontSize: 18 }, events: ['click'], tooltips: { mode: 'index', intersect: true }, hover: { mode: 'index', intersect: true }, elements: { line: { tension: 0 // disables bezier curves } }, scales: { yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Flow (Ft3/Min)' }, ticks: { suggestedMin: 0, // Fixed: access last valid element in yPoints array suggestedMax: yPoints[length - 1] + 80, beginAtZero: true } }], xAxes: [{ display: true, // Explicitly set linear scale (redundant for scatter, but avoids edge cases) type: 'linear', scaleLabel: { display: true, labelString: 'Induced Pressure (Pa)' }, ticks: { suggestedMin: 0, // Fixed: access last valid element in xPoints array suggestedMax: xPoints[xLength - 1] + 10, beginAtZero: true, // Optional: adjust decimal precision for ticks precision: 1 } }] } });
Key Fixes:
- Corrected array indexing: Changed
xPoints[xLength]toxPoints[xLength - 1]andyPoints[length]toyPoints[length - 1]to target the last valid data point in each array. - Explicit linear scale: Added
type: 'linear'to the X axis to ensure Chart.js uses the correct scale type for scatter plot data. - Optional tick precision: Included
precision:1to control how many decimal places are shown on X-axis ticks (adjust the number to match your data's precision needs).
Once these fixes are applied, your scatter plot will render correctly with decimal X-axis values without modifying the original storage data.
内容的提问来源于stack exchange,提问作者danielooo
相关产品推荐
相关产品推荐

