Algorithm for “nice” grid line intervals on a graph

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

    Using a lot of inspiration from answers already availible here, here's my implementation in C. Note that there's some extendibility built into the ndex array.

    float findNiceDelta(float maxvalue, int count)
    {
        float step = maxvalue/count,
             order = powf(10, floorf(log10(step))),
             delta = (int)(step/order + 0.5);
    
        static float ndex[] = {1, 1.5, 2, 2.5, 5, 10};
        static int ndexLenght = sizeof(ndex)/sizeof(float);
        for(int i = ndexLenght - 2; i > 0; --i)
            if(delta > ndex[i]) return ndex[i + 1] * order;
        return delta*order;
    }
    

提交回复
热议问题