A simple line / area charting library for iOS, written in Swift.

Line and area charts

Multiple series

Partially filled series

Works with signed Double

Touch events

Installation

CocoaPods

SwiftChart is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "SwiftChart"Copy the code

Manually

  1. Download SwiftChart.zip from the last release and extract its content in your project’s folder.
  2. From the Xcode project, choose Add Files to … from the File menu and add the extracted files.

Usage

The library includes:

Example

let chart = Chart()
let series = ChartSeries([0, 6, 2, 8, 4, 7, 3, 10, 8])
series.color = ChartColors.greenColor()
chart.add(series)Copy the code

To run the example project, clone the repo, and run pod install from the Example directory first.

To initialize a chart

From the Interface Builder

The chart can be initialized from the Interface Builder. Drag a normal View into a View Controller and assign to it the Chart Custom Class from the Identity Inspector.

Programmatically

To initialize a chart programmatically, use the Chart(frame: ...) initializer, which requires a frame:

let chart = Chart(frame: CGRect(x: 0, y: 0, width: 200, height: 100))Copy the code

If you prefer to use Autolayout, set the frame to 0 and add the constraints later:

let chart = Chart(frame: CGRectZero)
// add constraints nowCopy the code

Adding series

Initialize each series before adding them to the chart. To do so, pass an array to initialize a ChartSeries object:

let chart = Chart(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) let series = ChartSeries([0, 6.5, 2, 8, 4.1, 7, -3.1, 10, 8]) chart. Add (series)Copy the code

Result:

As you can see, as default the values on the x-axis are the progressive indexes of the passed array. You can customize those values by passing an array of (x: Double, y: Double) tuples to the series initializer:

let chart = Chart(frame: CGRect(x: 0, y: 0, width: 200, height: New series specifying x and Y values let data = [(x: 0, Y: 0), (x: 1, Y: 3.1), (x: 4, Y: 2), (x: 1) 5, y: 4), (x: 7, y: 5), (x: 9, y: 9), (x: 10, y: 8)] let series = ChartSeries(data: data). Add (series)Copy the code

Result:

Partially filled series

Use the chart.xLabels property to make the x-axis showing more labels than those inferred from the actual data. For example,

Let chart = chart (x: 0, y: 0, width: 200, height: 100) let data = [(x: 0, y: 0), (x: 3, y: 2.5), (x: 1, x: 2)) 4, y: 2), (5 x: y: 2.3), (7 x, y: 3), (8 x: y: 2.2), (9, x: y: 2.5)] let series = ChartSeries (data: data) series.area = true // Use `xLabels` to add more labels, even if empty chart.xLabels = [0, 3, 6, 9, 12, 15, 18, 21, 24] // Format the labels with a unit chart.xLabelsFormatter = { String(Int(round($1))) + "h" } chart.add(series)Copy the code

Result:

Different colors above and below zero

The chart displays the series in different colors when below or above the zero-axis:

let chart = Chart(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) let data: [Double] = [0, -2, -2, 3, -3, 4, 1, 0, -1] let series = ChartSeries(data) series.area = true chart.add(series) // Set minimum and maximum values for y-axis Chart.miny = -7 chart.maxy = 7 // Format Y-axis, e.g., with units chart.ylabelsformatter = {String(Int($1)) + "ºC"}Copy the code

Result:

You can customize the zero-axis and the colors with the colors options in the ChartSeries class.

series.colors = (
    above: ChartColors.greenColor(), 
    below: ChartColors.yellowColor(), 
    zeroLevel: -1
)Copy the code

Result:

Multiple series

Using the chart.add(series: ChartSeries) and chart.add(series: Array<ChartSeries>) methods you can add more series. Those will be indentified with a progressive index in the chart’s series property.

