Algorithm for “nice” grid line intervals on a graph

前端 未结 14 1305
长发绾君心
长发绾君心 2020-11-28 01:45

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 k

14条回答
  •  心在旅途
    2020-11-28 02:08

    There are 2 pieces to the problem:

    1. Determine the order of magnitude involved, and
    2. Round to something convenient.

    You can handle the first part by using logarithms:

    range = max - min;  
    exponent = int(log(range));       // See comment below.
    magnitude = pow(10, exponent);
    

    So, for example, if your range is from 50 - 1200, the exponent is 3 and the magnitude is 1000.

    Then deal with the second part by deciding how many subdivisions you want in your grid:

    value_per_division = magnitude / subdivisions;
    

    This is a rough calculation because the exponent has been truncated to an integer. You may want to tweak the exponent calculation to handle boundary conditions better, e.g. by rounding instead of taking the int() if you end up with too many subdivisions.

提交回复
热议问题