iOS

How to Use iOS Charts API to Create Beautiful Charts in Swift


Using charts to display data can help users understand the information more easily than they would if it were presented in a table, especially when dealing with a lot of data. With charts, you can easily see patterns in the data at a glance as opposed to reading through a whole table (or several tables) to get this information. The use of charts has been a common feature in business and fitness apps.

In this article, we’ll look at how to add charts to your application using the ios-charts library by Daniel Cohen Gindi. ios-charts is an iOS port of the fairly popular Android library MPAndroidChart created by Philipp Jahoda. With this library, you can include various types of charts in your app fairly quickly and easily. With a few lines of code, you can have a fully working and interactive chart, that is highly customizable.

Core features of the library include:

  • 8 different chart types
  • Scaling on both axes (with touch-gesture, axes separately or pinch-zoom)
  • Dragging / Panning (with touch-gesture)
  • Combined-Charts (line-, bar-, scatter-, candle-stick-, bubble-)
  • Dual (separate) Y-Axis
  • Finger drawing (draw values into the chart with touch-gesture)
  • Highlighting values (with customizeable popup-views)
  • Multiple / Separate Axes
  • Save chart to camera-roll / export to PNG/JPEG
  • Predefined color templates
  • Legends (generated automatically, customizable)
  • Customizable Axes (both x- and y-axis)
  • Animations (build up animations, on both x- and y-axis)
  • Limit lines (providing additional information, maximums, e.t.c.)
  • Fully customizable (paints, typefaces, legends, colors, background, gestures, dashed lines, e.t.c.)

Getting Started

To get started, first download the starter project we’ll be using in the tutorial. It’s of a simple application called iOSChartsDemo. When you run the app, you’ll get a table with two items: Bar Charts and Other Charts. On tapping on these list items, you’ll get empty views. In the project, I have created two view controllers which we’ll use: BarChartViewController and ChartsViewController.

Next we’ll include the library in our project. You can use CocoaPods to install the library, but here, we’ll do the manual installation.

Download the ios-charts project. The zip file contains the library (in a folder named Charts) and a demo project (named ChartsDemo). The demo project is a great resource to use if you want to learn more about the library.

Unzip the downloaded file and copy the Charts folder and paste it into your project’s (iOSChartsDemo) root directory. Open this Charts folder in Finder and drag Charts.xcodeproj to your project in Xcode. You should have something similar to what’s shown below.

charts01

Next select your project from the Project Navigator and make sure that the iOSChartsDemo target is selected. In the General tab on the right, locate the Embedded Binaries section and hit the + in this section to add the charts framework. Select Charts.framework from the list and click Add.

charts02

If you want to use the library in an Objective-C project you can read how to do this from the Usage instructions.

Build the project with Command-B or by going to Product > Build. If you don’t build the project first, Xcode will give the error “Cannot load underlying module for ‘Charts'” when you import the Charts framework into your files.

Now we are ready to create our first chart.

Creating a Bar Chart

Open BarChartViewController.swift file and add the following import statement.

Open the storyboard file. We need to add the view that will show the chart. Select Bar Chart View Controller from the Documents Outline and in the Attributes Inspector, uncheck the Under Top Bars in Extend Edges. We don’t want the chart to extend itself underneath the navigation bar.

charts03

Next drag a View onto the Bar Chart View Controller and pin its edges as shown. This View is a child of the main View in the controller.

charts04

With this View still selected, go to the Identity Inspector and set its Class to BarChartView. Then use the Assistant Editor to add an outlet of the view to the BarChartViewController class. Name the outlet barChartView. You should have the following in the BarChartViewController class.

Run the project and select Bar Chart from the table, you should get a view with the message “No chart data available”.

charts05

You can customize this message if you want to display something different for your Blank Slates when no data is available for a chart to be generated. In viewDidLoad() add the following to the bottom of the function.

Run the project and you’ll be presented with the custom message.

charts06

You can further add a description to this with the following. This can be used to explain to the user why the chart is empty and what they need to do in order to get data, for example a fitness app can let the user know that they need to record X number of runs before the data can be aggregated.

Add the following attribute to the class. We’ll use it to store some mock data for the chart.

Add the following function to the class. We’ll use it to set up the chart.

Notice I have included the statement we had in viewDidLoad() here. Remove that statement from viewDidLoad(). We’ll use setChart() to customize the chart.

In viewDidLoad(), add the following to the bottom of the function.

We set some mock data that gives the number of units sold of some product for each month in a year. We then pass this data to setChart().

For a chart to display data, we need to create a BarChartData object and set it as the barChartView’s data attribute. Add the following to the botton of setChart()

In the above code, we create an array of BarChartDataEntry objects. The BarChartDataEntry initializer takes the value of each data entry, the index of the entry the value corresponds to and an optional label.

We then use this object to create a BarChartDataSet which is created by passing in the array of BarChartDataEntry objects and a label to describe the data.

Finally we use this to create a BarChartData object which we set as our chart view’s data.

Run the app and you should have a bar chart of the data.

charts07

You can set a description of the chart that will appear on the bottom right of the view. By default, the text is set to “Description” as you can see in the image above. A look through the documentation of MPAndroidChart, shows that you should be able to change the location of the description, but looking through the iOS API, this wasn’t included. The library is still being maintained, so this might be added at a later date. If you want to change the location of the description, you can change this in the drawDescription(context) function of the ChartViewBase class which is a superclass of the BarChartView class.

For our app, we’ll remove the description text. Add the following to the bottom of setChart() to set the description text to an empty string.

Customizing the Chart

You can customize the look of the chart view by changing some of its attributes. We’ll look at some of these; you can have a look at the documentation to find out what else can be customized.

First we’ll change the default color of the bar chart. Add the following to the bottom of setChart()

The above sets the colors that will be associated to our data set. We set this to an array of UIColor objects. Since we only have one color in our array, this will be used for all the entries.

charts08