let chart = Chart(frame: CGRect(x: 0, y: 0, width: 200, height: 100)) let series1 = ChartSeries([0, 6, 2, 8, 4, 7, 3, 10, Color = chartcolor.yellowcolor () series1. Area = true let series2 = ChartSeries([1, 0, 0.5, 0.2, 0, 1, 0.8, 0.3, 1]) series2.color = ChartColors.redColor() series2.area = true // A partially filled series let series3 = ChartSeries([9, 8, 10, 8.5, 9.5, 10]) series3. Color = ChartColors. PurpleColor () ChartColors.Copy the code

Result:

Touch events

To make the chart respond to touch events, implement the ChartDelegate protocol in your class, e.g. a View Controller, and then set the chart’s delegate property:

class MyViewController: UIViewController, ChartDelegate {
    override func viewDidLoad() {
        let chart = Chart(frame: CGRect(x: 0, y: 0, width: 100, height: 200))
        chart.delegate = self
    }
    
    // Chart delegate
    func didTouchChart(chart: Chart, indexes: Array<Int?>, x: Double, left: CGFloat) {
        // Do something on touch
    }
    
    func didFinishTouchingChart(chart: Chart) {
        // Do something when finished
    }

    func didEndTouchingChart(chart: Chart) {
        // Do something when ending touching chart
    }
}Copy the code

The didTouchChart method passes an array of indexes, one for each series, with an optional Int referring to the data’s index:

func didTouchChart(chart: Chart, indexes: Array<Int? >, x: Double, left: CGFloat) { for (serieIndex, dataIndex) in enumerate(indexes) { if dataIndex ! = nil { // The series at serieIndex has been touched let value = chart.valueForSeries(serieIndex, atIndex: dataIndex) } } }Copy the code

You can use chart.valueForSeries() to access the value for the touched position.

The x: Double argument refers to the value on the x-axis: it is inferred from the horizontal position of the touch event, and may be not part of the series values.

The left: CGFloat is the x position on the chart’s view, starting from the left side. It may be used to set the position for a label moving above the chart:

Common issues and solutions

If you have issue with this library, please tag your question with swiftchart on Stack Overflow.

The chart is not showing

The Chart class inherits from UIView, so if your chart is not displaying it is likely a problem related to the view’s size. Check your view constraints and make sure you initialize it on viewDidLoad, when UIKit can calculate the view dimensions.

Some tips for debugging an hidden chart:

  • start your app and then debug the UI Hierarchy from the Debug navigator
  • initialize a simple UIView with a colored background instead of the chart to easily see how the view is positioned
  • try to not to nest the chart in a subview for better debugging

Chart class

Chart options

  • areaAlphaComponent— Alpha factor for the area’s color.
  • axesColor– the axes’ color.
  • bottomInset— Height of the area at the bottom of the chart, containing the labels for the X-axis.
  • delegate– The delegate for listening to touch events.
  • highlightLineColor— Color of the highlight line.
  • highlightLineWidth— Width of the highlight line.
  • hideHighlightLineOnTouchEnd (default false) — hide the highlight line when the touch event ends (e.g. when stop swiping over the chart)
  • gridColor– the grid color.
  • labelColor— The color of the labels.
  • labelFont— The font used for the labels.
  • lineWidth— Width of the chart’s lines.
  • maxX– custom maximum x – value.
  • maxY– custom maximum y – value.
  • minX– minimum x – value.
  • minY– minimum y – value.
  • topInsetHeight of the area at the top of the chart, acting a padding to make place for the top Y-axis label.
  • xLabelsFormatter— Formats the labels on the X-axis.
  • xLabelsOrientation– Sets the X-axis labels orientation to vertical or horizontal.
  • xLabelsTextAlignment– text-alignment for the X-labels.
  • xLabelsSkipLast (default true) – Skip the last x-label. Setting this to false will make the label overflow the frame width, so use carefully!
  • yLabelsFormatter— Formats the labels on the Y-axis.
  • yLabelsOnRightSide— Place the Y-labels on the right side.

Methods

  • add(series: ChartSeries)— Add a series to the chart.
  • removeSeries()— Remove all the series from the chart.
  • removeSeriesAtIndex(index: Int)— Remove a series at the specified index.
  • valueForSeries()The value of the specified series at the specified index.

ChartSeries class

  • Area — Draws an area below the series’ line

  • Line – Set it to false to hide the line (Useful for drawing only the area).

  • Color — The series color.

  • Colors — a tuple to specify the color above or below the zero (or another value).

    For example, to use red for values above -4, and blue for values below -4.

    series.colors = (
        above: ChartColors.redColor(), 
        below: ChartColors.blueColor(), 
        zeroLevel: -4
    )Copy the code

ChartDelegate

  • didTouchChart— Telling the delegate that the specified chart has been touched.
  • didFinishTouchingChart— Telling the delegate that the user finished touching the chart. The user will “finish” touching the chart only swiping left/right outside the chart.
  • didEndTouchingChart— Telling the delegate that the user ended touching the chart. The user will “end” touching the chart whenever the touchesDidEnd method is being called.

License

SwiftChart is available under the MIT license. See the LICENSE file for more info.