algorithmchartsgraph

Algorithm for "nice" grid line intervals on a graph


I need a reasonably smart algorithm to come up with "nice" grid lines for a graph (chart).

For example, assume a bar chart with values of 10, 30, 72 and 60. You know:

Min value: 10 Max value: 72 Range: 62

The first question is: what do you start from? In this case, 0 would be the intuitive value but this won't hold up on other data sets so I'm guessing:

Grid min value should be either 0 or a "nice" value lower than the min value of the data in range. Alternatively, it can be specified.

Grid max value should be a "nice" value above the max value in the range. Alternatively, it can be specified (eg you might want 0 to 100 if you're showing percentages, irrespective of the actual values).

The number of grid lines (ticks) in the range should be either specified or a number within a given range (eg 3-8) such that the values are "nice" (ie round numbers) and you maximise use of the chart area. In our example, 80 would be a sensible max as that would use 90% of the chart height (72/80) whereas 100 would create more wasted space.

Anyone know of a good algorithm for this? Language is irrelevant as I'll implement it in what I need to.


Solution

  • CPAN provides an implementation here (see source link)

    See also Tickmark algorithm for a graph axis

    FYI, with your sample data:

    • Maple: Min=8, Max=74, Labels=10,20,..,60,70, Ticks=10,12,14,..70,72
    • MATLAB: Min=10, Max=80, Labels=10,20,,..,60,80