Calculating Min/Max Y-Axis values for a line chart
I am attempting to replicate how 'right' Excel feels with regards to calculating the Y-Axis boundaries for a line chart.
As an example, lets assume I currently have a chart with three datapoints on it. (0, 100), (1,500), (2,930).
The simplistic code I currently have sets the Y-Axis min value to 100 and the Y-Axis max value to 930. The idea was to prevent datasets which have no 0 values from skewing the size of the chart. This works, but I feel that it could be much better.
For the above example, Excel plots the datapoints on the range 0 through 1000. I am trying to create a general algorithm plotting the same 'feel good' range. It is proving to be slightly tricky, however.
I feel that I need a few points of information:
- The order of magnitude for the upper and lower values (power of 10).
- Always take the ceiling / floor of a data point -- it is not very clear when a data point shares the same value as max/min range plotted.
From there I'm at a bit of a loss.
If I take 930 as a max data point value, I know it's order of magnitude is 3. So, I add one to its largest value and zero the rest -- resulting in 1000.
If I take 1030 as a max data point value, I know it's order of magnitude is 4. If I add one to it's largest value and zero the rest the result is 2000. Excel plots 1200 as the max range when graphing (0, 100), (1,500), (2,930), (3,1030).
This problem quickly degrades at larger values -- it's just not quite ri开发者_运维百科ght to always increase the largest value, but it is sometimes. Does anyone have any experience with this that could shed some insight into a better approach?
A quite robust approach is as follows:
- take the range
r = max - min
- assume a padding of approx. five percent (adjust figure if necessary),
pad = r * 0.05
- round
pad
up to the next(1,2,5)*10^n
(e.g.0.23
will be rounded to0.5
while5.5
will be rounded up to10
). - take
axis_min = floor(min/pad-1)*pad
- take
axis_max = ceil(max/pad+1)*pad
Why not just have the range going from something like:
(1-padding) * minimum_value // minimum > 0
(1+padding) * minimum_value // minimum < 0
to
(1+padding) * maximum_value // maximum > 0
(1-padding) * maximum_value // maximum < 0
where padding
is a number between 0
and 1
, e.g. 0.05
.
精彩评论