Charts: ************* Migrating to Charts 3.0 ********************

Created on 19 Sep 2016  ·  61Comments  ·  Source: danielgindi/Charts

Many have asked about how to migrate to Charts 3.0. So everything will be in the release notes soon as there will be a release, but I will write those down here for now:


This is a major release, with a few breaking changes. So please pay attention.

Updates:

  • x-indexes are dead. Intoducing: x-values. Each entry now has an x and a y.
  • Pie/radar charts do not have a concept of X index anymore
  • Unified XAxis/YAxis features and experience.
  • Unified formatter interfaces for axes.
  • New formatter for y values, not inheriting from NSNumberFormatter anymore, to have dataSet and viewport information to take better formatting decisions.
  • Major refactoring of the Highlight mechanism.
  • Refactored marker mechanism
  • Refactored legend entry mechanism
  • Each dataset can now set its own legend form/size/etc.
  • More demos
  • Some classes have been renamed, keeping the namespaced name only in ObjC (using Swift 2.2 objc(...) feature, and the change of a major version update)
  • FillFormatter now has a block representation using FillFormatter.withblock(...)
  • Same goes for all Default formatters too.
  • No more saveToCameraRoll(). Since Xcode 8.0 it causes "privacy" issues with Apple Review, you have to add the photo albums privacy key to your Info.plist for that.
  • Moved to Swift 3.0. Make sure your project conforms to Swift 3.0.
  • Many minor bug fixes and improvements

Breaking changes / how to migrate:

  • All dataset constructors have changed - they do not take an array of x-indices anymore.
  • All entry constructors have changed - they take in an X and a Y.
  • Pie and Radar chart entries now have their own classes. So exchange the Entry classes withPieChartDataEntry/RadarChartDataEntry
  • If you have any old startAtZeroEnabled calls - these have been deprecated for a long time. Replace them with axisMinimum.
  • If you are using formatters:

    • Replace any chart.valueFormatter = formatter with chart.valueFormatter = ChartDefaultValueFormatter(formatter: formatter) or chart.valueFormatter = [[ChartDefaultValueFormatter alloc] initWithFormatter:formatter];

    • Replace any axis.valueFormatter = formatter with axis.valueFormatter = ChartDefaultAxisValueFormatter(formatter: formatter) or axis.valueFormatter = [[ChartDefaultAxisValueFormatter alloc] initWithFormatter:formatter];

  • In general, all functions that accepted x-indices before, now accept an x-value, so you might have to adjust the names a little bit.
  • Where ChartViewDelegate is implemented, update the chartValueSelected interface
  • Replace drawSliceTextEnabled with drawEntryLabelsEnabled
  • If you have a custom scatter shape - implement an IShapeRenderer, and put your rendering code in there
  • If you have a custom marker - consider subclassing MarkerView/MarkerImage or implementing IMarker. There are more options than before now...
  • If you have used barSpace before, move to using barWidth
  • If you used saveToCameraRoll(), replace with UIImageWriteToSavedPhotosAlbum(chart.getChartImage(trasparent: false), nil, nil, nil)
  • Some classes have been renamed for a cleaner look. They do not contain the "Chart" prefix anymore. That's for Swift only, where there are namespaces. In ObjC the names stayed the same for the sake of namespacing, using Swift 2.2's feature of @objc(name). If your compiler yells that a class does not exist, try to remove the Chart from its name. This should rarely happen, as we've chosen only the classes that are rarely instantiated by the user.

Most helpful comment

@Carielle To install Charts 3.0.0 before it is compatible with CocoaPods, remove the old Charts from your pod file and your project, and then download the Charts.xcodeproj file from this github page.

Then open your target project in XCode and drag the Charts.xcodeproj file from the directory it downloaded to into your project in the XCode interface.

After that, add Charts.framework in the "Embedded Binary" section of your project's General Settings.

All 61 comments

@danielgindi Support cocoapods?

@danielgindi can i still copy those classes to my project like before?

Not yet in Cocoapods. As I've said it's not released yet.

Yes you can copy it the classes like before. However it's more comfortable to drag the xcodeproj to the project. It's not recommended to drag the sources themselves, as this will make updating Chrats in your project more difficult.

@danielgindi
Thanks for great job!

Now I have a issue, I notice that x-indexes are dead:

- x-indexes are dead. Intoducing: x-values. Each entry now has an x and a y.
- In general, all functions that accepted x-indices before, now accept an x-value,   
   so you might have to adjust the names a little bit.

Then how can I show string(for example, a date string) on xAxis rather than float number(like 1.0, 2.0 ...)?

Answer by Daniel:

