Correct data not showing in ios Charts

2019-07-25 18:27发布

Im using Charts Version 3.0.1. Im currently teaching myself Swift by converting my Rails project. I have no knowledge of Objective C so please bear with me; I've done ok so far.

My code below is/may not be formatted correctly as Im missing the days array in the PieChart:

enter image description here

Numbers seem not to be correct. The code:

@IBOutlet weak var chartView: PieChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    let days = ["Mo", "Tu", "Wed", "Thur", "Fri", "Sat", "Sun"]
    let gross = [11.00, 90.95, 250.00, 40.90, 60.88, 99.99, 25.00]

    setChart(dataPoints: days, values: gross)
}

func setChart(dataPoints: [String], values: [Double]) {
    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {

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

    }
    let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Gross Income")
    pieChartDataSet.sliceSpace = 2.0
    let pieChartData = PieChartData(dataSets: [pieChartDataSet]) // somewhere here confuses me.

    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

    chartView.data = pieChartData
}

Have I missed out something? Your second eye would be highly appreciated.

1条回答
够拽才男人
2楼-- · 2019-07-25 19:03

You have changed x & y values and hence index is coming as your pie chart's value. Also, please use PieChartDataEntry. (working code on my box)

  override func viewDidLoad() {
    super.viewDidLoad()
    let days = ["Mo", "Tu", "Wed", "Thur", "Fri", "Sat", "Sun"]
    let gross = [11.00, 90.95, 250.00, 40.90, 60.88, 99.99, 25.00]

    setChart(days: days, gross: gross)
  }

  func setChart(days: [String], gross: [Double]) {
    var dataEntries: [ChartDataEntry] = []

    for i in 0..<days.count {
      let dataEntry = PieChartDataEntry(value : gross[i], label : days[i])
      dataEntries.append(dataEntry)
    }

    let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Gross Income")
    pieChartDataSet.sliceSpace = 2.0
    let pieChartData = PieChartData(dataSets: [pieChartDataSet])

    var colors: [UIColor] = []

    for _ in 0..<days.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
    pieChartView.data = pieChartData
  }

Try this and let me know.

查看更多
登录 后发表回答