Given an array of y-values, like [-3400, -1000, 500, 1200, 3790]
, how do I determine "good" Y-axis labels and positions them on a grid?
^
---(6,000)-|---
|
---(4,000)-|---
|
---(2,000)-|---
|
<------(0)-+---------------------------------------->
|
--(-2,000)-|---
|
--(-4,000)-|---
V
You could do it along the following lines:
n
). The result may not have exactly this many labels, but it will be close. I'm going to have n = 6
.min
) and maximum (max
) of the sequence, the rest of the numbers don't matter. (min = -3400
, max = 3790
)uglyStep = (max - min) / (n - 2)
. We subtract two for the label at the bottom and at the top. (uglyStep = 1797
)uglyStep
as magnitude = 10 ^ floor(log10(uglyStep))
. (magnitude = 1000
)uglyStep
. This will be prettyStep
. (prettyStep = 2000
)bottom = floor(min / prettyStep) * prettyStep
and top = ceil(max / prettyStep) * prettyStep
. Note that /
denotes normal mathematical division, not C-like integer division. (bottom = -4000
, top = 4000
)bottom
and top
that is divisible by prettyStep
is going to have a label. (-4000, -2000, 0, 2000, 4000
)This might need some modifications if you don't want min
and max
to be very close to bottom
and top
.
Also, it sometimes behaves somewhat oddly, e.g. for min = 0
and max = 3002
, it chooses 0, 500, 1000, 1500, 2000, 2500, 3000, 3500
, but for max = 3005
, it uses 0, 1000, 2000, 3000, 4000
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With