Get the NSTimeInterval of a date, NSTimeInterval is actually a double. Then Use formatter to custom it.

Can't wait for the release! 👍

@danielgindi Since I updated to XCode 8.0, my project won't build because I have Charts installed via cocoapods and it's still using a legacy version of Swift. How soon can we expect a release of Charts 3.0, or what can I do to resolve these errors in the meantime? Thanks for all your efforts.

Point your podfile to master branch instead of a version for now

@petester42 Thanks for the tip, however, I can't seem to get it to work. Changed my podfile to pod 'Charts', :git => 'https://github.com/danielgindi/Charts.git', :branch => 'master' and ran pod install. The output looked like this:
snip20160919_3
But then I still got the "Use Legacy Swift Language Version" error when I tried to run the project:
snip20160919_1

Any more helpful hints?

@Carielle To install Charts 3.0.0 before it is compatible with CocoaPods, remove the old Charts from your pod file and your project, and then download the Charts.xcodeproj file from this github page.

Then open your target project in XCode and drag the Charts.xcodeproj file from the directory it downloaded to into your project in the XCode interface.

After that, add Charts.framework in the "Embedded Binary" section of your project's General Settings.

@ALL do check #1291 for swift 2.3 & 3.0 issues

Point out a mistake in Migrating description :
If you are using formatters:

  • Replace any chart.valueFormatter = formatter with chart.valueFormatter = ChartDefaultValueFormatter(formatter: formatter) or chart.valueFormatter = [[ChartDefaultValueValueFormatter alloc] initWithFormatter:formatter];
  • Replace any axis.valueFormatter = formatter with axis.valueFormatter = ChartDefaultAxisValueFormatter(formatter: formatter) or axis.valueFormatter = [[ChartDefaultAxisValueValueFormatter alloc] initWithFormatter:formatter];

I'm getting the same as @Carielle, will try what @HenryAlkire said

captura de tela 2016-09-20 as 09 38 38

What branch are you using?

@rrecio It can't be.. I fixed this like a few days ago.

I was using regular cocoapod setup: pod 'Charts'

To fix it I removed the Podfile entry and linked Charts.framework manually as @Henry explained

Enviado do meu iPhone

Em 20 de set de 2016, às 21:59, Xuan [email protected] escreveu:

@rrecio It can't be.. I fixed this like a few days ago.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

Any idea about when it will be available on Cocoapods ?

How do I upgrade Charts to work with Xcode 8.0 and Swift 3.0 using Carthage?

When I run "carthage update", it's still pulling Charts 2.3.0. My Cartfile is configured to use the latest version.

Cartfile:

github "danielgindi/Charts"

Command line:

$carthage update
** Cloning Charts
*
* Cloning Result
** Cloning realm-cocoa
*
* Checking out Charts at "v2.3.0"

@danielgindi
It would be great if you include this features..As this features are supposed to be in major of the library ...especially in High Charts:

1) line graph with different markers shape
https://github.com/danielgindi/Charts/issues/1405

2) Able to add custom view in specific locations in x-axis.Customization of background colors is missing in major of the views.
https://github.com/danielgindi/Charts/issues/1416

Carthage uses the latest release version. If you want 3.0 (which isn't released yet) use github "danielgindi/Charts" "master"

Download Full project using master branch and then drag and drop Charts.xcodeproj and then go to General tab and add Charts.framework under Embedded Binaries after Clean and build so you can see all error are gone just try it. in case you required any help comment it i'll help you. @petester42 @Huang-Libo

@HenryAlkire I did what you suggested and removed Charts from my podfile and dragged and dropped it manually into my project, and added it as an embedded binary. However, when I try to build the project I keep getting this error:
dyld: Library not loaded: @rpath/libswiftCore.dylib Reason: image not found
It seems to be referenced from the Charts.framework/Charts. Any idea how to solve this issue?

I solved my own problem - my project is an Objective-C project using the Swift Charts library, so I had to go to Build Settings > Build Options > "Always Embed Swift Standard Libraries" and set it to YES. This replaces the deprecated "Embedded Content Contains Swift" flag.

@Carielle Also can see this issue https://github.com/danielgindi/Charts/issues/1487

@danielgindi Is it possible to estimate a Cocoa Pods release for Charts 3? 1-2 Weeks or more like a month?

Thanks for your efforts 👍

You can use charts 3 with cocoapods right now by pointing to the master branch. We can't guarantee that is going to be stable since it is not final.

@petester42 Iam providing a framework pod which has a dependency in the pod spec to Charts. Unfortunately you can not point to other repository or branches in pod specs like in Pod files. I could overwrite my Podfile for my example project, but this is not distributable. So i am locked for now to Swift 2.2. But thanks for the tip :)

