Skip to content
Swift library for Data Visualization 📊
C++ Swift Jupyter Notebook Other
Branch: master
Clone or download
Latest commit a6f26e8 Sep 28, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
Notebooks rfac: Update Jupyter Notebook to use latest code Sep 28, 2019
Tests Add third party libraries May 15, 2019
examples chor: Update Examples Aug 11, 2019
framework chor: Update Examples Aug 11, 2019
.gitignore conf: Add .ipynb_checkpoints to gitignore Jun 18, 2019
LICENSE Update license year May 10, 2019
Package.resolved
Package.swift feat: Add ability to use custom fonts to AGG and SVG renderers Jul 21, 2019
README.md Update README.md Sep 28, 2019
run_examples.sh feat: Implement stacked histogram for step type and update examples Jun 29, 2019
swiftplot.png Merge master into bar_chart Jun 1, 2019

README.md


License

Table of contents

Overview

The SwiftPlot framework is a cross-platform library that lets you plot graphs natively in Swift. The existing Swift plotting frameworks (such as CorePlot) run only on iOS or Mac. The idea behind SwiftPlot is to create a cross-platform library that runs on iOS, Mac, Linux and Windows.

SwiftPlot currently uses two rendering backends to generate plots:

  • Anti-Grain Geometry(AGG) C++ rendering library
  • A simple SVG Renderer

To encode the plots as PNG images it uses the lodepng library.
SwiftPlot can also be used in Jupyter Notebooks.

Examples, demonstrating all the features, have been included with the repository under the examples directory. To run the examples, clone the repository, and run the run_examples.sh script as shown below.

run_examples.sh

Jupyter Notebook examples are under the Notebooks directory.

The resultant images are stored in the examples/Reference directory. The images rendered by each of the backends are stored their respective directories: agg and svg.

License

SwiftPlot is licensed under Apache 2.0. View license

How to include the library in your package

Add the library to your projects dependencies in the Package.swift file as shown below.

dependencies: [
        .package(url: "https://github.com/KarthikRIyer/swiftplot.git", .exact("1.0.0")),
    ],

In case you get an error saying that a file ft2build.h is not found, you need to install the freetype development package.

Linux

sudo apt-get install libfreetype6-dev

macOS

brew install freetype

If the above method doesn't work you can also build and install freetype on your own. You can find the source code and build instructions here.

How to include the library in your Jupyter Notebook

Add these lines to the first cell:

%install-swiftpm-flags -Xcc -isystem/usr/include/freetype2 -Xswiftc -lfreetype
%install '.package(url: "https://github.com/KarthikRIyer/swiftplot", from: "1.0.0")' SwiftPlot

In order to display the generated plot in the notebook, add this line to a new cell:

%include "EnableJupyterDisplay.swift"

Examples

Here are some examples to provide you with a headstart to using this library. Here we will be looking at plots using only the AGGRenderer, but the procedure will remain the same for SVGRenderer. To use the library in your package, include it as a dependency to your target, in the Package.swift file.

Simple Line Graph

import SwiftPlot
import AGGRenderer

let x:[Float] = [10,100,263,489]
let y:[Float] = [10,120,500,800]

var agg_renderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Float,Float>(enablePrimaryAxisGrid: true)
lineGraph.addSeries(x, y, label: "Plot 1", color: .lightBlue)
lineGraph.plotTitle = PlotTitle("SINGLE SERIES")
lineGraph.plotLabel = PlotLabel(xLabel: "X-AXIS", yLabel: "Y-AXIS")
lineGraph.plotLineThickness = 3.0
lineGraph.drawGraphAndOutput(fileName: filePath+"agg/"+fileName, renderer: agg_renderer)

Line Graph with multiple series of data

import SwiftPlot
import AGGRenderer
import SVGRenderer

let x1:[Float] = [0,100,263,489]
let y1:[Float] = [0,320,310,170]
let x2:[Float] = [0,50,113,250]
let y2:[Float] = [0,20,100,170]

