Nice Label Algorithm for Charts with minimum ticks

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

    Much BETTER and SIMPLER algorythm on swift. Size is fixed, values are not "hardcoded":

    class NiceNumbers {
        /// Returns nice range of specified size. Result min <= min argument, result max >= max argument.
        static func getRange(forMin minInt: Int, max maxInt: Int, ofSize size: Int) -> [Int] {
            let niceMinInt = getMinCloseToZero(min: minInt, max: maxInt)
            let step = Double(maxInt - niceMinInt) / Double(size - 1)
            let niceStepInt = Int(get(for: step, min: false))
    
            var result = [Int]()
            result.append(niceMinInt)
            for i in 1...size - 1 {
                result.append(niceMinInt + i * Int(niceStepInt))
            }
            return result
        }
    
        /// Returns nice min or zero if it is much smaller than max.
        static func getMinCloseToZero(min: Int, max: Int) -> Int {
            let nice = get(for: Double(min), min: true)
            return nice <= (Double(max) / 10) ? 0 : Int(nice)
        }
    
        /// Get nice number. If min is true returns smaller number, if false - bigger one.
        static func get(for number: Double, min: Bool) -> Double {
            if number == 0 { return 0 }
            let exponent = floor(log10(number)) - (min ? 0 : 1)
            let fraction = number / pow(10, exponent)
            let niceFraction = min ? floor(fraction) : ceil(fraction)
            return niceFraction * pow(10, exponent)
        }
    }
    

    Tested only on positive numbers.

提交回复
热议问题