Easy to use and highly customizable pie charts library for iOS

Overview

PieCharts

Version Carthage compatible License

Easy to use and highly customizable pie charts library for iOS

Swift 4.2, iOS 8+

Video

ScreenShotScreenShot

Features:

  • Customizable slices
  • Add overlays using simple UIViews
  • Interactive
  • Animated
  • Dynamic slice insertion
  • Reusable components via extensible layer system
  • Configurable in interface builder
  • Legends. This is in a separate project to keep things focused and reusable.

Installation

CocoaPods

Add to your Podfile:

use_frameworks!
pod 'PieCharts'

Carthage

Add to your Cartfile:

github "i-schuetz/PieCharts"

Usage

Basic chart:

@IBOutlet weak var chartView: PieChart!

chartView.models = [
    PieSliceModel(value: 2.1, color: UIColor.yellow),
    PieSliceModel(value: 3, color: UIColor.blue),
    PieSliceModel(value: 1, color: UIColor.green)
]

Configurable in interface builder, with live update of the view:

ScreenShot

Overlays:

Overlays are implemented using layers. There are several built in layers and you also can implement your own ones.

To add text e.g. text labels inside the slices + text with lines outside, simply:

chartView.layers = [PiePlainTextLayer(), PieLineTextLayer()]

Each layer has its own customization options. For example, here we customize the plain labels layer:

let textLayerSettings = PiePlainTextLayerSettings()
textLayerSettings.viewRadius = 55
textLayerSettings.hideOnOverflow = true
textLayerSettings.label.font = UIFont.systemFont(ofSize: 8)

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
textLayerSettings.label.textGenerator = {slice in
    return formatter.string(from: slice.data.percentage * 100 as NSNumber).map{"\($0)%"} ?? ""
}

let textLayer = PiePlainTextLayer()
textLayer.animator = AlphaPieViewLayerAnimator()
textLayer.settings = textLayerSettings

This is the custom views layer, which makes possible to create custom views:

let viewLayer = PieCustomViewsLayer()

let settings = PieCustomViewsLayerSettings()
settings.viewRadius = 135
settings.hideOnOverflow = false
viewLayer.settings = settings

viewLayer.viewGenerator = {slice, center in
    let myView = UIView()
    // add images, animations, etc.
    return myView
}

Interactivity, events:

Conform to PieChartDelegate to react to interaction and other events:

func onGenerateSlice(slice: PieSlice)
func onStartAnimation(slice: PieSlice)
func onEndAnimation(slice: PieSlice)
func onSelected(slice: PieSlice, selected: Bool)

Dynamic slice insertion:

chartView.insertSlice(index: 1, model: PieSliceModel(value: 5, color: UIColor.blue))

Contributing

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

Outlook

The layer system can be abstracted a step further in order to make the slices themselves be in a layer. This way we can combine multiple slice-layers to create more complex types of pie charts.

Credits

The food images used in the demo are from freepik.com, and flaticon.com/authors/madebyoliver

Created By:

Ivan Schütz

License

SwiftCharts is Copyright (c) 2017 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.