var agg_renderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Float,Float>(enablePrimaryAxisGrid: true)
lineGraph.addSeries(x1, y1, label: "Plot 1", color: .lightBlue)
lineGraph.addSeries(x2, y2, label: "Plot 2", color: .orange)
lineGraph.plotTitle = PlotTitle("MULTIPLE SERIES")
lineGraph.plotLabel = PlotLabel(xLabel: "X-AXIS", yLabel: "Y-AXIS")
lineGraph.plotLineThickness = 3.0
lineGraph.drawGraphAndOutput(fileName: filePath+"agg/"+fileName, renderer: agg_renderer)

Line Graph with Sub Plots stacked horizontally

import SwiftPlot
import AGGRenderer

let x:[Float] = [10,100,263,489]
let y:[Float] = [10,120,500,800]

var agg_renderer: AGGRenderer = AGGRenderer()
var plots = [Plot]()

var lineGraph1 = LineGraph<Float,Float>(enablePrimaryAxisGrid: true)
lineGraph1.addSeries(x, y, label: "Plot 1", color: .lightBlue)
lineGraph1.plotTitle = PlotTitle("PLOT 1")
lineGraph1.plotLabel = PlotLabel(xLabel: "X-AXIS", yLabel: "Y-AXIS")
lineGraph1.plotLineThickness = 3.0

var lineGraph2 = LineGraph<Float,Float>(enablePrimaryAxisGrid: true)
lineGraph2.addSeries(x, y, label: "Plot 2", color: .orange)
lineGraph2.plotTitle = PlotTitle("PLOT 2")
lineGraph2.plotLabel = PlotLabel(xLabel: "X-AXIS", yLabel: "Y-AXIS")
lineGraph2.plotLineThickness = 3.0

plots.append(lineGraph1)
plots.append(lineGraph2)

var subPlot: SubPlot = SubPlot(numberOfPlots: 2, stackPattern: .horizontallyStacked)
subPlot.draw(plots: plots, renderer: agg_renderer, fileName: "subPlotsHorizontallyStacked")

Plot functions using LineGraph

import Foundation
import SwiftPlot
import AGGRenderer

func function(_ x: Float)->Float {
    return 1.0/x
}

var agg_renderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Float,Float>(enablePrimaryAxisGrid: true)
lineGraph.addFunction(function, minX: -5.0, maxX: 5.0, numberOfSamples: 400, label: "Function", color: .orange)
lineGraph.plotTitle = PlotTitle("FUNCTION")
lineGraph.plotLabel = PlotLabel(xLabel: "X-AXIS", yLabel: "Y-AXIS")
lineGraph.drawGraphAndOutput(fileName: "functionPlotLineGraph", renderer: agg_renderer)

Using a secondary axis in LineGraph

import SwiftPlot
import AGGRenderer

let x:[Float] = [10,100,263,489]
let y:[Float] = [10,120,500,800]
let x1:[Float] = [100,200,361,672]
let y1:[Float] = [150,250,628,800]

var lineGraph = LineGraph<Float,Float>()
lineGraph.addSeries(x1, y1, label: "Plot 1", color: .lightBlue, axisType: .primaryAxis)
lineGraph.addSeries(x, y, label: "Plot 2", color: .orange, axisType: .secondaryAxis)
lineGraph.plotTitle = PlotTitle("SECONDARY AXIS")
lineGraph.plotLabel = PlotLabel(xLabel: "X-AXIS", yLabel: "Y-AXIS")
lineGraph.plotLineThickness = 3.0
lineGraph.drawGraphAndOutput(fileName: filePath+"agg/"+fileName, renderer: agg_renderer)

The series plotted on the secondary axis are drawn dashed.

Displaying plots in Jupyter Notebook

You can display plots in Jupyter Notebook using only the AGGRenderer. To do so, create the plots as shown in the above examples and instead of using the drawGraphAndOutput function from LineGraph, use the drawGraph function, then get a base64 encoded image from the AGGRenderer and pass it to the display function as showm below:

lineGraph.drawGraph(renderer: agg_renderer)
display(base64EncodedPNG: agg_renderer.base64Png())

How does this work

All the plotting code, utility functions, and necessary types are included in the SwiftPlot module. Each Renderer is implemented as a separate module. Each Renderer must have SwiftPlot as its dependency and must conform to the Renderer protocol defined in Renderer.swift in the SwiftPlot module. Each plot type is a generic that accepts data conforming to a protocol, FloatConvertible. At the moment FloatConvertible supports both Float and Double. The Renderer protocol defines all the necessary functions that a Renderer needs to implement. Each Plot must conform to the Plot protocol. At the moment this protocol defines the necessary variablse and functions that each Plot must implement in order to support SubPlots.

You can add series to the plots using their respective functions(addSeries for LineGraph). This is stored in as an array of Series objects. You can set other properties such as plotTitle, plotLabel, plotDimensions, etc. To actually generate the plot you need to call either the drawGraph or drawGraphAndOutput function. This calculates all the parameters necessary to generate the plots such as the coordinates of the border, scaled points to plot, etc. Then it sends over this information to the renderer which has functions to draw primitives like lines, rectangles and text.

In case the Renderer is in C++(here in the case of AGG), a C wrapper is written which is in turn wrapped in Swift.

In order to display the plots in Jupyter notebook, we encode the image(which is in the form of an RGB buffer) to a PNG image in memory and return the encoded image to the Swift code where it is stored as NSData. Then it is encoded to base64 and passed to the display function in swift-jupyter which finally displays the image.

Documentation

LineGraph<T: FloatConvertible, U: FloatConvertible>

Function Description
init(points: [Point], width: Float = 1000, height: Float = 660, enablePrimaryAxisGrid: Bool = false, enableSecondaryAxisGrid: Bool = false) Initialize a LineGraph with a set of points
init(width: Float = 1000, height: Float = 660, enablePrimaryAxisGrid: Bool = false,enableSecondaryAxisGrid: Bool = false) Initialize a LineGraph
addSeries(_ s: Series, axisType: Axis.Location = Axis.Location.primaryAxis) Add a series to the plot
addSeries(points p: [Point], label: String, color: Color = Color.lightBlue, axisType: Axis<T,U>.Location = Axis<T,U>.Location.primaryAxis) Add a series to the plot with a set of points, a label and a color for the series
addSeries(_ x: [Float], _ y: [Float], label: String, color: Color = Color.lightBlue, axisType: Axis<T,U>.Location = Axis<T,U>.Location.primaryAxis) Add a series to the plot with a set of x and y coordinates, a label and a color for the series
addSeries(_ y: [Float], label: String, color: Color = Color.lightBlue, axisType: Axis<T,U>.Location = Axis<T,U>.Location.primaryAxis) Add a series to the plot with only the y-coordinates. The x-coordinates are automatically enumerated [1, 2, 3, ...]
addFunction(_ function: (Float)->Float, minX: Float, maxX: Float, numberOfSamples: Int = 400, label: String, color: Color = Color.lightBlue, axisType: Axis.Location = Axis.Location.primaryAxis) Add a function to plot along with the range of x-coordinates over which to plot, number of samples of the function to take for plotting, a label, and color for the plot
drawGraphAndOutput(fileName name: String = "swift_plot_line_graph", renderer: Renderer) Generate the plot and save the resultant image
drawGraph(renderer: Renderer) Generate the plot in memory
drawGraphOutput(fileName name: String = "swift_plot_line_graph", renderer: Renderer) Save the generated plot to disk
Property
plotTitle: PlotTitle? = nil
plotLabel: PlotLabel? = nil
var plotDimensions: PlotDimensions
plotLineThickness: Float = 1.5
gridLineThickness: Float = 0.5
markerTextSize: Float = 12
gridColor: Color = .gray

BarChart<T: LosslessStringConvertible, U: FloatConvertible>

Function Description
init(width: Float = 1000, height: Float = 660, enableGrid: Bool = false) Initialize a BarChart
addSeries(_ s: Series<T,U>) Add a series to the plot .
addStackSeries(_ s: Series<T,U>) Add a stacked series to the plot
addStackSeries(_ x: [U], label: String, color: Color = .lightBlue, hatchPattern: BarGraphSeriesOptions.Hatching = .none) Add a stacked series to the plot
addSeries(values: [Pair<T,U>], label: String, color: Color = Color.lightBlue, hatchPattern: BarGraphSeriesOptions.Hatching = .none, graphOrientation: BarGraph.GraphOrientation = .vertical) Add a series to the plot using a Pair array
addSeries(_ x: [T], _ y: [U], label: String, color: Color = Color.lightBlue, hatchPattern: BarGraphSeriesOptions.Hatching = .none, graphOrientation: BarGraph.GraphOrientation = .vertical) Add a series to the plot using a Pair array
drawGraphAndOutput(fileName name: String = "swift_plot_bar_graph", renderer: Renderer) Generate the plot and save the resultant image
drawGraph(renderer: Renderer) Generate the plot in memory
drawGraphOutput(fileName name: String = "swift_plot_bar_graph", renderer: Renderer) Save the generated plot to disk
Property
plotTitle: PlotTitle? = nil
plotLabel: PlotLabel? = nil
var plotDimensions: PlotDimensions
space: Int = 20 (Sets the space between two bars)
gridLineThickness: Float = 0.5
markerTextSize: Float = 12
gridColor: Color = .gray

Histogram<T:FloatConvertible>

Function Description
init(width: Float = 1000, height: Float = 660, isNormalized: Bool = false, enableGrid: Bool = false) Initialize a Histogram
addSeries(_ s: HistogramSeries) Add a series to the plot.
addSeries(data: [T], bins: Int, label: String, color: Color = .lightBlue, histogramType: HistogramSeriesOptions.HistogramType = .bar) Add a series using an array.
addStackSeries(data: [T], label: String, color: Color = .lightBlue) Add a stacked series to the plot
drawGraphAndOutput(fileName name: String = "swift_plot_histogram", renderer: Renderer) Generate the plot and save the resultant image
drawGraph(renderer: Renderer) Generate the plot in memory
drawGraphOutput(fileName name: String = "swift_plot_histogram", renderer: Renderer) Save the generated plot to disk
Property
plotTitle: PlotTitle? = nil
plotLabel: PlotLabel? = nil
var plotDimensions: PlotDimensions
var strokeWidth: Float = 2
gridLineThickness: Float = 0.5
markerTextSize: Float = 12
gridColor: Color = .gray

ScatterPlot<T:FloatConvertible, U:FloatConvertible>

Function Description
init(width: Float = 1000, height: Float = 660, isNormalized: Bool = false, enableGrid: Bool = false) Initialize a ScatterPlot.
init(points p: [Pair<T,U>], width: Float = 1000, height: Float = 660, enableGrid: Bool = false) Initialize a ScatterPlot.
addSeries(_ s: Series<T,U>) Add a series to the plot.
addSeries(points: [Pair<T,U>], label: String, color: Color = .lightBlue, scatterPattern: ScatterPlotSeriesOptions.ScatterPattern = .circle) Add a series using an array of Pairs.
addSeries(_ x: [T], _ y: [U], label: String, color: Color = .lightBlue, scatterPattern: ScatterPlotSeriesOptions.ScatterPattern = .circle) Add a series using separate x and y arrays.
addSeries(_ x: [T], _ y: [U], label: String, startColor: Color = .lightBlue, endColor: Color = .lightBlue, scatterPattern: ScatterPlotSeriesOptions.ScatterPattern = .circle)) Add a series using separate x and y arrays and specify a start and end color for the scatter points.
addSeries(_ y: [U], label: String, color: Color = .lightBlue, scatterPattern: ScatterPlotSeriesOptions.ScatterPattern = .circle) Add a series using just the y array. It will be plotted against the index of the point.
addSeries(_ y: [U], label: String, startColor: Color = .lightBlue, endColor: Color = .lightBlue, scatterPattern: ScatterPlotSeriesOptions.ScatterPattern = .circle) Add a series using just the y array. It will be plotted against the index of the point. Also specify the start and end color for the scatter points.
drawGraphAndOutput(fileName name: String = "swift_plot_scatter_plot", renderer: Renderer) Generate the plot and save the resultant image
drawGraph(renderer: Renderer) Generate the plot in memory
drawGraphOutput(fileName name: String = "swift_plot_scatter_plot", renderer: Renderer) Save the generated plot to disk
Property
plotTitle: PlotTitle? = nil
plotLabel: PlotLabel? = nil
plotDimensions: PlotDimensions
scatterPatternSize: Float = 10
gridLineThickness: Float = 0.5
markerTextSize: Float = 12
gridColor: Color = .gray