If you want a different color for each data entry, then you have to provide as many colors as the total number of data entries you have, in our case 12. If you give a lesser number of colors than the total entries, then the bars, starting from the left will be set to the different colors provided until the colors run out whereby the color scheme will be repeated (like the image below where we use a template, 5 colors are repeated throughout)

The API also comes with some predefined color templates you can use to set different colors for the data set. They include:

  • ChartColorTemplates.liberty()
  • ChartColorTemplates.joyful()
  • ChartColorTemplates.pastel()
  • ChartColorTemplates.colorful()
  • ChartColorTemplates.vordiplom()

Using the ChartColorTemplates.colorful() template gives the following.

charts09

To change the position of the x-axis labels use the following.

Now the labels are at the bottom of the chart.

charts10

You can also change the chart’s background color with the following.

With the above, you’ll get:

charts11

Animation

You can add some animation to the chart to make it more interesting. There are 3 main types of animation methods you can use to animate either both axes or the x and y axis seperately.

  • animate(xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
  • animate(xAxisDuration: NSTimeInterval)
  • animate(yAxisDuration: NSTimeInterval)

You can add an optional ChartEasingOption to the above functions. The options available are:

  • Linear
  • EaseInQuad
  • EaseOutQuad
  • EaseInOutQuad
  • EaseInCubic
  • EaseOutCubic
  • EaseInOutCubic
  • EaseInQuart
  • EaseOutQuart
  • EaseInOutQuart
  • EaseInQuint
  • EaseOutQuint
  • EaseInOutQuint
  • EaseInSine
  • EaseOutSine
  • EaseInOutSine
  • EaseInExpo
  • EaseOutExpo
  • EaseInOutExpo
  • EaseInCirc
  • EaseOutCirc
  • EaseInOutCirc
  • EaseInElastic
  • EaseOutElastic
  • EaseInOutElastic
  • EaseInBack
  • EaseOutBack
  • EaseInOutBack
  • EaseInBounce
  • EaseOutBounce
  • EaseInOutBounce

Add the following to setChart()

Run the app and the bar chart will animate into view. We animate both axes in 2 seconds.

charts01

Change the above statement to:

And you’ll see the effect of the above.

charts02

Limit Lines

The limit line is an additional feature for all Line, Bar and ScatterCharts. It allows the displaying of an additional line in the chart that marks a certain limit on the specified axis (x- or y-axis). Such a line can be used to set a target/goal value for the data and helps the user easily see where they didn’t meet the target.

To add a limit line to the chart, add the following to setData()

On running the app, you should see a red line marking the 10 units limit. In the above code we added a label to the limit line, but ChartLimitLine has another initializer that doesn’t take the label, so you can omit it if you prefer.

charts12

Touch Events

If you run the app, you’ll notice that zooming by pinching and double tapping work by default. Also, a tap on a bar highlights the tapped bar. It’s great that we get this functionality for free without writing any code for it, but you might want to add more functionality, for example take some action when the user taps on a bar.

To detect selections made inside the chart, we’ll use the ChartViewDelegate protocal.

Modify the class’ declaration as shown.

Add the following to viewDidLoad() after the call to super.viewDidLoad()

Then add the following function to the class.

The above is called when a value has been selected inside the chart view. Here we print out the value and month selected.

Saving the Chart

You can save the current state of a chart as an image. You can choose to save it to the camera roll or you can set a path for it to be saved to.

First we’ll add a Save button to the chart view. Open the storyboard file and locate the Bar Chart View Controller. Drag a Navigation Item to the view controller’s navigation bar, then drag a Bar Button Item and place it to the right corner of the Navigation Item. Remove the “Title” text of the Navigation Item’s Title attribute in the Attributes Inspector. Select the Bar Button Item and set its identifier to Save in the Attributes Inspector. You should have the following.

charts13

Next create an action for the button. Name it saveChart. You should have the following in the BarChartViewController class.

Modify the above method as shown.

Run the app and when you tap the Save button, an image of the chart will be saved to the camera roll. You can view it using the Photos app.

You can instead set a path to save to with the following method.

The format can be either .JPEG or .PNG and the compressionQuality is the compression quality for lossless formats (JPEG).

More Charts

Here we’ll look at a couple of other chart examples we can create. I won’t give detailed instructions since we’ve looked at most of what we’ll do.

First locate the Charts View Controller in the storyboard file and set the Class of the view labelled Pie Chart View to PieChartView in the Identity Inspector. Do the same for the Line Chart View, setting its class to LineChartView. Then create outlets for these two views named pieChartView and lineChartView respectively.

Then modify the ChartsViewController class as ahown.

In the above, we import the Charts framework into the class and create a pie chart and a line chart in the same way as we created a bar chart. Note however, we use the superclass ChartDataEntry to create data entry objects when in the bar chart example we used BarChartDataEntry. Not all charts have subclasses for ChartDataEntry and so here, we use the superclass. For the chart data set and chart data objects, we use the specific subclass for the particular chart.

If you run the app and select Other Charts from the table view, you should see a line chart and a colored pie chart. Your app will look different from the one shown, since we use random numbers for the pie chart’s colors.

charts14

Conclusion

We’ve only looked at a few chart types that can be created using the ios-charts library. We’ve also only touched the surface of the customization you can perform on a chart. If you want to know what else the library is capable of, you can look through the code of the ChartsDemo project that comes with the library download and also have a look at the project’s Wiki. The link to the Wiki page leads to the MPAndroidChart project documentation. At the time of writing, there is no documentation for the iOS version of the library, but since the API is about 95% the same as on Android, the Android documentation can still come in handy when searching for help.

You can download the completed project here.

The following shows the type of charts you can create (images are from the original repository)

LineChart (with legend, simple design)

LineChart (with legend, simple design)

LineChart (cubic lines)

LineChart (single DataSet)

Combined-Chart (bar- and linechart in this case)

BarChart (with legend, simple design)

BarChart (grouped DataSets)

Horizontal-BarChart

PieChart (with selection, …)

ScatterChart (with squares, triangles, circles, … and more)

CandleStickChart (for financial data)

BubbleChart (area covered by bubbles indicates the value)

RadarChart (spider web chart)

Note: This tutorial is also available in Chinese. We’re going to support other languages soon. If you want to join our translation team, please contact us.
iOS
A First Look at Contacts Framework in iOS 9
iOS
How to Access Photo Library and Use Camera in SwiftUI
Tutorial
Using Google Cloud Translation API to Power Your App with Instant Translation
  • Yanchi88

    Yanchi88Yanchi88

    Author Reply

    While I agree that ios-charts is very well made library, documentation is rather poor (maybe because everything is well documented in android lib? :)). Basically if you do anything complex like custom colors based on data value, multiple y values for each x axis point, you are going to have a pretty hard time figuring out, how to do it.


    • Ivan Schuetz

      With this library that’s easy: https://github.com/i-schuetz/SwiftCharts

      Admittedly there’s also little documentation, but on the other side a bunch of self explanatory examples which can be customized quickly.


    • Andre

      AndreAndre

      Author Reply

      SOMEONE PLEASE document this lib…………….. I had no trouble with Android Studio, but I can’t make this do anything in IOS Swift 3. HELP!


  • Ben

    BenBen

    Author Reply

    Hey Joyce, I was wondering how can I create beatiful presentation of screenshots like the first picture of this tutorial?


    • Joyce Echessa

      Hi Ben, Simon actually does that with the screenshots I take of the tutorial app. But if you want such an image, you can find free and for-sale iphone mockup PSDs online. You just open the mockup in Photoshop and drop in your image. The PSDs come with actions that will size and transform the image, so it will look right in whatever position the device is in. Look at this as an example.


  • miles

    milesmiles

    Author Reply

    Every time I think of something I’d like to accomplish, AppCoda has a tutorial on it. Thanks!


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Thanks for your words! So glad to hear that.


    • yuppymike

      yuppymikeyuppymike

      Author Reply

      Same for me, couple of times I thought “I wonder how you do….” And within a few days it appears on here!


  • Chris Kong

    Chris KongChris Kong

    Author Reply

    Great tutorial. I ran into trouble running the other 2 charts on the simulator. Got this message on the console:

    iOSChartsDemo[57733:10990604] Unknown class LineChartView in Interface Builder file.

    2015-06-24 12:36:32.422 iOSChartsDemo[57733:10990604] Unknown class PieChartView in Interface Builder file.

    What I am doing wrong?


  • Bin Sand

    Bin SandBin Sand

    Author Reply

    Hello,

    This is really an informative blog for all the beginners as well as app developers. I like Objective C more than Swift.

    I am an iOS app developer, I have tried most of the mobile app development platforms described above. I have developed more than 50 apps till today with the help of Phonegap, Telerik, Configure.IT etc. They are running successfully on app store.

    As per my experience in this field, I recommend developers as well as beginners to use mobile app development platform like Configure.IT, because it provides automatic coding, app preview facility, direct API connect and a lot more features. These things save a lot more development time and provides fast and well designed app in much less time.

    Read more: http://www.configure.it/features/mobile-app-configuration/


  • timbojill

    timbojilltimbojill

    Author Reply

    I am a newbie developer. If anyone want to chat about IOS Development kindly Google Chat/Hangouts with me. My email address is [email protected].


  • Stan Sison

    Stan SisonStan Sison

    Author Reply

    Hi, this looks like a well made library. I’m working on a charting app and I’m curious how this compares to coreplot 2.0?


    • Joyce Echessa

      Hi Stan, I have no experience with CorePlot, so I can’t make any comparisons between the two.


      • Stan Sison

        Stan SisonStan Sison

        Author Reply

        Thank you Joyce, I’ll try it out and see how they compare with each other.


      • Ivan Schuetz

        You may also want to take a look at SwiftCharts: It’s written to be very easy use and customize. Written from the ground up in Swift, taking full advantage of the language (it also already has a fully functional Swift 2.0 branch) . And it has also a lot of examples. https://github.com/i-schuetz/SwiftCharts


  • Mohammed Khalidi

    I am a beginner in programming and I found this post very informative and I have applied all steps as mentioned above and I got the results as shown, but I tried to apply that to my own project but I couldn’t manage to get the same result

    My project is about many business centers with different results for each business centre and I want to link each cell of my table to a bar chart

    PLEASE Help it would make my life easy 🙂


    • Joyce Echessa

      Hi Mohammed, it seems that you are going for a slightly different bar chart than the one in the tutorial. You said you wanted to show results for different companies, so are you looking to create a chart as shown in the image under BarChart (grouped DataSets) above? If so, then you’ll need to create data sets for each company. In the tutorial example we, only had one dataset.

      If you need further help, look at the demo project that comes when you download ios-charts. I don’t have the running app infront of me at the time of writing, but looking through the code on github right now, I’m guessing what you need is in MultipleBarChartViewController

      If that’s not what you want, then run the demo app and look through the different chart examples and if you find one that fits your needs, then check its corresponding code.

      Hope that helps.


  • JCarlos

    JCarlosJCarlos

    Author Reply

    Why if if start from scratch, I mean, I project from zero, It sends an error, but If I use you starter project It function perfectly?


  • Ian

    IanIan

    Author Reply

    Hi Joyce, thanks for the tutorial. I am looking for a charting option. At the moment I need to be able to do a stacked bar chart. Can this software do that and if so would you have an example?
    Thanks, Ian


    • Joyce Echessa

      Hey Ian, you can see all the different types of charts the library can create by running the ChartsDemo project that comes with the downloaded library zip file. Just run it and if you find one that fits your needs, check its code in the demo project. Here’s a quick video of the Android version that might help you decide https://www.youtube.com/watch?v=ufaK_Hd6BpI


  • Daniel Cohen Gindi

    @joyceechessa:disqus thanks for creating this great tutorial!

    I wanted to say something to the community:

    1. Documentation is not a top priority as it already exists (as @yanchi88:disqus mentioned) in the android repo. We are however improving the documentation in the code, which pops up while coding or shows in the right pane in Xcode when pointing at a function or a variable.

    2. If you’re using CocoaPods, not that you might be struggling with a bug that is fixed in the GitHub repository, so if something behaves really weird you might want to check there.

    3. If you are wondering if something is possible – just check out the demo. The demo in the Android project has more features, but that’s just because I was too lazy to write all the demos in Swift too. But the functionality is there 🙂

    And finally…
    Thanks for using and supporting Charts!

    There are some great people helping out with this project, with idea, bug reports, and pull requests and implementation of new features. Thanks!


  • Nitin KR

    Nitin KRNitin KR

    Author Reply

    Hii Joyce.. Thank you for the wonderful library.. im implementing a simple bar chart in ios swift as like the screenshot attached. where,
    1.The heighest data points on every y axis should be indicated with a Circle dot..
    2. change the color of each bar. (Custom Colors)
    3. minimize the width of each bar..

    It would be a super great help for me if you can help with this.. Thanks in advance.


    • Anoop Ghildiyal

      I am looking for the same solution. Please help me in this!!!!!!!! thanks in adv..


      • Ivan Schuetz

        Try out this library: https://github.com/i-schuetz/SwiftCharts it’s quite easy to customize and the features you request are not a problem there.


        • Gokul

          GokulGokul

          Author Reply

          Ivan, Your SwiftChart is great. I’ve been using GroupedAndStacked Bar and I got stuck on an issue. With the below data on X and Y axis, the graph won’t show –

          let groupsData: [(title: String, bars: [(start: CGFloat, quantities: [Double])])] = [

          (“A”, [

          (200000,

          [200]

          )

          ])]

          let (axisValues1: [ChartAxisValue], axisValues2: [ChartAxisValue]) = (

          Array(stride(from: 200000, through: 201000, by: 100)).map {ChartAxisValueFloat($0, labelSettings: labelSettings)},

          [ChartAxisValueString(order: -1)] +

          Array(enumerate(groupsData)).map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} +

          [ChartAxisValueString(order: groupsData.count)]

          )


          • Ivan Schuetz

            Ivan SchuetzIvan Schuetz

            Author

            Hi Gokul,
            thanks for the feedback, the issue is fixed now (in master). Next time please report issues directly in Github, it’s better to keep things organized and Disqus is easy to miss.


          • Gokul

            GokulGokul

            Author

            Ivan, that worked like a magic. Appreciate your quick response.


    • Ivan Schuetz

      Try out this library: https://github.com/i-schuetz/SwiftCharts/ it’s quite easy to customize and the features you request are not a problem there.


  • Suresh

    SureshSuresh

    Author Reply

    Hi Daniel Cohen Gindi. i am a beginner in ios It sends an error “Could not build Objective-C module ‘Charts'”. Please help me in this! thanks in advance


    • Suresh

      SureshSuresh

      Author Reply

      Please help me in this


  • amol p

    amol pamol p

    Author Reply

    Hi,

    I am trying to follow this tutorial using xcode 7-beta. The starter project with the empty views builds correctly and I can see it running in the simulator. But as soon as I include the embedded binaries and try to build, it gives an error, where the linker says “directory not found for option -F/Applications/Xcode-beta-app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs”
    “/iPhoneSimulator9.0.sdk/Developer/Library/Frameworks”

    Why is it trying to get ios9 SDK? I am not able to proceed beyong this point. any help is appreciated.


  • vishal

    vishalvishal

    Author Reply

    GReat……………Tutorial ….. Love it


  • Šulinokaz Cizopasný

    Hi, I’m trying to use the library to create quite simple Bar+Line chart, but I can’t figure out how to achieve what I need although I’ve read project’s wiki and checked demo sources carefully, but maybe I missed something important, so I’d like to ask you for help. Can I contact you on email to not bother the others here? Thank you.


  • Azadi Means Freedom

    Hi, great tutorial!

    One question: What if I wanted to set up multiple years, in other words, using the 12 columns you provided, but to do it for 3 years (36 entries?) I am trying to do this, but cannot get more than 12 columns to show.

    Thanks so much in advance!


  • Huy Nguyen

    Huy NguyenHuy Nguyen

    Author Reply

    Hi Joyce, how can i place a background image below a chart ?
    Thank you.


  • Karpis Sanosyan

    I keep getting a Use of unresolved identifier ‘dataPoints’

    for i in 0..<dataPoints.count {

    let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)

    dataEntries.append(dataEntry)

    }

    let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Units Sold")

    let chartData = BarChartData(xVals: months, dataSet: chartDataSet)

    barChartView.data = chartData

    Can someone help me with this thank you


    • Michael

      MichaelMichael

      Author Reply

      The variable dataPoints is out of scope. Make sure your code is inside the function setChart(),


  • neena

    neenaneena

    Author Reply

    hi i want to show a title on y axis just to show the units of the data point like . kg e.tc. i don’t want to show it with every other data point rather want to show on whole y axis as a label. is there any option in these graphs that i can do it with line graphs.


  • Joel G. Verástica

    Hey! Thanks for sharing this amazing library 🙂
    I’m implementing it and everything is looking good… just one thing, do you know how to delete the legends for the data sets?? Thanks in advance


  • Hi Ren 

    Hi Ren Hi Ren 

    Author Reply

    Hi Joyce,

    Thanks for nice tutorial.

    How can I show multiline detail information in stack bar ? Right now it’s showing only single line so my most of the chart detail information are wrap up.

    Thanks,
    Hiren


    • John Brohan

      Hi Ren
      I would like to make an x_axis similar to yours. Would you possibly share the formatting of the x-axis with me? The rest of it is going well. How did you get the names in the colors at the bottom (stack bar?) Thanks.


  • Cesar Ceron

    Hello, i was using your library and it was working good, but i ve updated to Xcode 7 and all libraries started to show errors, do i need to do something special to make this chart compile is this new Xcode version? Thanks in advance


  • Cesar Ceron

    Hello Joyce, first of all i would like to thank you for this library it helps me a lot, but now im have a problem

    Yesterday apple released a new version of xcode, i’ve dowloaded and installed the new xcode then when i open my code, xcode asked me to migrate my app, after i click on accept (big mistake) the aplicacion and the libraries shows like 50 errors that i tried to solve it but xcode show more errors, pls could you tell what to? how it can be solve ?

    Thanks for you help


  • 章恩齊

    章恩齊章恩齊

    Author Reply

    iOS charts project can’t support xCode 7.0 for iOS9. have anyone can help?


  • John Brohan

    Hide the Grid

    Thanks for the wonderful library and clear examples…but

    I need to not display a grid … Please!


    • Dan Beaulieu

      you’ll wind up doing something like this in you viewDidLoad:
      self.lineChartView.leftAxis.gridColor = UIColor.clearColor()


  • Meinhard Kissich

    I tried to follow your instruction to implement your library in the demo project. As I tried to build the project after adding the Charts.framework I got 22 errors. (El Capitan, latest Xcode update: 03.10.15) – Am I doing something wrong?


    • BlackPearl12

      It is because you need to use the latest syntax method, where the parameters are changed.


  • JCarlos

    JCarlosJCarlos

    Author Reply

    Hi Joyce! I want to create an array of charts, but when I implemented it, the type of the array is ChartViewBase, and I can´t assign any kind of data to the chart. Do you know how can I make it?


  • Jeetendra Choudhary

    Hi Joyce,

    I am trying to implement the pie chart, but not able to see the legends in pie chart using the same code above just the data set and data entries are changed .. Can you help what might be an issue here ..

    here is the code –

    func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {

    let dataEntry = ChartDataEntry(value: values[i], xIndex: i)

    dataEntries.append(dataEntry)

    }

    let pieChartDataSet = PieChartDataSet(yVals: dataEntries, label: "Months")

    let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)

    pieChartData.setDrawValues(false)

    pieChartView.data = pieChartData

    pieChartView.animate(xAxisDuration: NSTimeInterval(5))

    var colors: [UIColor] = []

    for _ in 0..<dataPoints.count {

    let red = Double(arc4random_uniform(256))

    let green = Double(arc4random_uniform(256))

    let blue = Double(arc4random_uniform(256))

    let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)

    colors.append(color)

    }

    pieChartDataSet.colors = colors

    }


  • John Brohan

    Show y-Axis as Integers

    let formatter: NSNumberFormatter = NSNumberFormatter()

    formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle

    lineChartView.leftAxis.valueFormatter = formatter

    This is really very easy, but hard to find!!!

    f anyone knows how to show x-axis labels as strings (0,15s,30s,45s) please let me know. I can’t show any labels on the x-axis right now!!


    • 陳胤

      陳胤陳胤

      Author Reply

      thx!!!! i have been looking for this for a week!!!!!Thanks a lot


  • Akilan Kamal

    Is it compatible to iOS 7?


  • Cary Douglass

    I tried you tutorial and the bar chart worked fine but the pie chart crashed with an error of: fatal error: unexpectedly found nil while unwrapping an Optional value. Any Idea why??


    • JeffDec

      JeffDecJeffDec

      Author Reply

      2 reasons for this to happen.
      1.In the Identify Inspector, the custom class is not set to barchartview or linechartview, and the module should be charts.
      2. In the Connection Inspector, the connections to your views are not connected.


  • Pirate Chicken

    doesn’t work when you try and run the completed program, using Xcode 7


    • Prince Umair

      i was getting same problem i solved it simply by uodating my Xcode to 7.3


  • Pirate Chicken

    please update the code or give instructions on how to run the completed code…

    When I was going to add the outlets for pie and line charts, it wouldn’t let me add them.. so i tried to run the completed program and it has so many errors and that saved over my work, and I am new to this. Please help.


    • Raghunath

      RaghunathRaghunath

      Author Reply

      Download the full source code from Appcoda,…..


  • Rohan Sanap

    How can I use this library in current Objective-C project? I really want to use this


    • Raghunath

      RaghunathRaghunath

      Author Reply

      Swift to objective-c Integration:

      1) Create a new Project in Objc

      2) Create a new file in Swift

      then popUp a window for confirmation” Would You like to configure in Objective-c bridging Header” .

      Please check Out Yes.

      3) Click on your Xcode Project file

      4) Click on Build Setting

      5) Find a search bar and Search “Defines module”.

      6) Please tick out “Yes”.

      7) Search “PRODUCT MODULE.

      8) Please write Your Project name.

      9) Please Write in Your App delegates #Import “YourProjectName-swift.h”


  • jan gifvars

    Hi!

    I wonder if there is an example how to programatically start/view a LineChart for example from an Objective-C ViewController class?
    My data to be plot’ed are a NSMutableDictionary object with NSintegers, sort of…

    Kind regards.


    • Kyle Hadley

      Jan,

      Did you ever learn how to programmatically create a LineChart? I’m trying to perform the same operation you’re discussing except with Swift and was hoping that if you had a solution, it might help me with my problem.

      Thanks!


  • Cássia Rosa

    Hi Joyce,

    First excuse me by the English .

    I’m trying to use the framwork , but this returning me the following error (imgem):

    Any idea what mistake I am making ? 🙁

    I am new to ios development.

    Grateful now.


  • Yosuke Nakayama

    Can use by iOS 9? barChartView.noDataText = “You need to provide data for the chart.” I tried this code but doesnt work


    • Pedro Luis Berbel

      set in the view inside of BarChartView the class “BarChartView” / Module: Charts


      • Yosuke Nakayama

        its work! you are my hero!


      • Arjun Mayilvaganan

        For me, still doesn’t work. Says: “EXEC_BAD_INSTRUCTION”.


        • Ploy Goh

          Ploy GohPloy Goh

          Author Reply

          me too


          • Ploy Goh

            Ploy GohPloy Goh

            Author

            @arjunmayilvaganan:disqus please try connect your view to the code via Assistance Editor.
            Hope this help!


  • Raghunath

    RaghunathRaghunath

    Author Reply

    I can able to show the char using BarChartViewController.Swift.I want to show the chartData(which is in swift file) in my ViewController(obj-c) view.If i compile means, Function is called and its entering into viewDidLoad().But it shows the error

    This is my entire source code:
    ViewController.m

    #import “ViewController.h”
    #import “Demo-swift.h”
    #import “Demo-Bridging-Header.h”

    @interface ViewController ()

    @end

    @implementation ViewController
    – (void)viewDidLoad
    {
    [super viewDidLoad];
    UIView *ChartView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 450)];

    BarChartViewController *cv = [[BarChartViewController alloc]init];
    [cv viewDidLoad];
    }

    BarChartViewController.swift

    import Foundation
    import Charts

    public class BarChartViewController: UIViewController {

    @IBOutlet var barChartView: BarChartView!
    @IBOutlet var lineChartView: LineChartView!
    @IBOutlet var pieChartView: PieChartView!
    var months: [String]!

    override public func viewDidLoad()
    {
    setChart(months, values: units)
    }

    public func setChart(dataPoints: [String], values: [Double])
    {

    var dataEntries: [BarChartDataEntry] = []

    for var i=0; i < dataPoints.count; i++
    {
    let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
    dataEntries.append(dataEntry)
    }
    print(dataEntries)
    let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Units Sold")

    let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
    chartDataSet.colors = [UIColor .redColor()]

    barChartView.data = chartData

    barChartView.xAxis.labelPosition = .Bottom

    }

    fatal error: unexpectedly found nil while unwrapping an Optional value

    I will give you reward if you provide solution.


  • 吳易達

    吳易達吳易達

    Author Reply

    How can I use charts SDK to create the chart like below …


  • Murat

    MuratMurat

    Author Reply

    Hi Joyce,
    The library is awesome. I’m using the pie chart in my ios app and it works excellent. I just want to move the labels in slices a bit outside of the pie. Is it possible? Just illustrated below.
    Thanks


    • Bhagwan Rajput

      Hello, sir can i get full source code in swift if it is available in anywhere plz give me link..
      -Thanks in advance.


  • Vatsal

    VatsalVatsal

    Author Reply

    I can’t seem to figure out how to do Group Bar Chart. did anyone do it? if so, do you mind sharing it?


  • mahmoud essa

    Dear
    Thank you for amazing Charts but i see this problem when build and run

    ld: framework not found Realm for architecture x86_64

    clang: error: linker command failed with exit code 1 (use -v to see invocation)

    Please help thank you


  • Alex

    AlexAlex

    Author Reply

    in swift 2 not working


  • Carmine Cuofano

    wow! these are the most beautiful charts APIs but i have a question

    if i use the first chart (that you show in the tutorial) , when i get to insert my data, the charts will get to resize by my data, is possible fix a point ( for example 10) as the maximum value and show the chart ?
    i’m certain that the value will always be minor or equal to 10

    as you can see in the following images , the maximum values are different

    i would like to fix a maximum value in the charts. Is it possible?


  • Ploy Goh

    Ploy GohPloy Goh

    Author Reply

    How to create stacked bar chart?


  • Keshav Aggarwal

    Can I use this code in my app?


  • Nils

    NilsNils

    Author Reply

    Great tutorial! I’m trying to implement a combined bar- and line chart but can’t figure out how to do this. How could I put together the different data sets?


  • adam

    adamadam

    Author Reply

    How can i change the colour of the legend. or to remove the legend?


  • StevieCoyle

    Have loads of problems getting this example off the ground. I have only been able to add iOS-charts to a project and build once. But then when I try and import Charts to a file, it cannot find it? Tried everything, been looking at know issues on iOS-charts GitHub page and Stack Overflow. Nothing is helping. I have updated Xcode to 7.3 and that sort of help. But still not working. Can someone explain how I should embed the iOS-charts framework into a project.


  • Gauurof

    GauurofGauurof

    Author Reply

    Hi there,

    thanks for the nice tutorial. I have a question about the Piechart. Is is possible to change the size of the text when you click on the slice?


  • Prince Umair

    Thank You soo mch for this lovely tutorial can you please guide me how can i get these behaviours for Bar and Line ?
    i want graphs for more then one data array


  • Volkan Paksoy

    Thanks for the great tutorial. Very informative and great starting point for using the Charts library.


  • Shiroh23

    Shiroh23Shiroh23

    Author Reply

    hey!

    i want to disable the pinch to zoom option in the charts view, can i do that in the code? 🙂


    • 陳胤

      陳胤陳胤

      Author Reply

      HI! did you find the solution? can you share with me?


      • Eduardo Oliveros

        hello, this properties not are of lineChartView? how i can customize it ?

        thanks


        • 陳胤

          陳胤陳胤

          Author Reply

          lineChartView.pinchZoomEnabled = false


          • Eduardo Oliveros

            how i can repeat x values , example: xvalues[“monday”,”thursday”,”wednesday”,”tuesday”,”friday”] Yvalues: 30 values of all days of the month i want see all points in one chart. my email [email protected]


    • 陳胤

      陳胤陳胤

      Author Reply

      chart.pinchZoomEnabled = false
      chart.doubleTapToZoomEnabled = false
      chart.scaleXEnabled = false
      chart.scaleYEnabled = false


  • Pravin

    PravinPravin

    Author Reply

    let months = [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”]
    let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]
    setChart(months, values: unitsSold)

    When I add this code to viewDidLoad() i get the correct pie chart with its legend, But when i add the same code in viewDidAppear the legends(count) do not appear. Its shows incorrect count of legends. Any help would be appreciated. Thanks in advance.


  • Isra Hun Ikal

    Hello! Awesome tutorial n working like a charm. I wanted to ask you, how do you make the lines of LineChartView curved? like in the examples. Thank you!


  • Johanna

    JohannaJohanna

    Author Reply

    Thx, it’s a great How to.

    I have met an issue, I would like to force all xAxis labels to show with Charts iOS but atm, xAxis labels have showed with an interval : 2.

    Any help ? 🙂


    • Jans Calderon

      You can use mLineChartView.xAxis.setLabelsToSkip(0) This will force all of the labels to be displayed.


  • William_admin

    Hi all, small question. If the results are all high numbers I don’t see the bottom part of chart. Example: I have two lines, results are 10,15, 22 and 9,22,17, I can’t see the chart from 8 to 0. Any idea why? Or should I make the view bigger?


  • thecruz3r

    thecruz3rthecruz3r

    Author Reply

    anyone knows how i can load the graph data from a core data table ?


  • Ramy Al Zuhouri

    What if you want real values on the x axis? the ChartDataEntry constructor just accepts an integer index (ChartDataEntry::init:value:xIndex).


  • Morgan May

    Morgan MayMorgan May

    Author Reply

    Great tutorial! I’m having some difficulty getting horizontal bar graphs to work though. is there something I’m missing with it’s implementation?


  • Parth Anand

    In Pie chart I want to perform a segue when i click on a particular slice.
    for eg : if i click on the “jan” slice i want to go to some other viewController. and when i click feb i want to go to some other view controller. can someone help me with this? i am trying this since very long time and not able to achieve it. 🙁
    please help!


    • Charuta Rajopadhye

      They have provided a callback for the click event.
      Implement ChartViewDelegate protocol, and call performSegue method in delegate method:
      // MARK: ChartViewDelegate
      func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) {

      // perform segue goes here
      }


  • Rahul

    RahulRahul

    Author Reply

    How to show legends on click bar same like popover??


  • Eduardo Oliveros Acosta

    look this video to customize the charts https://www.youtube.com/watch?v=p_bp8gH1odg


  • NyoSeint Lay

    Could we change X-axis data points, now X-axis data point are always same size?
    I tested with NSObject , Double array, but it also not working.
    For eg –
    Xaxis – 4.7, 9.41, 18.81, 37.6, 75.6
    Yaxis – 0.035, 0.146, 0.373, 0.912, 2.276


  • Rajesh Maurya

    Great tutorial.


  • Paulo Carvalho

    How to set percent % in values? Me did not show.


  • Sanjeev

    SanjeevSanjeev

    Author Reply

    I am trying to run this project on iOS 9 but it gives lots of compile errors(in charts.xcodeproj). Anyone has any idea how to resolve those. Count is approximately more than 300 🙁


    • Sanjeev

      SanjeevSanjeev

      Author Reply

      I have created my own sample project and included charts.xcodeproj and its working fine now. But when I am trying to add following piece of code

      for i in 0..<dataPoints.count {
      let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
      dataEntries.append(dataEntry)
      }

      let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
      let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
      barChartView.data = chartData

      It is giving error in BarChartDataEntry and BarChartData saying it does not match any available argument

      Is anyone also facing same problem??


    • Kevin Zuiker

      I have 139 compilation errors. Not sure what the problem is, but I can’t even use it.


  • Sanjaysinh Chuahan

    Can I use this Charts API for demand graph. Means I have 100000 data point and I want to load those points as I scroll the graph.


  • Dhamodharan Krishnan

    Charts 3.0 APIs now bit of change. Please refer original one from this same page and apply new API changes as given below.

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {

    let dataEntry = ChartDataEntry(x: Double(i), y: values[i])

    dataEntries.append(dataEntry)

    }

    let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Altitude")

    lineChartDataSet.setColor(UIColor.blue)

    // lineChartDataSet.drawCubicEnabled = true

    lineChartDataSet.mode = .cubicBezier

    lineChartDataSet.drawCirclesEnabled = false

    lineChartDataSet.lineWidth = 1.0

    lineChartDataSet.circleRadius = 5.0

    lineChartDataSet.highlightColor = UIColor.red

    lineChartDataSet.drawHorizontalHighlightIndicatorEnabled = true

    var dataSets = [IChartDataSet]()

    dataSets.append(lineChartDataSet)

    let lineChartData = LineChartData(dataSets: dataSets)

    lineChartView.data = lineChartData


    • Neha

      NehaNeha

      Author Reply

      I have implemented line chart using charts 3.0, can you please tell me how do i set the Xaxis labels now?
      I have done: self.lineChartView.xAxis.enabled = false to disable the top line for xaxis but want to show text on bottom part of Xaxis.


  • sasha zanjani

    Any chance of a Swift 3 update to this very popular tutorial?


  • Amir

    AmirAmir

    Author Reply

    How would I use this library in Swift 3. As the code will not compile unless the syntax is converted but that may cause further problems in the SDK


    • Neha

      NehaNeha

      Author Reply

      For Swift 3, don’t use the pods. Copy the project file to your project.


  • Henry Dang

    Henry DangHenry Dang

    Author Reply

    great, thanks


  • Henry Dang

    Henry DangHenry Dang

    Author Reply

  • saikiran

    saikiransaikiran

    Author Reply

    I don’t have an access to install cocoa pods in my university but i have to display data in graphs. Is this is possible, how?
    thanks in advance


  • Aamir Zakaria

    I wish I could use this, but I cannot get things to work with Swift 3.


  • Aditya Deshmane

    I am facing one issue with PieChart, I have added button below pie chart (not inside pie chart view) but only bottom half of button is clickable. I figured out, it is due to pan gesture of pie chart which is conflicting with button tap. Anyone faced similar issue. Any solution to this?


  • coarist

    coaristcoarist

    Author Reply

    Today 24 Nov 2016, this line
    let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
    ChartDataEntry() does not accept array of string in the first parameter. Available initializers are:
    /// Constructor for stacked bar entries.
    public init(x: Double, yValues: [Double])
    /// Constructor for normal bars (not stacked).
    public init(x: Double, y: Double)
    /// Constructor for stacked bar entries.
    public init(x: Double, yValues: [Double], label: String)
    /// Constructor for normal bars (not stacked).
    public init(x: Double, y: Double, data: AnyObject?)
    For demo, replace the month array with [Double] numbers and make corresponding changes. Having done so, I am able to show the expected bar graph using iPhone.


    • Kevin Zuiker

      So what should it be for this example?


    • Kevin Zuiker

      You say, “For demo, replace the month array with [Double] numbers and make corresponding changes. ”

      Can you please share the code?


    • Kevin Zuiker

      This line of code is causing trouble too:

      let chartData = BarChartData(xVals: months, dataSet: chartDataSet)

      “Cannot invoke initializer ‘BarChartData’ with an argument list of type (xVals: (String), dataSet: BarChartDataSet)”

      What should this be?


      • Alex Cha

        Alex ChaAlex Cha

        Author Reply

        Hi

        did you solve this problem?
        I got a same problem. I use Chart 2.3.

        Thanks,


        • Neelam Pursnani

          I have tried this pod ‘Charts’, ‘~> 2.3’
          for getting let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
          but it’s not working.


          • Chris Navarro

            Chris NavarroChris Navarro

            Author

            Did you solve the problem?


          • Varun yadav

            Varun yadavVarun yadav

            Author

            Even I am having the same issue.


  • Kevin Zuiker

    I keep getting a ‘No such module Charts’ when I use the Import Charts statement.

    When I try to compile, it says there are 138 errors in Charts. I loaded the workspace file. I added the framework in Embedded Binaries. Not sure what’s wrong..

    https://uploads.disquscdn.com/images/22b221e5c124add25ee8537a170860a827ef6a0707da51a9fe9cbc59967db1a8.png https://uploads.disquscdn.com/images/45a136379993a09f20ffd9fa39c1be793c037c2f008a0dbef9713078e1136c27.png
    https://uploads.disquscdn.com/images/b96c06e0651ebca5a3b02a378a521ae826b85c4f15851a85027b1c842bebca37.png


  • Hetal Upadhyay

    Great example again…can you please share example of area chart and line chart with curved and stylish lines like in example images


  • Nelson Ko

    Nelson KoNelson Ko

    Author Reply

    Is the function .SaveToPath still available? I haven’t been able to find it.


  • Morgan May

    Morgan MayMorgan May

    Author Reply

    Can an update to this with the current release of the iOSChart using Swift 3 be posted for this?


  • Gianfranco Percopo

    Fantastic tutorial. Please update it. Not work in swift 3.0. and last library. There is an example:
    change
    BarChartDataEntry(value: values[i], xIndex: i)
    to
    BarChartDataEntry(x: Double(i), y:values[i])


  • Ashish Langhe

    Hello @joyceechessa, please update this blog for Implementation of Charts i.e Bar Chart using Swift 3.0.
    Due to updation in @Daniel Chart Library, we are facing much more problems. One common problem is set xAxis Labels.


    • Awais Fayyaz

      having same problem. how to set x axis labels in swift 3/4


  • विनोद जाधव

    Is this library support to drill down feature?


  • Tobias Zimmermann

    Really nice! Thx


  • Vrushali Jadhav

    I have implemented bar chart using Chart 3.0 library with Swift 3.0. The chart is working fine but I need to remove or hide the values from above the bars. also can I set image as a point on xAxis?


  • Zee Ro

    Zee RoZee Ro

    Author Reply

    Why can’t anyone make a You Tube step by step video to install and use this library. It works great in Androud Studio, but I can’t even install it in IOS ????? HELP.


  • ethanfox27

    ethanfox27ethanfox27

    Author Reply

    This tutorial sucks


  • Ashley Silver

    This is a great library, but I am having trouble getting the xAxis labels to show and I don’t want to use numbers for months. It should be pretty basic to have labels in a simple BarChart. I try initializing each datapoint with a x, a y and a data/lablel as AnyObject but it doesn’t appear. What am I doing wrong?


    • Awais Fayyaz

      having same problem. have you got the solution?


  • Fahad Hussain

    I have problem in BarchartDataset


  • Mr. JD Agrawal

    how to use the Percentage Formatter in Charts API. Just like you used in this image. The values are displayed in percentage format. https://uploads.disquscdn.com/images/f531e81d6a8fd38ccfb0cea7d605ccc9125173182b4634b138dcd7f6124f0a7d.png


  • Zee Ro

    Zee RoZee Ro

    Author Reply

    I am trying to get the index number of a selected bar in the barChart. I cannot get it to work. I know it works because I was able to do it in Android MP Charts. Is there a bug in IOS Charts? or am I not understanding something? Anyone, Please?


  • Zee Ro

    Zee RoZee Ro

    Author Reply

    Then add the following function to the class.

    func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) {
    println(“(entry.value) in (months[entry.xIndex])”)
    }
    1
    2
    3
    func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) {
    println(“(entry.value) in (months[entry.xIndex])”)
    }
    This doesn’t work. Please halp…


  • Brandt Kruger

    Hi. I am still new to IOS. I have updated the X-Code and now it does not compile. Error – Module compiled with Swift 4.0 cannot be imported in Swift 4.0.2.


  • Krishna Ghetiya

    How can I use this library in current swift TVOS project ? I really want to use this.I use Xcode 9.1.


  • shilpashree

    how to design the chart like below?


  • Gago Nersisyan

    Hello thanks for library , i have a little problem with colors, I need to change each bars’ color by their values, I did some but I could change only the whole set color, I want to change one by one


  • Jose Omar Gonzalez

    Thanks.. Can you update this tutorial to the lastest swift and Charts version?


  • Bibhishan Biradar

    hi sir I am bibhishan, I have problem in chart, I want a example to fetch the data from json and add into line chart.


  • MURAT EROL

    MURAT EROLMURAT EROL

    Author Reply

    Is it possible to find and highlight the intersection of x and y axis according to find a data input, I mean can we find the dot and highlight which is our input that meets by the area under the LineChart (gradient fill)

    Thanks…


Shares