SwiftCharts - Easy to use and highly customizable charts library for iOS

Overview

SwiftCharts

Version Carthage compatible License

Easy to use and highly customizable charts library for iOS

Features:

  • Bars - plain, stacked, grouped, horizontal, vertical
  • Scatter
  • Lines (straight/cubic/custom path generator)
  • Areas
  • Bubble
  • Multiple axes
  • Candlestick
  • Multiple labels per value (x axis)
  • Everything is customizable - colors, views, units, labels, animations, interactions, axes, etc.
  • Easy creation of arbitrary markers, overlays, info views, etc., using simple UIViews!
  • Modular architecture, which allows to easily create new chart types or add effects to existing types externally (without library changes).
  • Charts can be combined with each other.
  • Pie chart*
  • Legends*
  • Zooming & panning, lockable to x/y axis, max delta or both. Elastic effect. (unreleased)
  • Extensible axis values and label generators for numbers, dates, etc, with customizable zooming handling (nice numbers, divide in half, etc). (unreleased).

*These are separate repos for better focus and reusability.

iOS 7+

Video

Documentation

ScreenShot ScreenShot ScreenShot ScreenShot of Multi-chart touch tracking

ScreenShot

ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot ScreenShot

Installation

CocoaPods

Add to your Podfile:

use_frameworks!
pod 'SwiftCharts', '~> 0.6.5'

To use master directly:

pod 'SwiftCharts', :git => 'https://github.com/i-schuetz/SwiftCharts.git'

And then:

pod install

Import the framework in your code:

import SwiftCharts

Carthage

Add to your Cartfile:

0.6.5 ">
github "i-schuetz/SwiftCharts" ~> 0.6.5

Contribute

Contributions are highly appreciated! To submit one:

  1. Fork
  2. Commit changes to a branch in your fork
  3. Push your code and make a pull request

Quick start

Multiline chart:

let chartConfig = ChartConfigXY(
    xAxisConfig: ChartAxisConfig(from: 2, to: 14, by: 2),
    yAxisConfig: ChartAxisConfig(from: 0, to: 14, by: 2)
)

let frame = CGRect(x: 0, y: 70, width: 300, height: 500)

let chart = LineChart(
    frame: frame,
    chartConfig: chartConfig,
    xTitle: "X axis",
    yTitle: "Y axis",
    lines: [
        (chartPoints: [(2.0, 10.6), (4.2, 5.1), (7.3, 3.0), (8.1, 5.5), (14.0, 8.0)], color: UIColor.red),
        (chartPoints: [(2.0, 2.6), (4.2, 4.1), (7.3, 1.0), (8.1, 11.5), (14.0, 3.0)], color: UIColor.blue)
    ]
)

self.view.addSubview(chart.view)

Bars chart:

let chartConfig = BarsChartConfig(
    valsAxisConfig: ChartAxisConfig(from: 0, to: 8, by: 2)
)

let frame = CGRect(x: 0, y: 70, width: 300, height: 500)
        
let chart = BarsChart(
    frame: frame,
    chartConfig: chartConfig,
    xTitle: "X axis",
    yTitle: "Y axis",
    bars: [
        ("A", 2),
        ("B", 4.5),
        ("C", 3),
        ("D", 5.4),
        ("E", 6.8),
        ("F", 0.5)
    ],
    color: UIColor.red,
    barWidth: 20
)

self.view.addSubview(chart.view)
self.chart = chart

Concept:

  • Layer architecture, which makes it extremely easy to customize charts, create new types, combine existing ones and add interactive elements.

  • Creation of views via a generator function, which makes it easy to use custom views in any layer.

Main Components:

1. Layers:

A chart is the result of composing layers together. Everything is a layer - axis, guidelines, dividers, line, circles, etc. The idea is to have losely coupled components that can be easily changed and combined. This is for example the structure of a basic chart, which shows a line with circles:

ScreenShot

Following a more low level example, to provide an insight into the layer system. Note that most examples are written like this, in order to provider maximal flexibility.

