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

PieChart: Identify univocally a specific entry #2513

Closed
gmoraleda opened this issue Jun 11, 2017 · 1 comment
Closed

PieChart: Identify univocally a specific entry #2513

gmoraleda opened this issue Jun 11, 2017 · 1 comment

Comments

@gmoraleda
Copy link

gmoraleda commented Jun 11, 2017

While using the Charts library I'm having problems identifying an entry. I have an array of categories and an array of amounts in order to build a pie chart. When I tap an entry, I want to show the amount and the name of the category:

var cats: [String]! = ["Transport","Shopping","Food","Accomodation","Fun","Other"]
var expensesArray = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

I fetch the values from Core Data:

func requestExp() {
        noExpView.isHidden = true
        pieChartView.isHidden = false

        total = 0
        trans = 0.0
        shop = 0.0
        food = 0.0
        acc = 0.0
        fun = 0.0
        other = 0.0

        // Create Fetch Request
        let fetchRequest: NSFetchRequest<Expense> = Expense.fetchRequest()
        // Create Predicate
        let predicate = NSPredicate(format: "%K >= %@ AND %K <= %@", argumentArray:["date", fromDate, "date", toDate])
        fetchRequest.predicate = predicate
        // Execute Fetch Request
        do {
            let result = try context.fetch(fetchRequest)

            for managedObject in result {
                if let amount = managedObject.value(forKey: "amount"), let currency = managedObject.value(forKey: "currency")
                {
                    switch managedObject.value(forKey: "Category") as! String {
                        case "Transportation":
                            trans+=amount as! Double
                        case "Shopping":
                            shop+=amount as! Double
                        case "Food":
                            food+=amount as! Double
                        case "Accomodation":
                            acc+=amount as! Double
                        case "Fun":
                            fun+=amount as! Double
                        case "Other":
                            other+=amount as! Double
                    default:
                            break
                    }
                    print("\(amount) \(currency)")
                    total+=amount as! Double
                }
            }
            expensesArray = [trans, shop, food, acc, fun, other]
            print("Total for "+dateFormatter.string(from: fromDate)+" to "+dateFormatter.string(from: toDate)+" = "+String(total))

            let final = formatter.string(from: total as NSNumber)
            totalLabel.text = final
            let dayAverage = total / calcDays()
            average.text = formatter.string(from: dayAverage as NSNumber)
            average.isHidden = false

            if total==0 {
                pieChartView.isHidden = true
                noExpView.isHidden = false
            }

        } catch {
            let fetchError = error as NSError
            print(fetchError)
        }

    }

    func setChart(dataPoints: [Double]) {
        
        
        var dataEntries: [ChartDataEntry] = []
        
        for i in 0..<dataPoints.count {
            let dataEntry = PieChartDataEntry(value: Double(dataPoints[i]), label: cats[i])
            dataEntries.append(dataEntry)
        }

        let pieChartDataSet = PieChartDataSet(values: dataEntries, label: nil)
        pieChartDataSet.colors = colors
        pieChartDataSet.drawValuesEnabled = false
        let data = PieChartData(dataSet: pieChartDataSet)
        pieChartView.data = data
        pieChartView.noDataText = "No data available"
        pieChartView.notifyDataSetChanged()

    }

This is my method to update the label which shows the category name. It doesn't work when I have 2 entries with the same value (since I'm using indexof, it shows the first one it finds in the array...) and I don't know how to address the issue:

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        let style = NSMutableParagraphStyle()
        style.alignment = NSTextAlignment.center
        let centerText = NSMutableAttributedString()
        let category = NSMutableAttributedString(string: cats[expensesArray.index(of: entry.y)!] , attributes: [NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName:UIColor.black,NSFontAttributeName: UIFont(name: "GillSans",size:19)!])
        let amount = NSMutableAttributedString(string: "\n"+formatter.string(from: entry.y as NSNumber)!, attributes: [NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName:UIColor.black,NSFontAttributeName: UIFont(name: "GillSans",size:20)!])
        centerText.append(category)
        centerText.append(amount)
        pieChartView.centerAttributedText = centerText
    }

Thumbs up for this great library and thanks in advance for your help!

@gmoraleda
Copy link
Author

gmoraleda commented Jun 12, 2017

Found the solution accessing directly the ChartDataEntry objects:
entry as! PieChartDataEntry).label
so, the whole chartValueSelected looks like this:

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        let style = NSMutableParagraphStyle()
        style.alignment = NSTextAlignment.center
        let centerText = NSMutableAttributedString()
        let category = NSMutableAttributedString(string: (entry as! PieChartDataEntry).label!
, attributes: [NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName:UIColor.black,NSFontAttributeName: UIFont(name: "GillSans",size:19)!])
        let amount = NSMutableAttributedString(string: "\n"+formatter.string(from: entry.y as NSNumber)!, attributes: [NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName:UIColor.black,NSFontAttributeName: UIFont(name: "GillSans",size:20)!])
        centerText.append(category)
        centerText.append(amount)
        pieChartView.centerAttributedText = centerText
    }

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

1 participant