Search code examples
swift3ios-charts

iOS-Charts xAxis Labels cut off


I am using iOS-Charts to show a horizontal bar chart. The x-Axis labels on the left are cut-off. Only when I double tap on the chart, the correct sizing appears to happen and the labels are not cut off anymore.

Here's the code I'm using

    func setChart(_ dataPoints: [(String,Int)], chart: HorizontalBarChartView) {

    chart.noDataText = "No data available."

    var dataEntries: [BarChartDataEntry] = []

    let maxNumberEntries = dataPoints.count

    var xAxisLabel: [String] = []

    var counter:Int = maxNumberEntries-1
    for _ in 0..<maxNumberEntries {
        let dataEntry = BarChartDataEntry(x: Double(counter), yValues: [Double(dataPoints[counter].1)], label: dataPoints[counter].0)
        dataEntries.append(dataEntry)
        xAxisLabel.append(dataPoints[counter].0)
        counter -= 1
    }

    xAxisLabel = xAxisLabel.reversed()

    let chartDataSet = BarChartDataSet(values: dataEntries, label: "")
    let chartData = BarChartData(dataSet: chartDataSet)
    chart.data = chartData
    chart.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)

    // disable zoom of chart
    chart.pinchZoomEnabled = false
    chart.scaleXEnabled = false
    chart.scaleYEnabled = false

    chart.chartDescription?.text = ""
    chart.legend.enabled = false

    // disable selection of bars
    chartDataSet.highlightEnabled = false
    chartDataSet.valueFont = NSUIFont.systemFont(ofSize: 10)

    let numberFormatter = ValueFormatter()
    chartData.setValueFormatter(numberFormatter)

    // specify the width each bar should have
    let barWidth = 0.8
    chartData.barWidth = barWidth

    let formato:BarChartFormatter = BarChartFormatter()
    formato.strings = xAxisLabel
    let xaxis:XAxis = XAxis()

    _ = formato.stringForValue(Double(1), axis: xaxis)
    xaxis.valueFormatter = formato
    chart.xAxis.valueFormatter = xaxis.valueFormatter

    let xAxis = chart.xAxis
    xAxis.labelPosition = XAxis.LabelPosition.bottom // label at bottom
    xAxis.drawGridLinesEnabled = false
    xAxis.granularity = 1.0
    xAxis.labelCount = maxNumberEntries
    xAxis.labelRotationAngle = 0

    // Don't show other axis
    let leftAxis = chart.leftAxis
    leftAxis.enabled = false
    let rightAxis = chart.rightAxis
    rightAxis.enabled = false

}

Any idea how to fix that?

Screenshots:

cut-off xAxis labels

after double tap the labels are not cut-off anymore


Solution

  • I solved this issue by calling

    chart.fitScreen()
    

    for every bar chart once all the data is passed.