Nice Label Algorithm for Charts with minimum ticks

后端 未结 16 2052
清酒与你
清酒与你 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:35

    This is the Swift version:

    class NiceScale {
        private var minPoint: Double
        private var maxPoint: Double
        private var maxTicks = 10
        private(set) var tickSpacing: Double = 0
        private(set) var range: Double = 0
        private(set) var niceMin: Double = 0
        private(set) var niceMax: Double = 0
    
        init(min: Double, max: Double) {
            minPoint = min
            maxPoint = max
            calculate()
        }
    
        func setMinMaxPoints(min: Double, max: Double) {
            minPoint = min
            maxPoint = max
            calculate()
        }
    
        private func calculate() {
            range = niceNum(maxPoint - minPoint, round: false)
            tickSpacing = niceNum(range / Double((maxTicks - 1)), round: true)
            niceMin = floor(minPoint / tickSpacing) * tickSpacing
            niceMax = floor(maxPoint / tickSpacing) * tickSpacing
        }
    
        private func niceNum(range: Double, round: Bool) -> Double {
            let exponent = floor(log10(range))
            let fraction = range / pow(10, exponent)
            let niceFraction: Double
    
            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(10, exponent)
        }
    }
    

提交回复
热议问题