How to add labels for XAxis for BarChartView in io

2019-04-29 08:33发布

问题:

I added a bar chart to the storyboard, but I cannot properly set labels for my data entries.

here is my code:

var names = ["aaa", "bbb", "ccc", "ddd"]
var values = [230.0, 280.0, 450.0, 340.0]

setChart(dataPoints: names, values: values)

setChart function:

func setChart(dataPoints: [String], values: [Double])
{
    let formatter = BarChartFormatter()
    formatter.setValues(values: dataPoints)
    let xaxis:XAxis = XAxis()


    barChartView.noDataText = "You need to provide data for the chart."
    var dataEntries: [BarChartDataEntry] = []

    for i in 0..<dataPoints.count
    {
        let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
        dataEntries.append(dataEntry)
    }

    let chartDataSet = BarChartDataSet(values: dataEntries, label: "موجودی")

    let chartData = BarChartData(dataSet: chartDataSet)


    xaxis.valueFormatter = formatter
    barChartView.xAxis.labelPosition = .bottom
    barChartView.xAxis.drawGridLinesEnabled = false
    barChartView.xAxis.valueFormatter = xaxis.valueFormatter
    barChartView.chartDescription?.enabled = false
    barChartView.legend.enabled = true
    barChartView.rightAxis.enabled = false
    barChartView.data = chartData
}

and finally the formatter:

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter
{
    var names = [String]()

    public func stringForValue(_ value: Double, axis: AxisBase?) -> String
    {
        return names[Int(value)]
    }

    public func setValues(values: [String])
    {
        self.names = values
    }
}

but it didn't work well as shown below:

as shown here, it add 6 labels instead 4 labels, and it also has duplicates.

I already read this solution, however, as you can see, it has some issues yet.

How can I solve this problem?

回答1:

I think you can try to set the following properties:

barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1.0 //default granularity is 1.0, but it is better to be explicit
barChartView.xAxis.decimals = 0

The source code tells you a lot about the properties above. https://github.com/danielgindi/Charts/blob/master/Source/Charts/Components/AxisBase.swift