How to create a Combined Bar and Line chart using ios-charts

This tutorial is part of a series on iso-charts, if you haven't looked over the introduction I'd advise doing so before continuing. In this tutorial, we'll be making a combined chart using iOS-charts.

We’ll begin by creating a new single view application, we’ll name it and click create.

Go to the main.storyboard and search for “View” in the Object Library and you’ll see it near the bottom of the list. Drag the view out onto your view controller, position it however you like and add some basic constraints.

In the identity inspector, set the class for your new View to “CombinedChartView”, if you aren’t seeing an option for such a class please make sure you’ve followed the installation steps listed here.

If everything has gone well your main.storyboard should look like this:

one.png

 

Setting up our CombinedChartView object

Click on your Assistant Editor to reveal your ViewController.swift code. We’ll need to add an import statement and adopt a protocol before we can begin wiring up our Line Chart. Modify your class signature to look like this:

    
import Charts

class ViewController: UIViewController, ChartViewDelegate { //...

Now we can control drag from our View to our ViewController class and create an outlet named chartView with a type of CombinedChartView.

    
@IBOutlet weak var chartView: CombinedChartView!

We can now start setting the properties of our chartView object. For simplicity, we'll just set our chart properties in our  viewDidLoad, add the following lines of code:

    
override func viewDidLoad() {
    super.viewDidLoad()
    // 1    
    chartView.delegate = self
    // 2
    chartView.descriptionText = "Tap node for details" 
    // 3
    chartView.noDataTextDescription = "You need to provide data for the chart." 
    // 4
    chartView.drawBarShadowEnabled = false 
    // 5
    chartView.leftAxis.startAtZeroEnabled = false 
 
}

I should point out that not all of these options are necessary, I've just included them to expose you to more options.

  1. We set the ChartViewDelegate to our ViewController.
  2. We change the descriptionText that will appear at the bottom of our chart.
  3. Here, we are setting the "no data" description for when our chart's data source is empty.
  4. We're removing the bar shadow for a cleaner look.
  5. Disable "starting at zero" so that our charts start near the lowest data point.

Setting Data

In this dataset, we'll just utilize some random numbers. At the top of your ViewController add the following properties. 

    
var dataSet1 : [Double] = [123, 154, 132, 119, 134, 122, 126, 156, 143, 157, 163, 212] 
    var dataSet2 : [Double] = [132, 119, 139, 122, 126, 135, 145, 116, 123, 140, 135, 132] 
    var dataSet3 : [Double] = [112, 99, 102, 92, 96, 115, 105, 102, 99, 110, 115, 108] 
    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 

Then, add the following after the last line of code in your viewDidLoad:

    
// 6 
    let data: CombinedChartData = CombinedChartData(xVals: months) 
    data.lineData = self.setLineData()
    data.barData = self.setBarData()
    // 7
    chartView.data = data 
    // 8
    chartView.animate(xAxisDuration: 0.2, yAxisDuration: 1.0, easingOptionX: .EaseInExpo, easingOptionY: .EaseInExpo)
    
  1. Here we set up our CombinedChartData adding both lineData and bar Data.
  2. Add our data to the chartView.
  3. animate our chart.

Next, we'll define our two function  we used to set our lineData and our barData:

    
func setLineData() { }
func setBarData() { }

For this part of the tutorial, we'll set each chart up with two sets of data, which will create a single red line across our graph. I won't go into detail here because as you read through you'll get a good idea of what the properties mean.    

    
func setLineData(months : [String]) {
        var xVals: [ChartDataEntry] = [ChartDataEntry]()
        for i in 0 ..< months.count {
            xVals.append(ChartDataEntry(value: dataSet1[i], xIndex: i))
        }
        
        // 1 ////////////////
        var yVals: [ChartDataEntry] = [ChartDataEntry]()
        for i in 0 ..< months.count {
            yVals.append(ChartDataEntry(value: dataSet1[i], xIndex: i))
        }
        
        let set1: LineChartDataSet = LineChartDataSet(yVals: yVals, label: "Line set 1")
        set1.axisDependency = .Left
        set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5))
        set1.setCircleColor(UIColor.redColor())
        set1.lineWidth = 2.0
        set1.circleRadius = 6.0
        set1.fillAlpha = 65 / 255.0
        set1.fillColor = UIColor.redColor()
        set1.highlightColor = UIColor.whiteColor()
        set1.drawCircleHoleEnabled = true
        
        // 2 ////////////////
        var yVals2: [ChartDataEntry] = [ChartDataEntry]()
        for i in 0 ..< months.count { 
            let dataEntry: ChartDataEntry = ChartDataEntry(value: dataSet2[i] + 100, xIndex: i)
            yVals2.append(dataEntry)
        }
        let set2: LineChartDataSet = LineChartDataSet(yVals: yVals2, label: "Line set 2")
        set2.axisDependency = .Left
        set2.setColor(UIColor.greenColor().colorWithAlphaComponent(0.5))
        set2.setCircleColor(UIColor.greenColor())
        set2.lineWidth = 2.0
        set2.circleRadius = 6.0
        set2.fillAlpha = 65 / 255.0
        set2.fillColor = UIColor.greenColor()
        set2.highlightColor = UIColor.whiteColor()
        set2.drawCircleHoleEnabled = true
        
        // data sets
        var dataSets: [LineChartDataSet] = [LineChartDataSet]()
        dataSets.append(set1)
        dataSets.append(set2) 
        let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
        
        data.setValueTextColor(UIColor.whiteColor())
        data.setValueFont(UIFont.systemFontOfSize(9))
        
        
        return data            
    }
    <>
    