Comments
  • Support NSAttributedString on label of pie chart

    Support NSAttributedString on label of pie chart

    I want to using label with attributed string with name (issue #8). So, the following tasks were carried out :

    1. add 'name' property on PieSliceModel to identify as text
    2. support NSAttributedString to use label better without modifying labelGenerator on PieChartLabelSettings.swift

    you can create slice model as: PieSliceModel(value: 2, color: colors[2]) // previous or PieSliceModel(name: "fff", value: 2, color: colors[0]) // this time

    and you can use attributedText as:

        let categoryAttr = [
            NSFontAttributeName: UIFont.systemFont(ofSize: 8, weight: UIFontWeightLight),
            NSForegroundColorAttributeName: UIColor.blue
        ]
    
        let percentageAttr = [
            NSFontAttributeName: UIFont.systemFont(ofSize: 8),
            NSForegroundColorAttributeName: UIColor.black
        ]
    
        textLayerSettings.label.type = .attributed
        textLayerSettings.label.attributedTextGenerator = {slice in
            let categoryString = NSMutableAttributedString(string: slice.data.model.name ?? "", attributes: categoryAttr)
            let percentageString = NSMutableAttributedString(string:
                formatter.string(from: slice.data.percentage * 100 as NSNumber).map{"\($0)%"} ?? "", attributes: percentageAttr)
            categoryString.append(percentageString)
            
            return categoryString
        }
    

    without textGenerator.

    Thank you!

    opened by studiogaram 11
  • Personalizate DoughnutDemo

    Personalizate DoughnutDemo

    It is not a real problem but a clarification

    Hi, i'm using your library is good and can be used in many ways!

    I'm using your library in my project but first i'm trying in your demo project, i'm looking to personalizate the Doughnut but for me your library is not easy, i tried to modificate something and i'm getti what i want, but not at all.

    I'm gonna to personalizate the slices, where i want only two slices, 1st is the main and the 2nd will be modificate by code frequently(for that i can remove the last and create a new or i can modificate the currently slice), i want a single percentage in the middle (i have already set the text in the middle point of the doughnut but when i add slice i have a label over another).

    Have you some suggestion for my question?

    Thank you in advance.

    help wanted 
    opened by GianlucaP17 7
  • Cant add data to piechart properly

    Cant add data to piechart properly

    I ma facing an issue while adding data to pie chart from coredata, I am inserting new data with the method insertSlice and then lineTextLayerSettings.label.textGenerator this method is called and in it i am using for loop fetch data and the pie is inserted at 0 and the text is inserted at last. Can u help in this matter?

    improvement 
    opened by rahulbbit 6
  • Add support for XCode10 (Swift 4.2)

    Add support for XCode10 (Swift 4.2)

    I have updated the project to support Swift 4.2. The edits are backwards compatible to Swift 4.0 Signed-off-by: Markus Bürgler [email protected]

    opened by markus-mohemian 4
  • Updating pie chart when data changed

    Updating pie chart when data changed

    The value property of a model in the pie chart is a 'let' constant. So that cannot be modified. Other way i could figure out was to set models to empty and create models again, but that added two piecharts, one on top of another.

    Is there a clear precise way to update the chart with changing the values of the pie chart models?

    Expected Behavior: The pie chart should update the slices when the data is changed. Observed Behavior: The value property cannot be set. The updated chart shows up only when the app is started again.

    How do you recommend to update the chart when the data is changed?

    UPDATE:

    I am now able to update the chart, but I am still unable to show just the updated values in the text layer. The older text layers also show up despite removing all of them before setting the new labels.

    pieChart.models = [] pieChart.removeSlices() // now create models -> this updates the chart. However the previous text layers still show up.

    opened by karzler 4
  • Dynamically insert PieCustomViewsLayer?

    Dynamically insert PieCustomViewsLayer?

    Can I do something like:

    func onSelected(slice: PieSlice, selected: Bool) {
        if selected {
            chartView.layers = [createCustomViewsLayer()]
        }
     }
    

    Also also tried adding it while creating the chartView but then when I hide all layers by default (container view), I am not able to set isHidden=false in onSelected

    I am trying to add a uibezierpath around the selected slice, something like this:

    file

    opened by utsengar 4
  • Animation duration to 0, Infos are not displayed

    Animation duration to 0, Infos are not displayed

    I wanted to remove animation for ChartView : chartView.animDuration = 0.0

    Infos are not displayed anymore, you can test it by adding this line in "CustomViewsDemo".

    bug 
    opened by Aximem 2
  • want to change start angle

    want to change start angle

    I'm using it well but I want to change angle that start point of first pie slice.

    is there a method to change angle of chart in release version (0.04) ?

    feature request 
    opened by studiogaram 2
  • Ask for New Release

    Ask for New Release

    Hi, our team was hoping to use PieCharts through Cocoapods, with my pull request merged in the project. The current release does not have options for using PieChart without Xibs, while our team's internal policy is to not use Xibs.

    Could you do us a favor of releasing a new version of PieCharts?

    Thanks!

    opened by hyunminch 2
  • How can i change radius?

    How can i change radius?

    I want to change chart radius size but i can't do it.

    let viewLayer = PieViewLayer() let settings = PieViewLayerSettings() settings.viewRadius = 70 settings.hideOnOverflow = false viewLayer.settings = settings

    responseChart.layers = [viewLayer, responseTextLayer]

    is'nt it true?

    question 
    opened by editor83 2
  • inner and outer radius not updating when changing them via code

    inner and outer radius not updating when changing them via code

    I'm trying to add this chart to my app but I can't set the size using storyboard because it needs to auto scale with constraints. So I tried doing it programmatically but whatever I do it doesn't seem to update.

    @IBOutlet weak var profileChartView: PieChart!
    profileChartView.outerRadius = 40 //These are just demo values
    profileChartView.innerRadius = 50
    opened by JamieBerghmans 1
  • Adds Support for SPM

    Adds Support for SPM

    • Adds Support for SPM
    • Fixes compilation warnings
    • I mistakenly tagged 0.0.8 too soon, so my code jumps to v0.0.9

    Not too sure, but we may need to retag the master branch after this merge for cocoapods (and SPM) to work on the main project.

    opened by ecolesthecreator 0
  • labelGenerator creating Multiple labels for each Part

    labelGenerator creating Multiple labels for each Part

    var colors:[UIColor] = [ UIColor(hexString: "#F69300"), UIColor(hexString: "#93D460"), UIColor(hexString: "#5D86EF"), UIColor(hexString: "#F16051"), UIColor(hexString: "#FFFFFF")] var texts:[String] = [ "Lorem", "Ipsum", "Correct", "Wrong", "Correct"] var percentages:[CGFloat] = [15,12,18,25,30] var textLayers:[PieLineTextLayer] = [] var sliceModels:[PieSliceModel] = []

    for index in stride(from: 0, to: texts.count, by: 1) {
            
            sliceModels.append(PieSliceModel(value: Double(percentages[index]), color: colors[index]))
            
            let textLayerSettings = PieLineTextLayerSettings()
            textLayerSettings.label.font = Fonts.bold(size: 17)
            textLayerSettings.label.textColor = UIColor(hexString: "#F69300")
    
            let formatter = NumberFormatter()
            formatter.maximumFractionDigits = 1
            
            let textToSet = "\(percentages[index])% \(texts[index])"
            
            textLayerSettings.label.labelGenerator = { slice in
                
                let lbl = UILabel(frame: CGRect.zero)
                lbl.sizeToFit()
                lbl.text = textToSet
                lbl.textColor = self.colors[index]
                lbl.font = Fonts.bold(size: 18)
                
                lbl.setfont(text: textToSet, words: [self.texts[index]], firstFont: Fonts.bold(size: 18), secondFont: Fonts.medium(size: 14), wordColor: UIColor.white)
                return lbl
            }
            
            textLayerSettings.label.textGenerator = {slice in
                return textToSet
            }
    
            let textLayer = PieLineTextLayer()
            textLayer.settings = textLayerSettings
            
            textLayers.append(textLayer)
            
        }
        
        pieChart.models = sliceModels
        
        pieChart.layers = textLayers
    
    opened by ChanakyaHirpara 0
  • Pie chart not at center

    Pie chart not at center

    Hi Thank you for amazing lib.

    I'm using the pie chart inside a collection view cell. And it doesn't seem to be at the center (horozontal center). Pie chat view is added via Interface builder.

    Version: PieCharts (0.0.7)

            // Pie chart settings
            chartView.selectedOffset = 20
            chartView.outerRadius = 75
            chartView.innerRadius = 45
            
            var textLayerSettings = PieLineTextLayerSettings()
            textLayerSettings.lineColor = UIColor.white
            textLayerSettings.label.font = UIFont.systemFont(ofSize: 12, weight: .bold)
            textLayerSettings.label.textColor = UIColor.white
            
            let textLayer = PieLineTextLayer()
            textLayer.settings = textLayerSettings
            
            chartView.layers = [textLayer]
            chartView.strokeColor = UIColor(hexString: Constants.kDarkBackgroundColor)
            chartView.strokeWidth = 3
            
    

    Attached is a screenshot. IMG_51BDBC5159D4-1

    opened by rajdhakate 0
  • Added a check to avoid crashing if the percentage is 0

    Added a check to avoid crashing if the percentage is 0

    • I ran into this crash when receiving a 0 value from the backend server and the app attmepted to draw a chart for it. This way we'll avoid the crash vy not drawing the chart if the model.value property is 0
    opened by obada-darkznly 0
  • Labels overlapping

    Labels overlapping

    Hello,

    First of thanks for the library.

    The slice labels are overlapping if the slice values are too small. Here is a sample screenshot:

    Screenshot 2020-03-31 at 09 38 00

    Is it possible to solve this?

    Best

    opened by ergunkocak 3
Owner
null
Dr-Charts Easy to use, customizable and interactive charts library for iOS in Objective-C

dr-charts Easy to use, customizable and interactive charts library for iOS in Objective-C Features: Multiple chart types Line / Multiple lines / Lines

Zomato 93 Oct 10, 2022
SwiftCharts - Easy to use and highly customizable charts library for iOS

SwiftCharts Easy to use and highly customizable charts library for iOS Features: Bars - plain, stacked, grouped, horizontal, vertical Scatter Lines (s

Ivan Schütz 2.4k Jan 4, 2023
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
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
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
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
SwiftUI library to easily render diagrams given a tree of objects. Similar to ring chart, sunburst chart, multilevel pie chart.

Swift Sunburst Diagram Sunburst diagram is a library written with SwiftUI to easily render diagrams given a tree of objects. Similar to ring chart, su

Ludovic Landry 494 Dec 19, 2022
A simple and animated Pie Chart for your iOS app.

XYPieChart XYPieChart is an simple and easy-to-use pie chart for iOS app. It started from a Potion Project which needs an animated pie graph without i

XY Feng 1.7k Sep 6, 2022
A simple pie chart for iOS.

EGPieChart Installation EGPieChart is available through CocoaPods. To install it, simply add the following line to your Podfile: pod 'EGPieChart' manu

Ethan Guan 3 Nov 29, 2021
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