Update for others using charts 3 with Cocoapods

I'm working on migrating a project from Swift 2.2 and Xcode 7 to Swift 3.0 and Xcode 8.0. Following the approach of @Carielle -- and as @petester42 mentions above -- charts 3 can be installed with cocoapods.

Modifying the podfile to have:

pod 'Charts', :git => 'https://github.com/danielgindi/Charts.git', :branch => 'master'

led to the following for me (October 1st, 2016)

screen shot 2016-10-01 at 7 00 20 pm

Nevertheless, there are still some build time issues which I'm working through, as is to be expected until the final version is released.

For instance, plotView.xAxis.setLabelsToSkip(10) causes trouble since the setLabelsToSkip method is now not recognized. Can I assume this is temporary while the final version is being worked on, or is there some other method I should be using?

Thanks @danielgindi and others for your great work! I'd be eager to help contribute to the migration documentation as I learn by adapting my own project.

Before update iOS chart to 3.0 version, i can
let radarChartData = RadarChartData(xVals: dataPoints, dataSet: radarChartDataSet)

however, after upgrade, can't set xVals in RadarChartData, only
let radarChartData = RadarChartData(dataSet: radarChartDataSet)

How can I set xVals in newest version. I had try to
dataEntry = RadarChartDataEntry(value: Double(cleaningValue), data: "setTitle" as AnyObject?)
but not work, I had searched many document, but can't find how to do that, could you give me a example for that, thanks advise.

@AnChiChang please read the notes above thoroughly.

thanks, understand through ticket 1496

how can I format the x-values from double array to string array in v3.0 ?

@bingozb please look at the demos

google

var a:Double = 1.5
var b:String = String(format:"%f", a)
print("b: (b)") // b: 1.500000

@danielgindi I use the line chart 1, and I had seen the demo and found nothing about it.

NSMutableArray *values = [[NSMutableArray alloc] init];
[values addObject:[[ChartDataEntry alloc] initWithX:i y:val]];
LineChartDataSet *set1 = [[LineChartDataSet alloc] initWithValues:values label:@"xxx"];

the demo just use double x-values. ChartDataEntry have no init method that i can send string parameter.
Well, I saw the issues and found one said that we can send the integerValues of date, then format it back and display to the x label. But I can't find some method about this. I not sure it can work by this way actually.
help me please. I need to show the date to the x Axis.

Hello @bingozb

I hope your X values store in one array so pls do this kind of,

NSMutableArray *xVals;

  • (NSString *)stringForValue:(double)value
    axis:(ChartAxisBase *)axis
    {
    if (xVals.count>0){
    return xVals[(int)value % xVals.count]; // this calculation base on you want to display.
    }
    return nil;
    }

I hope you are understand.

@rs10693 Yes, I find this protocol method. It seems that I have to implement it. But I find no delegate was comply the IChartAxisValueFormatter protocol. Who should comply with this protocol and where to implement this method. I let my controller do this but it does't work.

@bingozb Use ChartViewDelegate and IChartAxisValueFormatter and i hope you @import Charts;

@rs10693 Oh, I see! the delegate is valueFormatter...

@bingozb what can you say i don't understand. plz elaborate me.

@danielgindi i am still not able to install Charts 3.0.0

Following error occurs when run pod install
Analyzing dependencies
[!] Unable to satisfy the following requirements:

  • Charts (~> 3.0.0) required by Podfile

None of your spec sources contain a spec satisfying the dependency: Charts (~> 3.0.0).

You have either:

  • out-of-date source repos which you can update with pod repo update.
  • mistyped the name or version.
  • not added the source repo that hosts the Podspec to your Podfile.

Note: as of CocoaPods 1.0, pod repo update does not happen on pod install by default.

Please help does it means that Charts 3.0.0 is not released yet to install by using

or am i missing any step.

3.0 is not yet in cocoapods because it's not final. You can point to the git repo and master to get 3.0 right now

We have now released 3.0.0!

Thats great to know.

But i am a bit worried do we need to update our cocoa pod or it's repository for installing newly released 3.0.0

woot 🎉

@danielgindi you need me to push the pod or you got that covered?

Tried, now after a long time, said that the podspec does not validate...

Ya it takes a while. I can do it. You need cocoapods 1.1 to work with Xcode 8/swift 3

@petester42 @danielgindi
I have
pod --version = 1.1.0

but still the pod install command installs older version.

Analysing dependencies
Downloading dependencies
Installing Charts (2.3.0)

Please guide

It's working now after updating the master repo of pod thanks for help

Getting such error in Swift 3.0, while implementing Bar Graph using this library.

