如何使用图表在 X 轴上显示每个月 (IOS)

How to display each month on X Axis using Charts (IOS)

我尝试使用图表,但我无法在 X 轴上显示每个月,只能显示一个。看看picture。

stringForValue 中,我尝试打印值并显示:0 2 4 6 8 10 0 1 2 3 4 5 6 7 8 9 10 11 0 2 4 6 8 10 但是为什么它通过了三次,第一次和最后一次通过了一次?我可以做什么来显示每个月?

import UIKit

import Charts

class BarChartViewController: UIViewController {

    var months = [String]()
    var unitsSold = [Double]()

    weak var axisFormatDelegate: IAxisValueFormatter?

    @IBOutlet weak var barChartView: BarChartView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        axisFormatDelegate = self

        months = ["Jan",
                  "Feb",
                  "Mar",
                  "Apr",
                  "May",
                  "Jun",
                  "Jul",
                  "Aug",
                  "Sep",
                  "Oct",
                  "Nov",
                  "Dec"
        ]

        unitsSold = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0]

        setChart(dataPoints: months, values: unitsSold)


    }

    func setChart(dataPoints: [String], values: [Double]) {
        barChartView.noDataText = "NO DATA"

        var dataEntries = [BarChartDataEntry]()

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

            dataEntries.append(dataEntry)
        }

        let chartDataSet = BarChartDataSet(entries: dataEntries, label: "Units Sold")
        let chartData = BarChartData(dataSet: chartDataSet)

        barChartView.data = chartData

        barChartView.xAxis.valueFormatter = axisFormatDelegate
    }


}

extension BarChartViewController: IAxisValueFormatter {

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {

        print(Int(value))

        return months[Int(value)]
    }  
}

您至少有两种选择可以解决您的问题。

只需为 xAxis 设置 属性 labelCount,例如barChartView.xAxis.labelCount = 12.

或用户方法setLabelCount(:),例如barChartView.xAxis.setLabelCount(12, force: true).

请注意,使用 属性 labelCount 并不能保证标签的数量完全等于您指定的数量。