How to add string labels( xAxis labels) to horizontal bar in Charts framework

后端 未结 4 1229
囚心锁ツ
囚心锁ツ 2020-12-20 07:52

I am using charts framework for drawing charts. I need to add some strings in left of every bars. In my code always there are two bars, one for Income and o

相关标签:
4条回答
  • 2020-12-20 08:14

    When you create your BarChartDataSet you can pass the label.

    let data = BarChartData()
    let ds1 = BarChartDataSet(values: yse1, label: "Income")
    ds1.colors = [UIColor.red, UIColor.blue]
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-20 08:22

    Charts framework is a great tool for drawing charts. You should study it perfectly. I used an old code in our project (copy/paste), so it caused some problems for drawing xAxis labels in my chart.

    Just comment below line:

        horizontalBarChartView.xAxis.drawLabelsEnabled = false
    
    0 讨论(0)
  • 2020-12-20 08:26
     self.ChartObj.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
                print(index)
                return YourArray.object(at: Int(index)) as! String
            })
     self.ChartObj.xAxis.setLabelCount(YourArray.count, force: true)
    

    Try this code

    0 讨论(0)
  • 2020-12-20 08:27

    I am using an extension for this

    extension BarChartView {
    
        private class BarChartFormatter: NSObject, IAxisValueFormatter {
    
            var labels: [String] = []
    
            func stringForValue(_ value: Double, axis: AxisBase?) -> String {
                return labels[Int(value)]
            }
    
            init(labels: [String]) {
                super.init()
                self.labels = labels
            }
        }
    
        func setBarChartData(xValues: [String], yValues: [Double], label: String) {
    
            var dataEntries: [BarChartDataEntry] = []
    
            for i in 0..<yValues.count {
                let dataEntry = BarChartDataEntry(x: Double(i), y: yValues[i])
                dataEntries.append(dataEntry)
            }
    
            let chartDataSet = BarChartDataSet(values: dataEntries, label: label)
            let chartData = BarChartData(dataSet: chartDataSet)
    
            let chartFormatter = BarChartFormatter(labels: xValues)
            let xAxis = XAxis()
            xAxis.valueFormatter = chartFormatter
            self.xAxis.valueFormatter = xAxis.valueFormatter
    
            self.data = chartData
        }
    }
    

    you can use this in code like this

    chartView.setBarChartData(xValues: xEntries, yValues: yEntries, label: "Income")
    

    where,

    //You need to add values dynamically
    var yEntries: [Double] = [1000, 200, 500]
    var xEntries: [String] = ["Income1", "Income2", "Income3"]
    

    Hope this works.

    0 讨论(0)
提交回复
热议问题