Skip to content

Commit eda1f71

Browse files
authored
feat: improve y-axis tick formatting (#51)
1 parent 4422081 commit eda1f71

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

src/components/ChartContainer.jsx

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -414,13 +414,20 @@ export default function ChartContainer({
414414
});
415415
});
416416
if (min === Infinity || max === -Infinity) {
417-
return { min: 0, max: 1 };
417+
return { min: 0, max: 1, step: 1 };
418418
}
419419
if (min === max) {
420-
return { min: min - 1, max: max + 1 };
420+
return { min: min - 1, max: max + 1, step: 1 };
421421
}
422422
const pad = (max - min) * 0.05;
423-
return { min: min - pad, max: max + pad };
423+
const paddedMin = min - pad;
424+
const paddedMax = max + pad;
425+
const range = paddedMax - paddedMin;
426+
let step = Math.pow(10, Math.floor(Math.log10(range)));
427+
if (range / step < 3) {
428+
step /= 10;
429+
}
430+
return { min: paddedMin, max: paddedMax, step };
424431
}, [xRange]);
425432

426433
const chartOptions = useMemo(() => ({
@@ -680,11 +687,20 @@ export default function ChartContainer({
680687
const showComparison = dataArray.length >= 2;
681688

682689
const yRange = calculateYRange(dataArray);
690+
const yDecimals = Math.max(0, -Math.floor(Math.log10(yRange.step)));
683691
const options = {
684692
...chartOptions,
685693
scales: {
686694
...chartOptions.scales,
687-
y: { ...chartOptions.scales.y, min: yRange.min, max: yRange.max }
695+
y: {
696+
...chartOptions.scales.y,
697+
min: yRange.min,
698+
max: yRange.max,
699+
ticks: {
700+
stepSize: yRange.step,
701+
callback: (value) => Number(value.toFixed(yDecimals))
702+
}
703+
}
688704
}
689705
};
690706

@@ -694,11 +710,20 @@ export default function ChartContainer({
694710
const compResult = buildComparisonChartData(dataArray);
695711
stats = compResult.stats.length > 0 ? compResult.stats : null;
696712
const compRange = calculateYRange(compResult.datasets);
713+
const compDecimals = Math.max(0, -Math.floor(Math.log10(compRange.step)));
697714
const compOptions = {
698715
...chartOptions,
699716
scales: {
700717
...chartOptions.scales,
701-
y: { ...chartOptions.scales.y, min: compRange.min, max: compRange.max }
718+
y: {
719+
...chartOptions.scales.y,
720+
min: compRange.min,
721+
max: compRange.max,
722+
ticks: {
723+
stepSize: compRange.step,
724+
callback: (value) => Number(value.toFixed(compDecimals))
725+
}
726+
}
702727
}
703728
};
704729
const compActions = (

0 commit comments

Comments
 (0)