Skip to content

Commit d9f28a3

Browse files
authored
auto-round based on wasted space (#558)
* auto-round based on wasted error * don’t round ordinal scales
1 parent 4f73ee5 commit d9f28a3

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

src/scales.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,25 @@ function autoScaleRangeY(scale, dimensions) {
6868
}
6969

7070
function autoScaleRound(scale) {
71-
if (scale.round === undefined && isOrdinalScale(scale) && scale.scale.step() >= 5) {
71+
if (scale.round === undefined && isBandScale(scale) && roundError(scale) <= 30) {
7272
scale.scale.round(true);
7373
}
7474
}
7575

76+
// If we were to turn on rounding for this band or point scale, how much wasted
77+
// space would it introduce (on both ends of the range)? This must match
78+
// d3.scaleBand’s rounding behavior:
79+
// https://github.com/d3/d3-scale/blob/83555bd759c7314420bd4240642beda5e258db9e/src/band.js#L20-L32
80+
function roundError({scale}) {
81+
const n = scale.domain().length;
82+
const [start, stop] = scale.range();
83+
const paddingInner = scale.paddingInner ? scale.paddingInner() : 1;
84+
const paddingOuter = scale.paddingOuter ? scale.paddingOuter() : scale.padding();
85+
const m = n - paddingInner;
86+
const step = Math.abs(stop - start) / Math.max(1, m + paddingOuter * 2);
87+
return (step - Math.floor(step)) * m;
88+
}
89+
7690
function piecewiseRange({scale, range}) {
7791
const length = scale.domain().length;
7892
if (!(length > 2)) return range;
@@ -179,6 +193,10 @@ export function isOrdinalScale({type}) {
179193
return type === "ordinal" || type === "point" || type === "band";
180194
}
181195

196+
function isBandScale({type}) {
197+
return type === "point" || type === "band";
198+
}
199+
182200
export function isDivergingScale({type}) {
183201
return /^diverging($|-)/.test(type);
184202
}

test/plots/google-trends-ridgeline.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export default async function() {
1414
axis: null
1515
},
1616
fy: {
17+
round: true,
1718
label: null
1819
},
1920
facet: {

test/plots/metro-unemployment-ridgeline.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export default async function() {
1111
axis: null
1212
},
1313
fy: {
14+
round: true,
1415
label: null
1516
},
1617
facet: {

0 commit comments

Comments
 (0)