Nice Label Algorithm for Charts with minimum ticks

后端 未结 16 2081
清酒与你
清酒与你 2020-11-29 17:07

I need to calculate the Ticklabels and the Tickrange for charts manually.

I know the \"standard\" algorithm for nice ticks (see http://books.google.de/books?id=fvA7

16条回答
  •  生来不讨喜
    2020-11-29 17:43

    I needed this algorithm converted to C#, so here it is...

    public static class NiceScale {
    
        public static void Calculate(double min, double max, int maxTicks, out double range, out double tickSpacing, out double niceMin, out double niceMax) {
            range = niceNum(max - min, false);
            tickSpacing = niceNum(range / (maxTicks - 1), true);
            niceMin = Math.Floor(min / tickSpacing) * tickSpacing;
            niceMax = Math.Ceiling(max / tickSpacing) * tickSpacing;
        }
    
        private static double niceNum(double range, bool round) {
            double pow = Math.Pow(10, Math.Floor(Math.Log10(range)));
            double fraction = range / pow;
    
            double niceFraction;
            if (round) {
                if (fraction < 1.5) {
                    niceFraction = 1;
                } else if (fraction < 3) {
                    niceFraction = 2;
                } else if (fraction < 7) {
                    niceFraction = 5;
                } else {
                    niceFraction = 10;
                }
            } else {
                if (fraction <= 1) {
                    niceFraction = 1;
                } else if (fraction <= 2) {
                    niceFraction = 2;
                } else if (fraction <= 5) {
                    niceFraction = 5;
                } else {
                    niceFraction = 10;
                }
            }
    
            return niceFraction * pow;
        }
    
    }
    

提交回复
热议问题