Core Plot Tutorial: Getting Started

In this Core Plot tutorial you’ll learn how to plot your data on beautiful pie and scatter charts using Swift and the open source Core Plot framework. By Attila Hegedüs.

3.7 (3) · 1 Review

Save for later
Share

Note: This Core Plot tutorial has been updated for iOS 10 and Swift 3.0 by Attila Hegedüs. The original tutorial was written by tutorial team member Steve Baranski.

If you’ve ever wanted to include charts or graphs in your app, chances are you’ve considered the following two options:

  1. DIY. Write all of the drawing code yourself using Core Graphics and/or Quartz. However, this can be a lot of work.
  2. Buy it! Purchase a commercial framework like ShinobiControls. This may save you time, but it will cost you to use it.

But what if you don’t want to the spend time and effort to write something from scratch, yet you also don’t want to shell out a ton of money? That’s where a third option comes in handy: use the open-source Core Plot library!

Core Plot is a 2D plotting library for iOS, Mac OS X, and tvOS. It uses Apple frameworks like Quartz and Core Animation; it has solid test coverage; and it’s released under a permissive BSD license.

In this Core Plot tutorial, you will learn how to use Core Plot to create pie charts and bar graphs. You’ll also create cool chart interactions!

Before you begin, you need to have Xcode 8.0 installed and a basic understanding of Swift, Interface Builder and storyboards. If you are new to any of these topics, you should go through some of our other tutorials first before continuing with this Core Plot tutorial.

This Core Plot tutorial also uses CocoaPods to install third-party library dependencies. If you’ve never used CocoaPods before, you should read our tutorial about it first.

Getting Started

In this Core Plot tutorial, you’ll create an app that displays currency exchange rates for a given time interval. Download the starter project for this Core Plot tutorial from here. Unzip the archive, and open SwiftRates.xcworkspace.

The key classes for this Core Plot tutorial are located under the App group and its subgroups. These include:

  • DataStore.swift
    This is a helper class that requests currency exchange rates from Fixer.io.
  • Rate.swift
    This is a model representing currency exchange rates on a given date.
  • Currency.swift
    This is a model for a currency type. The supported currencies are defined in Resources/Currencies.plist.
  • MenuViewController.swift
    This is the first view controller shown when the app launches. It lets the user select a base currency and two comparisons.
  • HostViewController.swift
    This is a container view controller that displays either PieChartViewController or BarGraphViewController based on its segmented control’s selected index. It also takes care of requesting rates from the DataStore, which it sets on its displayed view controller.
  • PieChartViewController.swift
    This will show a pie chart for exchange rates on a given day. You’ll implement this chart first!
  • BarGraphViewController.swift
    This will show a bar graph for exchange rates over several days. After mastering the pie chart, this will be a piece of cake! (See what I did there? Oh, come on! It was a little funny.) ;]

Build and run to see the starter project for this Core Plot tutorial in action.

Core Plot Tutorial

Select Get Rates to navigate to the HostViewController and then change the segmented control’s selection. The app really doesn’t do very much… yet. ;]

It’s time in this Core Plot tutorial to get plotting!

Installing Core Plot

First in this Core Plot tutorial, you need to install Core Plot. The easiest way to do this is via CocoaPods.

Add the following to your Podfile, right after the pod 'SwiftDate' line:

pod 'CorePlot', '~> 2.2'

Open Terminal; cd into your project directory; and run pod install.

After the install completes, build the project.

No errors, right? Great, you’re all setup to use Core Plot. Thanks, CocoaPods. :]

If you do get any errors, try updating CocoaPods via sudo gem install cocoapods and then pod install again.

Creating the Pie Chart

Open PieChartViewController.swift and add the following import:

import CorePlot

Next, add the following property:

@IBOutlet weak var hostView: CPTGraphHostingView!

CPTGraphHostingView is responsible for “hosting” a chart/graph. You can think of it as a “graph container”.

Next, add the following class extension after the ending class curly brace:

extension PieChartViewController: CPTPieChartDataSource, CPTPieChartDelegate {
    
