Search code examples
iosswiftchartsios-charts

iOS Charts Swift bar graph exceeds beyond view


I have a problem with the Charts library. The problem I am facing is that the bar graph is not "fit" within the borders of my view. The following image shows that, the both first and last bar are cut into half and label of the highest bar is also partially cut.

Bars and labels are cut along the graph borders

When I search online, I got the following thread https://github.com/danielgindi/Charts/issues/353 which seems to describe the exact same issue.

I use a simple dataset with some random numbers at 6 indices. The data is added to the chart as follows:

let values: [Int] = [5, 8, 1, 2, 1, 2]
var dataEntries: [BarChartDataEntry]

for i in 0..<values.count {
    let dataEntry = BarChartDataEntry(x: Double(i), y: Double(values[i]))
    dataEntries.append(dataEntry)
}

let chartDataSet = BarChartDataSet(values: dataEntries, label: "Count")
let chartData = BarChartData(dataSet: chartDataSet)
barChartView.data = chartData

Hopefully someone can help me out. Thanks in advance!


Solution

  • There is a bug in the library with regards to calculating the xAxis minimum and maximum.

    You can manually set the xAxis minimum and maximum to prevent the first and last bars to be shown in half.

    Add the below line of code, it should work perfectly fine.

    yourBarChartView.xAxis.axisMinimum = -0.5;
    yourBarChartView.xAxis.axisMaximum = Double(yourAxisDataList.count) - 0.5;