Bar Chart in iOS using Swift — Charts

Lucky Mehndiratta
4 min readFeb 12, 2022

Today we will show Bar Chart using the charts library in iOS with the help of Swift Language.
Why do we need this?
Sometimes there is a requirement to display the data in some format so that users can understand the resulting outcome throughout the time period, There are lots of ways to fulfill this requirement. But we will use the Bar Chart to display the data.

Steps:
First, we need to add the pod of charts in our pod file
pod ‘Charts’
and, Run the Pod Install so that this pod is added to our project.

Then, We need to take a UIView in a controller where we need to show the Bar chart. The height and width will depend on the project requirement or it's your choice how you want to give the width and height of this UIView.

After this, Add the BarChartView to this UIView through the interface inspector and create an outlet of this UIView to your file in which this UIView is added it may be a UIViewController, UITableViewCell, UICollectionViewCell. It totally depends on your requirement where you want to show and where this UIView is added in the UI hierarchy.

@IBOutlet weak var barChartView: BarChartView!

Now, We need to configure the bar chart view.
To display the data on the Chart you need to understand where the data is or in which form data is structured in your project, It may a Model, Array, Dictionary e.t.c. Once you get to know what this data needs to display then you need to structure this data so that we data will be shown on the Chart. Here we will use the two arrays to display the data on the chart just for understanding.

let actualValue = [1,10,100,1000,10000]
let targetValue = [0,10,10,100,1000]
with the help of these two arrays, we will display the data. One array contains the values of actual the user achieve and the second array contains the target values set by the user(Just for demo purposes you can change it by your data). We are creating a function that will help us to display the data on the barChartView.
func
setDataOnGraph(){

barChartView.clear() → This line clear the data display on the barchart view when ever you call this function. Because sometimes there is requirement to display a new set of data to the barChart. That’s why we will clear each time when we are going to display the data on the barChartView

var xAxixValues = [String]() → This line contains the values of the xAxix in the form of String. Its totally depend on your requirement what you want display on the xAxix. Means you can custom the labels of the xAxix.

barChartView.legend.enabled = false
barChartView.drawGridBackgroundEnabled = false
barChartView.drawBordersEnabled = false
barChartView.leftAxis.enabled = true
barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.enabled = false
barChartView.leftAxis.granularity = 1
barChartView.xAxis.granularity = 1
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.drawAxisLineEnabled = true
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.isExclusiveTouch = true
barChartView.dragEnabled = true
barChartView.setScaleEnabled(false)
barChartView.pinchZoomEnabled = true
barChartView.leftAxis.axisMinimum = 0.0

var dataSetList = [BarChartDataSet]()

var actualValues = [BarChartDataEntry]()
var targetValues = [BarChartDataEntry]()

for(index,_) in actualValue.enumerated(){
actualValues.append(BarChartDataEntry(x: Double(index), y: Double(actualValue[index])))
targetValues.append(BarChartDataEntry(x: Double(index), y: Double(targetValue[index])))
} → Here we convert our data into the BarchartDataEntry, As we need to show two bars in the Barchart in a one group that’s why we takes two dataentry. You can add multiple bar in the same group as per your choice but you need to carefully set these data.

let ds1 = BarChartDataSet(entries: actualValues, label:””)
ds1.setColor(.darkGray) → set the color to the bar

let ds2 = BarChartDataSet(entries: targetValues, label:””)
ds2.setColor(UIColor.brown.withAlphaComponent(0.5)) → set the color to the bar

dataSetList.append(ds2)
dataSetList.append(ds1)

for ds in dataSetList{
ds.highlightAlpha = 0
ds.highlightEnabled = false
ds.drawIconsEnabled = false
ds.drawValuesEnabled = true
}

for (index,_) in (actualValue).enumerated(){
xAxixValues.append(“\(index)”)
} → custom the values of the xAxix here are per your choice but right now we are using only index to show the demo

if !dataSetList.isEmpty && !xAxixValues.isEmpty{
barChartView.xAxis.valueFormatter =
IndexAxisValueFormatter(values:xAxixValues) → Set the formatter to the xAxix,

barChartView.xAxis.labelPosition = .bottom

let data = BarChartData(dataSets: dataSetList) → Create a data using the dataset that will be use to assign to the barChartView.

Now, Most important thing that we need to consider in this chart is
//equation (0.2 + 0.03) * 2 + 0.54 = 1.00 -> (barwidth + barSpace)*(no.of.bars) + groupSpace = 1
This equation is must be follow in this Bar chart. If this equation is not follow than data will be not display on the chart as per our need.

Barwidth → The width of each bar that you want to display in your Barchart
BarSpace → Space between two bars. It's your choice what you want to give
Number of Bars → The number of bars you need to show in one group. Or how many bars do you need to combine 2,3,4,5…
GroupSpace → The space between two groups you want to give

You need to calculate the each value based on your requirement and assign it below. Here you need to do some maths(Most Important thing)

let groupSpace = 0.3
let barSpace = 0.03
let barWidth = 0.32

data.barWidth = barWidth

data.setValueFormatter(IntValueFormatter())
barChartView.xAxis.axisMinimum = -0.2
barChartView.xAxis.axisMaximum = data.xMax + 1
barChartView.data = data
barChartView.xAxis.centerAxisLabelsEnabled = true
barChartView.fitBars = true
barChartView.groupBars(fromX:0, groupSpace: groupSpace, barSpace: barSpace)
barChartView.setVisibleXRange(minXRange: 1, maxXRange: 3) → how many groups will be show at a time rest will be a scrollable. you can scroll in both direction(Forward and Backward)
barChartView.moveViewToX(Double(data.xMax)) → Its you choice you want to scroll to end than you can use this line else you can skip this line of code
}}}

class IntValueFormatter:IValueFormatter,IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let v = Int(value)
if v >= 1000{
return “\(v/1000)K”
}
return “\(v)”
}

func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
let v = Int(value)
if v >= 1000{
return “\(v/1000)K”
}
return “\(v)”
}}

Happy Coding!!
Thank you

--

--