Skip to content

Commit

Permalink
🚧 remember nice ticks
Browse files Browse the repository at this point in the history
  • Loading branch information
sophiamersmann committed Jan 10, 2025
1 parent c54ba8c commit bbb2397
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions packages/@ourworldindata/grapher/src/axis/Axis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,8 @@ abstract class AbstractAxis {
})
}

private static makeScaleNice(
private niceTicks?: number[]
private makeScaleNice(
scale: ScaleLinear<number, number>,
totalTicksTarget: number
): ScaleLinear<number, number> {
Expand All @@ -223,14 +224,18 @@ abstract class AbstractAxis {
const firstTick = ticks[0]
const lastTick = last(ticks)!

this.niceTicks = ticks

// if the the max or min value exceeds the last grid line by more than 10%,
// expand the domain to include an additional grid line
const [minValue, maxValue] = scale.domain()
if (maxValue > lastTick + 0.1 * tickStep) {
scale.domain([scale.domain()[0], lastTick + tickStep])
this.niceTicks = [...this.niceTicks, lastTick + tickStep]
}
if (minValue < firstTick - 0.1 * tickStep) {
scale.domain([firstTick - tickStep, scale.domain()[1]])
this.niceTicks = [firstTick - tickStep, ...this.niceTicks]
}

return scale
Expand All @@ -241,7 +246,7 @@ abstract class AbstractAxis {
const d3Scale = isLogScale ? scaleLog : scaleLinear
let scale = d3Scale().domain(this.domain).range(this.range)
if (this.nice && !isLogScale) {
scale = AbstractAxis.makeScaleNice(scale, this.totalTicksTarget)
scale = this.makeScaleNice(scale, this.totalTicksTarget)
}

if (this.config.domainValues) {
Expand Down Expand Up @@ -385,7 +390,9 @@ abstract class AbstractAxis {
} else {
// Only use priority 2 here because we want the start / end ticks
// to be priority 1
ticks = d3_scale.ticks(this.totalTicksTarget).map((tickValue) => ({
const d3_ticks =
this.niceTicks ?? d3_scale.ticks(this.totalTicksTarget)
ticks = d3_ticks.map((tickValue) => ({
value: tickValue,
priority: 2,
}))
Expand Down

0 comments on commit bbb2397

Please sign in to comment.