Then we'll do the same for our barCharData function:

    
func setBarData() -> BarChartData {
        let d: BarChartData = BarChartData()
        
        var entries1: [ChartDataEntry] = [ChartDataEntry]()
        for index in 0 ..< months.count {
            entries1.append(BarChartDataEntry(value: Double(Int.random(25...45)) * 100, xIndex: index))
        }
        let set1: BarChartDataSet = BarChartDataSet(yVals: entries1, label: "Bar Data")
        set1.setColor(UIColor.darkGrayColor())
        set1.valueTextColor = UIColor.redColor()
        set1.valueFont = UIFont.systemFontOfSize(10)
        set1.axisDependency = .Right
        d.addDataSet(set1)
        
        var entries2: [ChartDataEntry] = [ChartDataEntry]()
        for index in 0 ..< months.count {
            entries2.append(BarChartDataEntry(value: Double(Int.random(25...45)) * 100, xIndex: index))
        }
        let set2: BarChartDataSet = BarChartDataSet(yVals: entries2, label: "Bar Data")
        set2.setColor(UIColor.blackColor())
        set2.valueTextColor = UIColor.redColor()
        set2.valueFont = UIFont.systemFontOfSize(10)
        set2.axisDependency = .Right
        d.addDataSet(set2)
        
        // data sets
        var dataSets: [BarChartDataSet] = [BarChartDataSet]()
        dataSets.append(set1)
        dataSets.append(set2)
        let data: BarChartData = BarChartData(xVals: months, dataSets: dataSets)
        
        data.setValueTextColor(UIColor.whiteColor())
        data.setValueFont(UIFont.systemFontOfSize(9))

        
        return data
    }
    

Build and run

Build and run and you should see your combinedChart in action!

 

In Tags

Adding multiple lines to your Line Chart using ios-charts

In part 1 we created a single line chart, in this tutorial we'll simply add 2 more data sets to our Line-Chart.

Multiple Lines

To add multiple lines you simply add multiple datasets like so:

    
let dollars1 = [1453.0,2352,5431,1442,5451,6486,1173,5678,9234,1345,9411,2212]
let dollars2 = [5641.0,2234,8763,4453,4548,6236,7321,3458,2139,399,1311,5612]
let dollars3 = [6541.0,3456,7843,5678,5877,7323,7111,6456,5143,4562,6311,10412]
    

Once you have your data sets you can simply repeat what we've did in our last tutorial to add additional lines:

    
func setChartData(months : [String]) {
        
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals1.append(ChartDataEntry(value: dollars1[i], xIndex: i))
    }
        
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "First Set")
    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5))
    set1.setCircleColor(UIColor.redColor())
    set1.lineWidth = 2.0
    set1.circleRadius = 6.0
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.redColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true
        
    var yVals2 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals2.append(ChartDataEntry(value: dollars2[i], xIndex: i))
    }
        
    let set2: LineChartDataSet = LineChartDataSet(yVals: yVals2, label: "Second Set")
    set2.axisDependency = .Left // Line will correlate with left axis values
    set2.setColor(UIColor.greenColor().colorWithAlphaComponent(0.5))
    set2.setCircleColor(UIColor.greenColor())
    set2.lineWidth = 2.0
    set2.circleRadius = 6.0
    set2.fillAlpha = 65 / 255.0
    set2.fillColor = UIColor.greenColor()
    set2.highlightColor = UIColor.whiteColor()
    set2.drawCircleHoleEnabled = true
        
    var yVals3 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals3.append(ChartDataEntry(value: dollars3[i], xIndex: i))
    }
        
    let set3: LineChartDataSet = LineChartDataSet(yVals: yVals3, label: "Second Set")
    set3.axisDependency = .Left // Line will correlate with left axis values
    set3.setColor(UIColor.blueColor().colorWithAlphaComponent(0.5))
    set3.setCircleColor(UIColor.blueColor())
    set3.lineWidth = 2.0
    set3.circleRadius = 6.0
    set3.fillAlpha = 65 / 255.0
    set3.fillColor = UIColor.blueColor()
    set3.highlightColor = UIColor.whiteColor()
    set3.drawCircleHoleEnabled = true
        
    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)
    dataSets.append(set2)
    dataSets.append(set3)
        
    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
    data.setValueTextColor(UIColor.whiteColor())
        
    //5 - finally set our data
    self.lineChartView.data = data
}

