Search code examples
iosswiftios-charts

How to set different colors for dots on LineChart at ios charts?


I need to paint values in one range to yellow and other range to red. How to implement it?


Solution

  • There is an much easier ways to color the circles differently. Here is an example which colors each circle with an random color. But you could also think about a conditional coloring like color each circle in red which y-value is greater than 10 or any other condition.

    var yValues: [ChartDataEntry] = []           // y-values
    var xValues: [String?] = []                  // x-values
    var set: LineChartDataSet                    // value set (x- and y-values)
    var circleColors: [NSUIColor] = []           // arrays with circle color definitions
    
    for i in 0..< xValues.count {
        let red   = Double(arc4random_uniform(256))
        let green = Double(arc4random_uniform(256))
        let blue  = Double(arc4random_uniform(256))
    
        let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
        circleColors.append(color)
    }
    
    // set colors and enable value drawing    
    set.colors = circleColors
    set.drawValuesEnabled = true
    set.valueFont = UIFont.systemFontOfSize(12.0)