Skip to content

Instantly share code, notes, and snippets.

@aliaspooryorik
Last active February 27, 2020 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliaspooryorik/fc14a2ff29523ff2685f9786b8039400 to your computer and use it in GitHub Desktop.
Save aliaspooryorik/fc14a2ff29523ff2685f9786b8039400 to your computer and use it in GitHub Desktop.
Axis ticks based on range
// based on https://stackoverflow.com/questions/8855026/generate-axis-scale
function calculateTicks(min, max, tickCount) {
var span = max - min,
step = Math.pow(10, Math.floor(Math.log(span / tickCount) / Math.LN10)),
err = tickCount / span * step;
// Filter ticks to get closer to the desired count.
if (err <= .15) step *= 10;
else if (err <= .35) step *= 5;
else if (err <= .75) step *= 2;
// Round start and stop values to step interval.
var tstart = Math.ceil(min / step) * step,
tstop = Math.floor(max / step) * step + step * .5,
ticks = [],
x;
// now generate ticks
for (var i=tstart; i < tstop; i += step) {
ticks.push(Number(i.toFixed(2))); // handle floating point issues
}
ticks.push(Number((i).toFixed(2))); // handle floating point issues
return [...new Set(ticks)]; // strip the duplicates
}
console.clear();
console.log(calculateTicks(0, 99.85, 10));
console.log(calculateTicks(0, 17.85, 10));
console.log(calculateTicks(0, 7.85, 10));
console.log(calculateTicks(0, .75, 10));
console.log(calculateTicks(0, .01, 10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment