SwiftUIGraphs (v1.1.2)
SwiftUIGraphs is a Swift package for iOS, iPadOS (14.0 and later) as well as MacOS (11.0 and later). It features a line chart, bar chart and pie chart for data visualization and has many customization options.
Feature Overview
- NEW: from v1.1 SwiftUIGraphs supports MacOS (from v11) natively - in the included example project , simply select the macOS target and try it out!
- From v1.0 DYLineChartView and DYBarChartView support muliple data series by default (multi-line charts and stacked bar charts).
- Create an interactive line chart with a moving data selector point. The package also allows setting separate data point colors and line section colors.
- Create an area chart by adding a gradient area below the line chart.
- Create a stacked bar chart with positive and negative fraction values
- line and bar charts feature cool appear animations
- Create a pie chart or doughnut chart with customizable colors and a cool pop out effect to present a detail pie chart.
- The chart views feature separate header / info / legend views that can be replaced by custom solutions easily.
- Add drop shadows to the line chart, gradient, bars and selected pie slice.
- Many more features - check out details below.
The folder SwiftUIGraphsExample contains an example project, make sure to check it out for more implementation details. All public structs / classes include in-code-documentation.
Installation
Installation through the Swift Package Manager (SPM) is recommended.
SPM:
Select your project (not the target) and then select the Swift Packages tab. Clicking + and typing SwiftUIGraphs should find the package on github. Otherwise copy and paste the URL of this repo.
Check out the version history below for the current version.
Make sure to import SwiftUIGraphs in every file where you use SwiftUIGraphs.
import SwiftUIGraphs
Usage
Check out the following examples. This repo also contains an example project to illustrate how to implement all three chart types. Check the in-code documentation for more details.
Line Charts
DYLineChartView supports the following modifiers:
- background(gradient...)
- selectorLine
- markerGridLine
- userInteraction
- showXAxis
- xAxisViewHeight
- xAxisGridLines
- xAxisLabelStringValue
- xAxisLabelFont(_ font: UIFont)
- xAxisScalerOverride
- showYaxis
- yAxisPosition
- yAxisViewWidth
- yAxisGridLines
- yAxisLabelStringValue
- yAxisLabelFont(_ font: UIFont)
- yAxisScalerOverride
Pass in one or several DYLineViews into DYLineChartView's lineViews closure. You can attach the following modifiers to DYLineView:
- lineStyle
- animation
- userInteraction
- area
- selectedPointIndicatorLineStyle
- colorPerLineSegment
Code Example: Multi-line chart
struct MultiLineChartExample: View {
let colors: [Color] = [.blue, .orange, .green]
@State private var dataPointArrays: Array<[DYDataPoint]> = []
@State private var blueSelectedDataPoint: DYDataPoint?
@State private var orangeSelectedDataPoint: DYDataPoint?
@State private var greenSelectedDataPoint: DYDataPoint?
var body: some View {
GeometryReader { proxy in
VStack {
DYLineChartView(allDataPoints: Array(self.dataPointArrays.joined()), lineViews: { parentProps in
let selectedPoints = [$blueSelectedDataPoint, $orangeSelectedDataPoint, $greenSelectedDataPoint]
ForEach(0..<dataPointArrays.count, id:\.self) { i in
DYLineView(dataPoints: dataPointArrays[i], selectedDataPoint: selectedPoints[i], pointView: { _ in
self.pointViewFor(index: i)
}, selectorView: self.selectorPointViewFor(index: i), parentViewProperties: parentProps)
.lineStyle(color: colors[i])
.selectedPointIndicatorLineStyle(xLineColor: colors[i], yLineColor: colors[i])
}
})
.markerGridLine(coordinate: 0, color: .red)
.yAxisLabelFontSize(UIDevice.current.userInterfaceIdiom == .phone ? 8 : 10)
.yAxisLabelStringValue({ yValue in
self.stringified(value:yValue)
})
.xAxisLabelFontSize(UIDevice.current.userInterfaceIdiom == .phone ? 8 : 10)
.xAxisLabelStringValue({ xValue in
self.stringified(value: xValue)
})
.frame(height: self.chartHeight(proxy: proxy))
.padding()
self.legendView.padding()
Spacer()
}
}.navigationTitle("Some Random Data Sets")
.onAppear {
generateDataPoints()
}
}
func chartHeight(proxy: GeometryProxy)->CGFloat {
return proxy.size.height > proxy.size.width ? proxy.size.height * 0.4 : proxy.size.height * 0.75
}
var legendView: some View {
return HStack(spacing:15) {
let selectedPoints = [blueSelectedDataPoint, orangeSelectedDataPoint, greenSelectedDataPoint]
ForEach(0..<selectedPoints.count, id:\.self) { i in
if let dataPoint = selectedPoints[i] {
HStack {
self.pointViewFor(index: i)
Text("X: \(self.stringified(value: dataPoint.xValue))")
Text("Y: \(self.stringified(value: dataPoint.yValue))")
}.font(UIDevice.current.userInterfaceIdiom == .pad ? .body : .caption)
}
}
Spacer()
}
}
func stringified(value: Double)->String {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
return formatter.string(for: value)!
}
func generateDataPoints() {
var dataPointArrays: Array<[DYDataPoint]> = []
for _ in 0..<3 {
var dataPoints: [DYDataPoint] = []
var xValue = Double.random(in: 1...1.5)
for _ in 0..<12 {
let yValue = Double.random(in: -10...40)
let dataPoint = DYDataPoint(xValue: xValue, yValue: yValue)
dataPoints.append(dataPoint)
xValue += Double.random(in: 0.5...1)
}
dataPointArrays.append(dataPoints)
}
self.dataPointArrays = dataPointArrays
}
func pointViewFor(index: Int)-> some View {
Group {
switch index {
case 0:
DYLinePointView(borderColor: colors[index])
case 1:
DYLinePointView(shape: Rectangle(), borderColor: colors[index], edgeLength: 10)
default:
DYLinePointView(shape: Triangle(), borderColor: colors[index])
}
}
}
func selectorPointViewFor(index: Int)-> some View {
Group {
switch index {
case 0:
DYSelectorPointView()
case 1:
DYSelectorPointView(shape: Rectangle(), shapeSize: 12, shapeHaloSize: 24)
default:
DYSelectorPointView(shape: Triangle(), haloOffset: CGSize(width: 0, height: -14 / 6))
}
}
}
}
Other examples
Check out the example project for details (included in the package).
In order to try out the stock price example, you need to sign up with https://iexcloud.io for free to get an authentication token.
Area Chart with different color per line segment example:
Additionally, you can add a drop shadow underneath the gradient (and / or the line):
Bar Charts
DYBarChartView supports multiple data series from version 1.0. Each bar is represented by a DYBarDataSet - check out the example below for details.
DYBarChartView supports the following modifiers:
- background(gradient: LinearGradient)
- userInteraction(enabled: Bool = true)
- animation(_ showAppearAnimation: Bool)
- barDropShadow(_ shadow: Shadow)
- labelViewOffset( _ offset: CGSize)
- selectedBar(borderColor: Color, dropShadow: Shadow? = nil)
- barLabelMinimumEdgeMargin(top: CGFloat = 0, bottom: CGFloat = 10)
- showXaxis(_ show: Bool)
- xAxisViewHeight(_ height: CGFloat)
- xAxisLabelFont(_ font: UIFont)
- showYaxis(_ show: Bool)
- yAxisPosition(_ position: Edge.Set)
- yAxisViewWidth(_ height: CGFloat)
- yAxisLabelStringValue(_ stringValue: @escaping (Double)->String)
- yAxisLabelFont(_ font: UIFont)
- yAxisGridLines(showGridLines: Bool = true, gridLineColor: Color = Color.secondary.opacity(0.5), gridLineStrokeStyle: StrokeStyle = StrokeStyle(lineWidth: 1, dash: [3]))
- markerGridLine(yCoordinate: Double, color: Color, strokeStyle: StrokeStyle = StrokeStyle(lineWidth: 1, dash: [3]))
- yAxisScalerOverride(minMax: (min:Double?, max:Double?)? = nil, interval: Double? = nil, maxTicks: Int = 10)
Code Example: Stacked Bar Chart
struct MultiBarChartExample: View {
let colors: [Color] = [.blue, .orange, .green]
let titles = ["Energy", "Pharmaceutical", "Agriculture"]
@State var barDataSets: [DYBarDataSet] = []
@State var selectedBarDataSet: DYBarDataSet?
var body: some View {
GeometryReader { proxy in
VStack {
DYBarChartView(barDataSets: barDataSets, selectedBarDataSet: $selectedBarDataSet)
.barDropShadow(Shadow(color: .gray, radius:8, x:-4, y:-3))
.selectedBar(borderColor: .purple, dropShadow: Shadow(color: .black.opacity(0.7), radius:10, x:-7, y:-5))
.yAxisLabelFontSize(UIDevice.current.userInterfaceIdiom == .phone ? 8 : 10)
.markerGridLine(yCoordinate: 0, color: .red)
.xAxisLabelFontSize(UIDevice.current.userInterfaceIdiom == .phone ? 8 : 10)
.frame(height:chartHeight(proxy: proxy))
if self.barDataSets.isEmpty == false {
HStack {
self.selectedDataSetDetailView()
Spacer()
}
}
Spacer()
}.padding()
}.navigationTitle("Profits & Losses Mio. USD per Division per Year")
.onAppear {
self.generateExampleData()
}
}
func chartHeight(proxy: GeometryProxy)->CGFloat {
return proxy.size.height > proxy.size.width ? proxy.size.height * 0.4 : proxy.size.height * 0.65
}
func selectedDataSetDetailView()->some View {
Group {
if let barDataSet = selectedBarDataSet {
VStack(alignment: .leading) {
Text(barDataSet.xAxisLabel).font(.callout).bold()
HStack {
if barDataSet.netValue >= 0 {
Text("Net Profit:")
} else {
Text("Net Loss:").foregroundColor(.red).bold()
}
Text(abs(barDataSet.netValue).toCurrencyString(maxDigits:1) + " million").foregroundColor(barDataSet.netValue >= 0 ? .primary : .red)
Spacer()
}
VStack(spacing: 0) {
ForEach(0..<barDataSet.fractions.count, id:\.self) { i in
let fraction = barDataSet.fractions[i]
HStack(spacing: 0) {
HStack {
Rectangle().fill(colors[i]).frame(width: 15, height: 15)
Text(fraction.title + ": ")
Spacer()
}
Text(fraction.value.toCurrencyString(maxDigits:1) + " million").foregroundColor(fraction.value >= 0 ? .primary : .red)
Spacer()
}.font(.callout)
}
}.transition(AnyTransition.opacity)
}.frame(maxWidth: 300).padding()
}
}
}
func generateExampleData() {
var barDataSets: [DYBarDataSet] = []
var currentYear = 2012
for _ in 0..<10 {
let firstValue = Double.random(in: -10 ..< 50)
let secondValue = Double.random(in: -20 ..< 40)
let thirdValue = Double.random(in: -30 ..< 30)
let values = [firstValue, secondValue, thirdValue]
let xValueLabel = "\(currentYear)"
var fractions: [DYBarDataFraction] = []
for i in 0..<values.count {
let fraction = DYBarDataFraction(value: values[i], title:titles[i], gradient: LinearGradient(colors: [colors[i]], startPoint: .top, endPoint: .bottom)) {
Text(values[i].toDecimalString(maxFractionDigits: 1)).font(.footnote).lineLimit(1).foregroundColor(.white).eraseToAnyView()
}
fractions.append(fraction)
}
let dataSet = DYBarDataSet(fractions: fractions, xAxisLabel: xValueLabel, labelView: { value in
let text = value != 0 ? value.toDecimalString(maxFractionDigits: 1) : ""
return Text(text).font(.footnote).eraseToAnyView()
})
barDataSets.append(dataSet)
currentYear += 1
}
self.barDataSets = barDataSets
}
}
Simple bar chart example: