如何在iOS图表中的X轴上添加字符串?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (33)

以前的代码是:

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

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

    let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Units Sold")
    let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
    barChartView.data = chartData
}

我可以使用以下行将值传递给数组:

let chartData = BarChartData(xVals: months, dataSet: chartDataSet)

新版本,实现相同的代码是:

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

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

    let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")

    let chartData = BarChartData()
    chartData.addDataSet(chartDataSet)
    barChartView.data = chartData
}

但我找不到修改X轴值的方法

提问于
用户回答回答于

首先,你需要创建一个新类,它将成为你的格式化程序类并添加IAxisValueFormater接口,然后使用stringForValue方法来定制新值,它需要两个参数,第一个参数是实际值(可以看到它索引),其次是值的轴。

import UIKit
import Foundation
import Charts

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter
{
  var months: [String]! = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

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

现在setChart()函数开始的文件中,为格式化程序类和轴类创建两个变量:

let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()

接下来,在for循环结束处继续并将索引和轴传递给你的格式化程序变量:

formato.stringForValue(Double(i), axis: xaxis)

循环后,将格式添加到轴变量中:

xaxis.valueFormatter = formato

最后一步是将新的xax格式添加到barChartView中:

barChartView.xAxis.valueFormatter = xaxis.valueFormatter

用户回答回答于

Swift 3.0中用于X轴标签的解决方案: -

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

barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
//Also, you probably want to add:

barChartView.xAxis.granularity = 1

扫码关注云+社区