SubPlot

enum stackPattern (to be passed in place of stackPattern in the initializer)
verticallyStacked
horizontallyStacked
gridStacked
Function Description
init(width: Float = 1000, height: Float = 660, numberOfPlots n: Int = 1, numberOfRows nR: Int = 1, numberOfColumns nC: Int = 1, stackPattern: Int = 0) Initialize a SubPlot
draw(plots: [Plot], renderer: Renderer, fileName: String = "subPlot_output") Generate plot with the plots passed in as Sub Plots and save the image to disk

PlotDimensions

Function Description
init(frameWidth : Float = 1000, frameHeight : Float = 660) Create a PlotDimensions variable with a frame width and height

Pair<T,U>

Property
x: T
y: U
Function Description
init(_ x: T, _ y: T) Create a Pair using x and y
typealias
Point = Pair<Float, Float>
Property
zeroPoint = Point(0.0, 0.0)

PlotLabel

Property
xLabel: String = "X-Axis"
yLabel: String = "Y-Axis"
labelSize: Float = 15
xLabelLocation = zeroPoint
yLabelLocation = zeroPoint

PlotTitle

Property
title : String = "TITLE"
titleSize : Float = 15
titleLocation = zeroPoint

Color

Function Description
init(_ r: Float, _ g: Float, _ b: Float, _ a: Float) Create a Color with r, g, b and a values. Each of them being between 0.0 and 1.0
Property(only on macOS and iOS)
cgColor: CGColor (return the corresponding CGColor)

PlotLabel

Property
xLabel: String = "X-Axis"
yLabel: String = "Y-Axis"
labelSize: Float = 15
xLabelLocation = zeroPoint
yLabelLocation = zeroPoint

Axis<T,U>

enum Location (to be passed into addSeries function in LineGraph)
primaryAxis
secondaryAxis

ScatterPlotSeriesOptions

enum ScatterPattern (to be passed into addSeries function in ScatterPlot)
circle
square
triangle
diamond
hexagon
pentagon
star

HistogramSeriesOptions

enum HistogramType: CaseIterable (to be passed into addSeries function in Histogram)
bar
step

BarGraphSeriesOptions

enum Hatching: Int, CaseIterable (to be passed into addSeries function in BarGraph)
none = 0
forwardSlash = 1
backwardSlash = 2
hollowCircle = 3
filledCircle = 4
vertical = 5
horizontal = 6
grid = 7
cross = 8

Base64Encoder

Function Description
encodeBase64PNG(pngBufferPointer: UnsafePointer, bufferSize: Int) -> String Encode a PNG image into base64 format.

Limitations

  • FloatConvertible supports only Float and Double. We plan to extend this to Int in the future.

Credits

  1. Maxim Shemanarev : The AGG library is directly used to render plots.
  2. Lode Vandevenne : The lodepng library is directly used to encode PNG images.
  3. The FreeType Project : AGG uses FreeType to draw text.
  4. Brad Larson and Marc Rasi for their invaluable guidance.
You can’t perform that action at this time.