Skip to content

Commit 2f545c0

Browse files
author
David Alban
committed
Update logarithmicScale (used when forceNiceScale=false) to respect yMin andyMax limits without changing them, and provide a useful log scale between them.
1 parent 8e6b2fa commit 2f545c0

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

src/modules/Scales.js

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -183,22 +183,40 @@ export default class Range {
183183
}
184184

185185
logarithmicScale(yMin, yMax, base) {
186+
// Basic validation to avoid for loop starting at -inf.
187+
if (yMax <= 0) yMax = Math.max(yMin, base)
188+
if (yMin <= 0) yMin = Math.min(yMax, base)
189+
186190
const logs = []
187191

188-
const ticks = Math.ceil(Math.log(yMax) / Math.log(base)) + 1 // Get powers of base up to our max, and then one more
192+
// Get the logarithmic range.
193+
const logMax = Math.log(yMax) / Math.log(base)
194+
const logMin = Math.log(yMin) / Math.log(base)
189195

190-
for (let i = 0; i < ticks; i++) {
191-
logs.push(Math.pow(base, i))
192-
}
196+
// Get the exact logarithmic range.
197+
// (This is the exact number of multiples of the base there are between yMin and yMax).
198+
const logRange = logMax - logMin
193199

194-
if (yMin === 0) {
195-
logs.unshift(yMin)
200+
// Round the logarithmic range to get the number of ticks we will create.
201+
// If the chosen min/max values are multiples of each other WRT the base, this will be neat.
202+
// If the chosen min/max aren't, we will at least still provide USEFUL ticks.
203+
const ticks = Math.round(logRange)
204+
205+
// Get the logarithmic spacing between ticks.
206+
const logTickSpacing = logRange / ticks
207+
208+
// Create as many ticks as there is range in the logs.
209+
for (let i = 0, logTick = logMin; i < ticks; i++, logTick += logTickSpacing) {
210+
logs.push(Math.pow(base, logTick))
196211
}
197212

213+
// Add a final tick at the yMax.
214+
logs.push(Math.pow(base, logMax))
215+
198216
return {
199217
result: logs,
200-
niceMin: logs[0],
201-
niceMax: logs[logs.length - 1]
218+
niceMin: yMin,
219+
niceMax: yMax
202220
}
203221
}
204222

0 commit comments

Comments
 (0)