screen shot 2017-01-11 at 1 22 48 pm

After resolving above error, it gives next error as shown below.

screen shot 2017-01-11 at 12 57 26 pm

How do I resolve such error in Swift 3.0?

let chartDataSet = BarChartDataSet(values: dataEntries, label: nil)
let chartData = BarChartData(dataSet: chartDataSet)

about xVals, you have to implement stringForValue.

Thanks. how should I implement stringForValue for xVals.

Please provide swift 3 examples

Hello,
I just migrated from the 2 to the 3 (I am using the 3.0.2) and I am running into 2 issues :

  • If I have 0 values in my dataset, the bar graph is being shifted , this is weird and I pretty much use the code of the demo samples. Any idea ?
  • Is there a way to hide the 0 values a together and just show the values that are > 0 ?

Thank you for the input.

screen shot 2017-06-09 at 12 15 13 pm
screen shot 2017-06-09 at 12 13 47 pm

in class BarChartRenderer
in open override func drawValues(context: CGContext)
add line 408
```
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }

                    let rect = buffer.rects[j]

                    let x = rect.origin.x + rect.size.width / 2.0

                    if !viewPortHandler.isInBoundsRight(x)
                    {
                        break
                    }
                    if !viewPortHandler.isInBoundsY(rect.origin.y)
                        || !viewPortHandler.isInBoundsLeft(x)
                    {
                        continue
                    }

                    let val = e.y
                    if val == 0                            <-----------this line
                    {                                           <-----------this line
                        continue                         <-----------this line
                    }                                          <-----------this line

```

add a variable if you want
var drawValuesZeroEnabled: Bool { get set }

Thank you Thierry.
So that's fixed :)

I still have the issue of that weird spacing.

So I just created a default bar chart with a 0 value and I still have the issue - I tried to get as close as possible to a simple bar to see what was the issue.

It looks like the demo but a soon as I put a value between 0 and 0.9999 I get that padding.

Here the sample code :

    @IBOutlet var barChartView: BarChartView!

 func viewDidLoad() {
        super.viewDidLoad()
         self.styleChart()
         self.configureChart()
    }

    internal func styleChart() {
        self.barChartView.xAxis.labelPosition = .bottom
        self.barChartView.xAxis.labelCount = 2
    }

    internal func configureChart() {

        var xValues = [String]()
        var entries: [ChartDataEntry] = Array()

         xValues.append("TEST 5")
         xValues.append("TEST 0")
         entries.append(BarChartDataEntry(x: Double(0), y: Double(5) ))
         entries.append(BarChartDataEntry(x: Double(1), y: Double(0) ))


        let dataSet = BarChartDataSet(values: entries, label: "")
        dataSet.drawIconsEnabled = false
        dataSet.drawValuesEnabled = true

        let formatter = NumberFormatter()
        formatter.numberStyle = NumberFormatter.Style.decimal
        dataSet.valueFormatter = DefaultValueFormatter(formatter: formatter)

        let barChartData = BarChartData(dataSet: dataSet)
        barChartData.barWidth = 0.2        
         self.barChartView.data = barChartData
    }

Pretty straightforward.

It is a bug ?

Issue with 0 :
screen shot 2017-06-12 at 11 55 15 am

No 0 :
screen shot 2017-06-12 at 12 21 20 pm

Thank you for the help ;)

Where I can find docs about old API for Charts ? I never used this framework (aside from upgrading it few times) and I have to upgrade from 2.3 to 3.0.4, so old docs would be nice to figure out old code, eg:

[entrySet addObject:[[ChartDataEntry alloc] initWithValue: item.avgSpeed xIndex:index]];

Now, there is no init called initWithValue: xIndex, but rather there is init called:

initWithX: y: , so I am trying to figure out what were old parameters, and how to use new init to achieve the same result...

Also the valuesObjc array is missing now:

//myLineChartView is LineChartView
 NSDate* date = (NSDate*)[myLineChartView.xAxis.valuesObjc objectAtIndex:index];

As I said, I never used this framework, so some help would be appreciated, or at least link to old API docs would be helpful...

I don’t think such resource exists. You can check the legacy/2.3 branch to check the demos and such to compared with other hthe current version.

BarChartData.init(xVals: xVals, dataSets: dataSets) can not work. what is replace it?

How can I scroll the x value of line chart to the center programatically?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guoyutaog picture guoyutaog  ·  3Comments

brytnvmg picture brytnvmg  ·  4Comments

Aungbandlab picture Aungbandlab  ·  4Comments

anhltse03448 picture anhltse03448  ·  3Comments

coop44483 picture coop44483  ·  3Comments