Build and run

You should now see multiple lines on your graph, if you're having an issue check out the project files.

In Tags

How to create a Line Chart using ios-charts

This tutorial is part of a series on iso-charts, if you haven't looked over the introduction I'd advise doing so before continuing. In this tutorial we'll be making a single line Line Chart using iOS-charts.

We’ll begin by creating a new single view application, we’ll name it and click create.

Go to the main.storyboard and search for “View” in the Object Library and you’ll see it near the bottom of the list. Drag the view out onto your view controller, position it however you like and add some basic constraints.

In the identity inspector, set your class to “LineChartView”, if you aren’t seeing an option for such a class please make sure you’ve followed the installation steps listed here.

If everything has gone well your main.storyboard should look like this:

20151018043029addLineChartView.png

Setting up our LineChartView object

Click on your Assistant Editor to reveal your ViewController.swift code. We’ll need to add an import statement and adopt a protocol before we can begin wiring up our Line Chart. Modify your class signature to look like this:

    
import Charts
class ViewController: UIViewController, ChartViewDelegate { //...
    

Now we can control drag from our View to our ViewController class and create an outlet named lineChartView with a type of LineChartView.

20151018043325Screenshot 2015-10-17 22.34.21.png
    
@IBOutlet weak var lineChartView: LineChartView!

We can now start setting the properties of our lineChartView object. in your viewDidLoad add the following lines of code:

    
override func viewDidLoad() {
    super.viewDidLoad()    
    // 1
    self.lineChartView.delegate = self
    // 2
    self.lineChartView.descriptionText = "Tap node for details"
    // 3
    self.lineChartView.descriptionTextColor = UIColor.whiteColor()
    self.lineChartView.gridBackgroundColor = UIColor.darkGrayColor()
    // 4
    self.lineChartView.noDataText = "No data provided"
    // 5
    setChartData(months)
        
}

func setChartData() {

}

  1. We set the ChartViewDelegate to our ViewController.
  2. We change the `descriptionText` that will appear at the bottom of our chart.
  3. Here, we set our description text color to white and our grid background color to dark grey.
  4. We make sure our user get feedback if there is not data provided.
  5. Finally, we call / create a custom function that will add data to our chart.

Setting Data

Of course, a very common thing to chart is money over time, and that what we’ll do in this example. So we’ll modify the signature of our setChartData method call to take an array of strings for our months.

    
setChartData(months) // in viewDidLoad
func setChartData(months : [String]) { }
	

And we’ll have to create an array of months as a class level object. While we’re at it, lets go ahead and add three variables that hold our month-to-month dollar amount.

    
let months = ["Jan" , "Feb", "Mar", "Apr", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec"]
    
let dollars1 = [1453.0,2352,5431,1442,5451,6486,1173,5678,9234,1345,9411,2212]

For this part of the tutorial, we'll set our chart up with just one set of data, which will create a single red line across our graph. First the code, then the explanation.

    
func setChartData(months : [String]) {
    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals1.append(ChartDataEntry(value: dollars1[i], xIndex: i))
    }
        
    // 2 - create a data set with our array
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "First Set")
    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5)) // our line's opacity is 50%
    set1.setCircleColor(UIColor.redColor()) // our circle will be dark red
    set1.lineWidth = 2.0 
    set1.circleRadius = 6.0 // the radius of the node circle
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.redColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true
        
    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)
        
    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
    data.setValueTextColor(UIColor.whiteColor())
        
    //5 - finally set our data
    self.lineChartView.data = data            
}
  1. We start by creating an array of ChartDataEntry items, to which we'll create and append one item for every value stored in our dollars array.
  2. We create a LineChartDataSet that take our array as its first parameter and a label for its second, this dataset represents the line we'll be creating. We continue by setting the attributes that belong to this class object.
  3. Since we're ultimately on a path to create a multi-lined array, we'll create a data set array that will just hold our single set.
  4. Create a data object that takes our months and our single data set.
  5. Set it as our lineCharView objects data 

Build and run

Build and run and you should see your first chart, congratulations, it gets better from here so move on to part II, where we augment this chart with multiple lines.

20151018050325Screen Shot 2015-10-18 at 12.02.56 AM.png