  func numberOfRecords(for plot: CPTPlot) -> UInt {
    return 0
  }
    
  func number(for plot: CPTPlot, field fieldEnum: UInt, record idx: UInt) -> Any? {
    return 0
  }
    
  func dataLabel(for plot: CPTPlot, record idx: UInt) -> CPTLayer? {
    return nil
  }
    
  func sliceFill(for pieChart: CPTPieChart, record idx: UInt) -> CPTFill? {
    return nil
  }
    
  func legendTitle(for pieChart: CPTPieChart, record idx: UInt) -> String? {
    return nil
  }  
}

You provide data for a Core Plot chart via CPTPieChartDataSource, and you get user interaction events via CPTPieChartDelegate. You’ll fill in these methods as the Core Plot tutorial progresses.

Setting Up the Graph Host View

To continue this Core Plot tutorial, open Main.storyboard and select the PieChartViewController scene.

Drag a new UIView onto this view. Change its class to CPTGraphHostingView, and connect it to the hostView outlet.

Add constraints on each side to pin this view to its parent view, making sure that Constrain to margins is NOT set:

Core Plot Tutorial

Set the background color to any color you like. I used a gray scale color with an opacity of 92%.

Back in PieChartViewController.swift, add the following methods right after viewDidLoad():

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  initPlot()
}

func initPlot() {
  configureHostView()
  configureGraph()
  configureChart()
  configureLegend()
}

func configureHostView() {
}

func configureGraph() {
}

func configureChart() {
}

func configureLegend() {
}

This sets up the plot right after the subviews are laid out. This is the earliest that the frame size for the view has been set, which you’ll need to configure the plot.

Each method within initPlot() represents a stage in setting up the plot. This helps keep the code a bit more organized.

Add the following to configureHostView():

hostView.allowPinchScaling = false

This disables pinching scaling on the pie chart, which determines whether the host view responds to pinch gestures.

You next need to add a graph to the hostView. Add the following to configureGraph():

// 1 - Create and configure the graph
let graph = CPTXYGraph(frame: hostView.bounds)
hostView.hostedGraph = graph
graph.paddingLeft = 0.0
graph.paddingTop = 0.0
graph.paddingRight = 0.0
graph.paddingBottom = 0.0
graph.axisSet = nil

// 2 - Create text style
let textStyle: CPTMutableTextStyle = CPTMutableTextStyle()
textStyle.color = CPTColor.black()
textStyle.fontName = "HelveticaNeue-Bold"
textStyle.fontSize = 16.0
textStyle.textAlignment = .center

// 3 - Set graph title and text style
graph.title = "\(base.name) exchange rates\n\(rate.date)"
graph.titleTextStyle = textStyle
graph.titlePlotAreaFrameAnchor = CPTRectAnchor.top

Here’s a breakdown for each section:

You first create an instance of CPTXYGraph and designate it as the hostedGraph of the hostView. This associates the graph with the host view.

The CPTGraph encompasses everything you see in a standard chart or graph: the border, the title, the plotted data, axes, and legend.

By default, CPTXYGraph has a padding of 20 points per side. This doesn’t look great here, so you explicitly set the padding for each side to 0.

  1. You first create an instance of CPTXYGraph and designate it as the hostedGraph of the hostView. This associates the graph with the host view.

    The CPTGraph encompasses everything you see in a standard chart or graph: the border, the title, the plotted data, axes, and legend.

    By default, CPTXYGraph has a padding of 20 points per side. This doesn’t look great here, so you explicitly set the padding for each side to 0.

  2. You next set up the text style for the graph’s title by creating and configuring a CPTMutableTextStyle instance.
  3. Lastly, you set the title for the graph and set its style to the one you just created. You also specify the anchoring point to be the top of the view’s bounding rectangle.

Build and run the app, and you should see the chart’s title displayed at the top of the screen:

Core Plot Tutorial

Attila Hegedüs

Contributors

Attila Hegedüs

Author

Over 300 content creators. Join our team.