Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get back x-values for BarChart[Charts 3 migration problem] #1688

Closed
patreu22 opened this issue Oct 20, 2016 · 22 comments
Closed

How to get back x-values for BarChart[Charts 3 migration problem] #1688

patreu22 opened this issue Oct 20, 2016 · 22 comments

Comments

@patreu22
Copy link

Hello,

I'm trying to get started with Charts 3 but I've got some migration problems.
That old Charts code created a Bar Chart with a history for right and wrong answered questions and writing the Day on the top over the belonging Bar.

img_0771

I've built it with the following code:

            let examHistoryChartFrame = CGRectMake(scrWidth*0.08, 24 + scrWidth*1.68 , scrWidth*0.84, scrWidth*0.84)
            let examHistoryView = BarChartView(frame: examHistoryChartFrame)

            examHistoryView.descriptionText = ""
            examHistoryView.userInteractionEnabled = false
            //  historyBarChartView.xAxis.valueFormatter = NSNumberFormatter()
            examHistoryView.rightAxis.enabled = false
            let formatter = NSNumberFormatter()
            formatter.minimumFractionDigits = 0
            examHistoryView.leftAxis.valueFormatter = formatter
            examHistoryView.drawHighlightArrowEnabled = true
            examHistoryView.drawValueAboveBarEnabled = false
            examHistoryView.xAxis.drawGridLinesEnabled = false

           //...getting the data in some way....

           var counter = 0
           let fi = getDataEntries(dataPoints, values: firstValues, counter: counter)
           counter += 1
           let sec = getDataEntries(dataPoints, values: secondValues, counter: counter)
           dataPoints = transformDataPoints(dataPoints)
           examHistoryView.data =  BarChartData(xVals: dataPoints, dataSets: [fi,sec])

The getDataEntries(...) function does the following:


    func getDataEntries(dataPoints: [String], values: [Double], counter: Int) -> BarChartDataSet{
        var dataEntries: [ChartDataEntry] = []
        for i in 0..<dataPoints.count {
            let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
            dataEntries.append(dataEntry)
        }
        let ret = BarChartDataSet(yVals: dataEntries)
        ret.drawValuesEnabled = false
        switch counter{
            case 0:
                ret.colors = [GREEN]
                ret.label = "Richtig beantwortet"
                break
            case 1:
                ret.colors = [RED]
                ret.label = "Falsch beantwortet"
                break
            default:
                break
        }
        return ret
    }

After the update I've tried everything to bring the Dates back to the Chart but I can't make it.

Does anybody know which attribute I should manipulate for achieving my goal?

Thanks for your help!
Patrick

@acegreen
Copy link

did you figure this out?

@patreu22
Copy link
Author

Nope, didn't get it

Am 24.10.2016 um 23:22 schrieb Ace Green <notifications@github.commailto:notifications@github.com>:

did you figure this out?

You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHubhttps://github.com//issues/1688#issuecomment-255869865, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AK1gNdZILGok2Rgm0xO085WjswkB-iroks5q3SF0gaJpZM4KcIMy.

@GLianwei
Copy link

same problem. not figure out yet

@patreu22
Copy link
Author

@danielgindi Any idea how to solve that problem?

@cbalsalobre
Copy link

I'm really interested on this, need categories (strings) on the x-Axis, not doubles

@cupid-stunt
Copy link

Same here! very frustrating. I appreciate the work that has been put into this but i'm considering using another charts project because of the x-axis problem.

@liuxuan30
Copy link
Member

liuxuan30 commented Oct 27, 2016

I don't know if you read the release notes or played with ChartsDemo, but x axis no longer works as index based one. Not it works like y axis.

For example, the Bar chart in ChartsDemo did exactly what you need.
ChartsDemo have so many demos for you to refer.

If you want to have strings, just conform to IChartAxisValueFormatter and write a formatter to format them to strings.
Don't forget to set xAxis.centerAxisLabelsEnabled = YES.

If you want to sure every x axis label, set labelCount = your x vals count

It's a big change indeed, but I believe the new x axis is more flexible to use.

@GLianwei
Copy link

GLianwei commented Oct 27, 2016

Here is my problem. My barchart has grouped bars. I want to set a x-string for each group yet do not know how. Tried axisformatter.

@patreu22
Copy link
Author

patreu22 commented Nov 1, 2016

My solution was a custom Formatter that inherits from AxisFormatter. Then you can set your x-axis values to count from 0 to z. Now you hand over your x-strings as a [String] and can set the right through the values. Hope that helps you.

@acegreen
Copy link

acegreen commented Nov 1, 2016