UIView? in let viewSize: CGFloat = Env.iPad ? 30 : 20 let center = chartPointModel.screenLoc let label = UILabel(frame: CGRect(x: center.x - viewSize / 2, y: center.y - viewSize / 2, width: viewSize, height: viewSize)) label.backgroundColor = UIColor.green label.textAlignment = NSTextAlignment.center label.text = chartPointModel.chartPoint.y.description label.font = ExamplesDefaults.labelFont return label } // create layer that uses viewGenerator to display chartpoints let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: viewGenerator, mode: .translate) // create chart instance with frame and layers let chart = Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, chartPointsLayer ] ) view.addSubview(chart.view) self.chart = chart ">
let chartPoints: [ChartPoint] = [(2, 2), (4, 4), (6, 6), (8, 8), (8, 10), (15, 15)].map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))}

let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)

let generator = ChartAxisGeneratorMultiplier(2)
let labelsGenerator = ChartAxisLabelsGeneratorFunc {scalar in
    return ChartAxisLabel(text: "\(scalar)", settings: labelSettings)
}

let xGenerator = ChartAxisGeneratorMultiplier(2)

let xModel = ChartAxisModel(firstModelValue: 0, lastModelValue: 16, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings)], axisValuesGenerator: xGenerator, labelsGenerator: labelsGenerator)

let yModel = ChartAxisModel(firstModelValue: 0, lastModelValue: 16, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())], axisValuesGenerator: generator, labelsGenerator: labelsGenerator)

let chartFrame = ExamplesDefaults.chartFrame(view.bounds)

let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom

// generate axes layers and calculate chart inner frame, based on the axis models
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame)

// create layer with guidelines
let guidelinesLayerSettings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: guidelinesLayerSettings)

// view generator - this is a function that creates a view for each chartpoint
let viewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsViewsLayer, chart: Chart) -> UIView? in
    let viewSize: CGFloat = Env.iPad ? 30 : 20
    let center = chartPointModel.screenLoc
    let label = UILabel(frame: CGRect(x: center.x - viewSize / 2, y: center.y - viewSize / 2, width: viewSize, height: viewSize))
    label.backgroundColor = UIColor.green
    label.textAlignment = NSTextAlignment.center
    label.text = chartPointModel.chartPoint.y.description
    label.font = ExamplesDefaults.labelFont
    return label
}

// create layer that uses viewGenerator to display chartpoints
let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: viewGenerator, mode: .translate)

// create chart instance with frame and layers
let chart = Chart(
    frame: chartFrame,
    innerFrame: innerFrame,
    settings: chartSettings,
    layers: [
        xAxisLayer,
        yAxisLayer,
        guidelinesLayer,
        chartPointsLayer
    ]
)

view.addSubview(chart.view)
self.chart = chart

Layers decide how to present their data - this can be done adding subviews, (CA)layers, with core graphics, etc.

2. View generators:

View based layers will use a generator function to generate chart point views. This function receives the complete state of each chartpoint (model data, screen location) and produces an UIView, allowing any type of customization.

Hello world:

There's a hello world included in the examples, similar to the above code, with a bit more explanations. Change some properties of the generated views, copy paste the chartPointsLineLayer used in the snippet above, and pass it to the chart's layers, to display a line behind the views, and you have already mastered the main concepts!

Important!

  • Don't forget to always keep a strong reference to the chart instance or it will be released, which leads to axis & labels not showing.

  • If you have a lot of axis labels in your chart it may be necessary to do the calculation of the coordinate space in the background, to avoid possible delays which are noticeable during transitions or scrolling. See ScrollExample or MultipleAxesExample example for this.

Tasks

SwiftCharts has got now some projects to plan features and improvements. Feel free to grab any of these topics even if it's just to add feedback. You can open an issue for this. Other options like opening a Slack channel are possible.

Created By:

Ivan Schütz

If you need something special or are just short of time, I'm also available for hire

Credits:

A big thank you to the awesome grafiti.io for having been sponsoring this project in the last months, and of course also to all the contributors!

License

SwiftCharts is Copyright (c) 2015 - 2019 Ivan Schütz and released as open source under the attached Apache 2.0 license.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

This is a port to Swift and (massively improved) continuation of an obj-c project which I did while working at eGym GmbH https://github.com/egymgmbh/ios-charts

Comments
  • Scaling the chart based on number of X Values to display

    Scaling the chart based on number of X Values to display

    Hi,

    Is there a way to scale the data on the graph so that a given number of pieces of data can be seen?

    I have many data points and I am basing my project off of the scrollable example and want to set how many pieces of data can be seen at once.

    Currently only 3 can be seen and i want to make the bars thinner and gaps smaller to fit more data on.

    img_1446

    I want to always be able to see 7 pieces of data at once and then need to scroll to see more

    Thanks

    question 
    opened by Trever123 17
  • Cubic Area Lines with String Data

    Cubic Area Lines with String Data

    |s it possible to get cubic lines with string data rather than integers? I've got data such as; var lineTest: [(title: String, val: Double)]! = [] where title could be something like "31/3" and double could be 27.7

    The Area lines work, but I am just wondering if it is possible to make them cubic lines or cubic areas? Also, Since it is in a scroll view, is it possible for it to cut off at the first and last values, rather than drop down to 0.

    untitled 2

    help wanted 
    opened by dhruveonmars 17
  • How to change the line width of the Axis?

    How to change the line width of the Axis?

    Hi, is it possible to change the width of the graph axis? I can change the line width in the graph, but not the axis. Like to have something thicker on iPad. Thanks...

    help wanted 
    opened by christinalau 16
  • Error 'No such module SwiftCharts' in Xcode 8.0

    Error 'No such module SwiftCharts' in Xcode 8.0

    Hi, I am using Swift 3.0 and Xcode 8.0. I am getting the compilation error ' No such module SwiftCharts'. Here is my pod file.

    platform :ios, '8.0'

    target 'xxxxx' do

    Comment this line if you're not using Swift and don't want to use dynamic frameworks

    use_frameworks! pod 'SwiftCharts', :git => 'https://github.com/i-schuetz/SwiftCharts.git', :branch => 'master'

    end

    Please help.

    Rafeeq

    help wanted 
    opened by mobyforce 15
  • Issues with Bar Chart View: scaling, gradient layer, thinner bar chart, hide Y axis grid only

    Issues with Bar Chart View: scaling, gradient layer, thinner bar chart, hide Y axis grid only

    Hi Ivan and all,

    Thanks for making such a handy library – it's very neat. I have been wrapping my head around it to recreate the following design:

    touched

    Here's what I have so far:

    simulator screen shot 27 jun 2017 20 20 35

    I can't figure out four things:

    1. The first bar ("Jan") is thinner than the other ones. Perhaps it's been clipped out by the axis or something?

    2. I can't figure out a way to scale the Y axis when the graph is instantiated. I always need to pinch down to reach y = 0. Is there a way to start from 0, 0? I am currently using this code:

    chart?.zoom(scaleX: 2.4, scaleY: 5, anchorX: 0, anchorY: 0)

    1. I don't know why adding a gradient layer to the view bar layer doesn't actually add anything, even if the background color is set to .clear.

    `let viewBar = ChartPointViewBar(p1: p1, p2: p2, width: barWidth, bgColor: #colorLiteral(red: 0.1725490196, green: 0.6509803922, blue: 1, alpha: 1), settings: settings) print("viewBar frame", viewBar.frame)

    let mGradient = CAGradientLayer()
    mGradient.frame = viewBar.bounds
    var colors = [CGColor]()
    colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor)
    colors.append(UIColor(red: 0, green: 0, blue: 0, alpha: 0).cgColor)
    
    mGradient.startPoint = CGPoint(x: 0.1, y: 0.5)
    mGradient.endPoint = CGPoint(x: 0.9, y: 0.5)
    mGradient.colors = colors
    
    viewBar.layer.addSublayer(mGradient)
    
    1. I can't figure out how to hide the X axis grid? Haven't found a way to only hide one of them (not both).

    Here's a gist of my view controller:

    https://gist.github.com/CeceXX/349d272702be85b7c26fba308c0a6574

    Would love some help on this. Thank you!

    help wanted 
    opened by csr 14
  • App-Extension-Safe version of SwiftCharts

    App-Extension-Safe version of SwiftCharts

    Hey guys. We use SwiftCharts in Loop and it's awesome. Recently I've been trying to embed SwiftCharts into an app extension so that I can show the chart on the lock screen.

    This results in the following warning: warning: linking against dylib not safe for use in application extensions

    Can you produce an App Extension Safe version of SwiftCharts that we can use this way? I don't have a sense for why this might be difficult, so if it's a challenge - would love to explore and understand more. thanks!

    Relevant docs: https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionOverview.html#//apple_ref/doc/uid/TP40014214-CH2-SW6

    bug 
    opened by bharat 13
  • how to put stack bar in library into a subview

    how to put stack bar in library into a subview

    I use pod install to load library, then copy code of StackedBarsExample.swift to paste in ViewContoller. And I copy code of ExamplesDefaults.swift and Env.swift to paste in my Xcode project. It can be run.

    Objective: I want to put this stack bar into a subview in ViewController. This name of this subview is subviewForGraph. I don't know how to put stack bar into this subview(subviewForGraph).

    subviewForGraph is a view that I drag from right-bottom window in Xcode.

    help wanted 
    opened by ElaneirzGard 12
  • trouble with landscape mode

    trouble with landscape mode

    Hello there. I am having some trouble with landscape mode when using a line chart. i have designed the view in landscape mode with the storyboard and programmatically force it to stay. I disabled the auto-rotate for just this view.

    However, the graph is not filling the space properly.

    screen shot 2016-03-01 at 9 41 19 am screen shot 2016-03-01 at 9 41 35 am

    help wanted 
    opened by shawn-kb 12
  • Tutorial does not consider auto-layout

    Tutorial does not consider auto-layout

    Very nice and useful tutorials, I'm trying to learn using your library with them. However I cannot get how to use auto layout. Is there a simple way to solve this not programmatically? Thanks

    question 
    opened by sniis84 12
  • #304: Implemented gradient fill for curved areas

    #304: Implemented gradient fill for curved areas

    • Implements gradient fill for curved areas
    • Code could be improved imho - open to any suggestions
    • Tested with CatmullPathGenerator, CubicPathGenerator and StraightLinePathGenerator
    • Tested with one or multiple colors
    opened by dehlen 11
  • Documentation is nonexistent

    Documentation is nonexistent

    How soon is "coming soon" for the documentation? Just in line comments in the examples would help. Having a terrible time getting the views sized correctly. In the examples you're moving the view down by 70px why? Using almost identical code my bar chart is squished into about 100px height. Its hard to figure out why without some documentation

    enhancement help wanted 
    opened by opswhisperer 11
  • ChartPointsBubbleLayer not draws properly

    ChartPointsBubbleLayer not draws properly

    If you run the BubbleExample, I assume changing the useViewsLayer flag should provide the same results, yet its not.

    Simulator Screen Shot - iPhone 13 Pro Max - 2022-05-27 at 11 49 03

    I also having similar issues when tried to implement it with my own example data: IMG_5789 As you can see, the line chart got properly rendered with similar data and similar SwiftChart setup methods.

    opened by laszlotuss 1
  • build swiftcharts headers first

    build swiftcharts headers first

    Context For this change: When LoopKit/Loop is built as workspace ( see https://github.com/LoopKit/LoopWorkspace) with xcode 13.3+build order set to "automatic" rather than "manual" we get a cycle problem related to swiftcharts (which is a dependency to Loop). This fixes that problem by building the headers first

    Let me know if I need to undo the xcscheme changes before merging. (Those edits were automatically created by xcode)

    Link to discussion of this issue: https://loop.zulipchat.com/#narrow/stream/209438-Build-Issues/topic/Dev.20Workspace.20Build.20Issue.20with.20new.20SPM.20package/near/275352863

    opened by dabear 1
  • SPM not working properly due to missing TAG

    SPM not working properly due to missing TAG

    It looks like the SPM support was added without incrementing the last version tag, meaning, Xcode can't find a proper tag while trying to add SwiftCharts as SPM. could you please add a new version tag? thanks in advance Arie

    opened by Gutty1 1
  • Problem building on new MacBook

    Problem building on new MacBook

    Hi, I just got my new MacBook Air yesterday. Unfortunately there seem to be some issues when building an old project in XCode.

    I get a bunch of these errors:

    'ChartAxisValue' is ambiguous for type lookup in this context
    Invalid redeclaration of 'ChartAxisValueDouble'
    

    Has anyone successfully gotten around this?

    I have tried with Rosetta, it is possible to compile, but then the Storyboard does not work and so on. So not an ideal solution.

    I have installed pods with both pod install and arch x86_64 pod install

    opened by bylowerik 0
  • Axis Labels not showing up

    Axis Labels not showing up

    I have run through the documentation and have copy and pasted the examples into my project and the labels and axis layer overall isn't showing up, the lines and points still are however, which doesn't make any sense to me.

    opened by dNienberg 2
Owner
Ivan Schütz
Ivan Schütz
Easy to use and highly customizable pie charts library for iOS

PieCharts Easy to use and highly customizable pie charts library for iOS Swift 4.2, iOS 8+ Video Features: Customizable slices Add overlays using simp

null 503 Dec 6, 2022
FLCharts: Easy to use and highly customizable charts library for iOS

FLCharts Requirements Xcode 11 / Swift 5 iOS >= 11.0 Installation FLCharts is av

Francesco Leoni 250 Dec 26, 2022
Easy to use and highly customizable pie charts library for iOS

PieCharts Easy to use and highly customizable pie charts library for iOS Swift 4.2, iOS 8+ Video Features: Customizable slices Add overlays using simp

null 503 Dec 6, 2022
An overview of the different types of charts you can make with Swift Charts

Swift Charts Examples This repo aims to provide sample code for lots of different chart types for you to use as inspiration for your own projects. We

Jordi Bruin 1.2k Dec 30, 2022
A powerful 🚀 Android chart view / graph view library, supporting line- bar- pie- radar- bubble- and candlestick charts as well as scaling, panning and animations.

⚡ A powerful & easy to use chart library for Android ⚡ Charts is the iOS version of this library Table of Contents Quick Start Gradle Maven Documentat

Philipp Jahoda 36k Jan 5, 2023
Core Charts | Basic Scrollable Chart Library for iOS

Core Charts | Basic Chart Library for iOS HCoreBarChart VCoreBarChart Requirements Installation Usage Appearance Customization Getting Started You nee

Çağrı ÇOLAK 71 Nov 17, 2022
SwiftUICharts - A charts / plotting library for SwiftUI.

A charts / plotting library for SwiftUI. Works on macOS, iOS, watchOS, and tvOS and has accessibility features built in.

Will Dale 632 Jan 3, 2023
Using Swift Charts and Voiceover Chart Descriptor to compose music. 🤯

Chart de lune ?? Using Swift Charts and Voiceover Chart Descriptor to compose music. ?? Image source: https://hadikarimi.com/portfolio/claude-debussy-

An Trinh 31 Nov 21, 2022
Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

One more heads up: As Swift evolves, if you are not using the latest Swift compiler, you shouldn't check out the master branch. Instead, you should go to the release page and pick up whatever suits you.

Daniel Cohen Gindi 26.3k Jan 3, 2023
🎉 SwiftUI stock charts for iOS

SwiftUI Stock Charts Display interactive stock charts easily ?? Instalation In Xcode go to File -> Swift packages -> Add package dependency Copy and p

Dennis Concepción Martín 94 Dec 26, 2022
🎉 SwiftUI stock charts for iOS

?? SwiftUI stock charts for iOS

Dennis Concepción Martín 94 Dec 26, 2022
An iOS wrapper for ChartJS. Easily build animated charts by leveraging the power of native Obj-C code.

TWRCharts TWRCharts An Obj-C wrapper for ChartJS. Easily build animated charts by leveraging the power of native code. TWRCharts is yet another charti

Michelangelo Chasseur 363 Nov 28, 2022
Light weight charts view generater for iOS. Written in Swift.

# ###Light weight charts view generater for iOS. Written in Swift. Requirements iOS 8.0+ XCode 7.3+ Installation CocoaPods $ pod init specify it in yo

Recruit Holdings. Media Technology Lab 982 Nov 16, 2022
Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

Version 4.0.0, synced to MPAndroidChart #f6a398b Just a heads up: Charts 3.0 has some breaking changes. Please read the release/migration notes. Anoth

Daniel Cohen Gindi 26.3k Jan 8, 2023
Aplikasi iOS kasus Covid-19 di U.S dengan Storyboard, Framework Charts dari danielgindi, dan API dari covidtracking.com

Aplikasi iOS kasus Covid-19 di U.S dengan Storyboard, Framework Charts dari danielgindi, dan API dari covidtracking.com

DK 7 Aug 1, 2022
This is pie chart that is very easy to use and customizable design.

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

iOSCS 40 Nov 29, 2022
SwiftUI Charts with custom styles

SwiftUI Charts Build custom charts with SwiftUI Styles Line Chart(data: [0.1, 0.3, 0.2, 0.5, 0.4, 0.9, 0.1]) .chartStyle( LineChartStyle(.

SpaceNation 609 Jan 6, 2023
Health Sample app using Swift, RxSwift, Anchorage, Charts

HealthSample First run pod install, then build the project and run in your devices or simulators. This project has used RIBs, Swift, RxSwift, Anchorag

null 4 Feb 11, 2022