Algorithm for “nice” grid line intervals on a graph

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

    Here's another implementation in JavaScript:

    var calcStepSize = function(range, targetSteps)
    {
      // calculate an initial guess at step size
      var tempStep = range / targetSteps;
    
      // get the magnitude of the step size
      var mag = Math.floor(Math.log(tempStep) / Math.LN10);
      var magPow = Math.pow(10, mag);
    
      // calculate most significant digit of the new step size
      var magMsd = Math.round(tempStep / magPow + 0.5);
    
      // promote the MSD to either 1, 2, or 5
      if (magMsd > 5.0)
        magMsd = 10.0;
      else if (magMsd > 2.0)
        magMsd = 5.0;
      else if (magMsd > 1.0)
        magMsd = 2.0;
    
      return magMsd * magPow;
    };
    

提交回复
热议问题