Algorithm for “nice” grid line intervals on a graph

前端 未结 14 1311
长发绾君心
长发绾君心 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:05

    I use the following algorithm. It's similar to others posted here but it's the first example in C#.

    public static class AxisUtil
    {
        public static float CalcStepSize(float range, float targetSteps)
        {
            // calculate an initial guess at step size
            var tempStep = range/targetSteps;
    
            // get the magnitude of the step size
            var mag = (float)Math.Floor(Math.Log10(tempStep));
            var magPow = (float)Math.Pow(10, mag);
    
            // calculate most significant digit of the new step size
            var magMsd = (int)(tempStep/magPow + 0.5);
    
            // promote the MSD to either 1, 2, or 5
            if (magMsd > 5)
                magMsd = 10;
            else if (magMsd > 2)
                magMsd = 5;
            else if (magMsd > 1)
                magMsd = 2;
    
            return magMsd*magPow;
        }
    }
    

提交回复
热议问题