Search code examples
iosswiftios-charts

iOS Charts possibility to rotate a bar chart x-axis label around a different anchor point other than its center


Dears,

I want to achive rotating an x-axis label on a bar chart by 45 degree. That's currently possible with using like this:

chartView.xAxis.labelRotationAngle = -45

And the result is: Bar chart labels

As you see, the rotating anchor point is exactly the center points of the labels.

But i need to rotate them around their very right corner. So, it prevents overlapping each other.


Solution

  • We don't have an easy way to change the rotating anchor point of the labels. But you can define your own custom XAxisRenderer class and override renderAxisLabels function. I have made a simple example and hope this will help you to move in the right direction. I have removed all unnecessary code from renderAxisLabels function and changed anchor point from (x: 0.5, y: 0.0) to (x: 0.8, y: 0.0)

    Define custom renderer

    class MyXAxisRenderer: XAxisRenderer {
        override func renderAxisLabels(context: CGContext)
        {
            guard let xAxis = self.axis as? XAxis else { return }
    
            if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled
            {
                return
            }
    
            let yOffset = xAxis.yOffset
    
            guard xAxis.labelPosition == .bottom else { return  }
    
            let customAnchorPoint = CGPoint(x: 0.8, y: 0.0)  // custom anchor point, default value is (x: 0.5, y: 0.0)
    
            drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: customAnchorPoint)
        }
    }
    

    and use it.

    chartView.xAxis.labelRotationAngle = -45
    chartView.xAxis.labelPosition = .bottom      
    chartView.xAxisRenderer = MyXAxisRenderer(viewPortHandler: chartView.viewPortHandler, xAxis: chartView.xAxis, transformer: chartView.getTransformer(forAxis: .left))