@patreu22 can you add some sample code to show this?

@patreu22
Copy link
Author

patreu22 commented Nov 1, 2016

Thats my code XAxisFormatter:

import Foundation
import Charts

public class XAxisFormatter: NSObject, IAxisValueFormatter {

    var dates: [String]
    /// Called when a value from an axis is formatted before being drawn.
    ///
    /// For performance reasons, avoid excessive calculations and memory allocations inside this method.
    ///
    /// - returns: The customized label that is drawn on the x-axis.
    /// - parameter value:           the value that is currently being drawn
    /// - parameter axis:            the axis that the value belongs to
    ///

   //swap the dates array with your x-axis-Strings
    init(dates: [String]){
        self.dates = dates
    }

    public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        let valStr = dates[Int(value)]

       //do Formatting
        return "\(day). \(newMonth)"

    }

And that's the code how I formatted the xAxis:

            let dateFormatter = XAxisFormatter(dates: dataPoints)
            historyBarChartView.xAxis.granularity = 1
            historyBarChartView.xAxis.labelCount = dataPoints.count
            historyBarChartView.xAxis.drawGridLinesEnabled = false
            historyBarChartView.drawValueAboveBarEnabled = true
            historyBarChartView.xAxis.valueFormatter = dateFormatter

For that solution its important that your x-values iterate from 0 to z.
I know, it's not the most beautiful solution but at least it works pretty straight.

Hope that helps!

@acegreen
Copy link

acegreen commented Nov 1, 2016

@patreu22 it does, thanks for this. Managed to test this out and get it working. Now I have to deal with formatting the font it seems. How did you deal with overlapping labels?

Sometimes change for the sake of change isn't good. How is subclassing a formatter easier than just passing an array directly like before? I can see this as a customization option for advanced usage but the older way should have still remained.

@patreu22
Copy link
Author

patreu22 commented Nov 1, 2016

For the Font-Problem, does xAxis.labelFont helps you?

I don't have a problem with overlapping labels..maybe "\n" is a solution?
Btw your UI looks very fancy! :)

@acegreen
Copy link

acegreen commented Nov 1, 2016

Yea I already had labelFont.. I think it would work if that second unexpected "Buy" label wasn't there.

Oh thats my app StockSwipe. What are you working on?

@patreu22
Copy link
Author

patreu22 commented Nov 1, 2016

On a little Education App that also features learning statistics... I hope you can figure it out!

@acegreen
Copy link

acegreen commented Nov 1, 2016

Vielen dank :) .. So it turns out that duplicate is because the values are not equal the number of datasets.

Edit:
Setting the granularity causes it to increment by one. Weird things happening here. Why would you need to set this if the datasets count is known and formatter values count is also known.

Seems Chart 3.0 is designed for maximum customization and advanced usage but this makes basic usage not easy.

chartView.xAxis.granularity = 1

@dbmrq
Copy link

dbmrq commented Nov 21, 2016

@acegreen I have a similar problem, the first label is duplicated and I can't figure out why. What do you mean by "the values are not equal the number of datasets"?

@acegreen
Copy link

@dbmrq by that I mean I meant that I had for example 4 dataset points, but the x values were 5, or so I thought. It turns out that if you bring the value in your subclass it will be something like 0 0 1 2 3 instead of 0 1 2 3 4.

i don't know why the first label is duplicated but if you read my edit, setting the granularity = 1 fixed the problem.

@danielgindi
Copy link
Collaborator

Note that in Charts 3.0.1 there's an IndexAxisValueFormatter that you can pass an array of labels and have them behave like in Charts 2.0

@dbmrq
Copy link

dbmrq commented Nov 21, 2016

@acegreen Ah, ok, now I get it. Thanks!

@danielgindi Oh, now I'll have to remove all those IAxisValueFormatter classes I just implemented, haha. Thanks! :)

@patreu22
Copy link
Author

Oh no, that hint would have been a real time-saver for me @danielgindi haha

Am 21.11.2016 um 19:08 schrieb Daniel Marques <notifications@github.commailto:notifications@github.com>:

@acegreenhttps://github.com/acegreen Ah, ok, now I get it. Thanks!

@danielgindihttps://github.com/danielgindi Oh, now I'll have to remove all those IAxisValueFormatter classes I just implemented, haha. Thanks! :)


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHubhttps://github.com//issues/1688#issuecomment-262018947, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AK1gNW6ZzcQMNhve8G1wO_oMBGFbnMgbks5rAd4fgaJpZM4KcIMy.

@liuxuan30
Copy link
Member

I will add this IndexAxisValueFormatter in the 3.0.1 release notes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants