2017-04-05 84 views
1

我试图让线图中的数据点标签显示自定义字符串,而不是实际的数字(使用iOS图表/图表库)。我想知道是否有像我用来格式化我的x和y轴标签的IAxisFormatter。如何在iOS图表中自定义数据点标签?

我想知道是否有人知道如何在Swift中做到这一点?我似乎无法在网上找到任何示例。谢谢!

回答

4

您必须将IValueFormatter协议附加到您的ViewController并实施stringForValue(_:entry:dataSetIndex:viewPortHandler:)方法(1)。

然后将ViewController设置为图表数据集(2)的valueFormatter委托。

import UIKit 
import Charts 

class ViewController: UIViewController, IValueFormatter { 

    @IBOutlet weak var lineChartView: LineChartView! 

    // Some data 
    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
    let unitsSold = [20.0, 4.0, 3.0, 6.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0] 

    // (1) Implementation the delegate method for changing data point labels. 
    func stringForValue(_ value: Double, 
         entry: ChartDataEntry, 
         dataSetIndex: Int, 
         implement delegate methodviewPortHandler: ViewPortHandler?) -> String{ 

     return "My cool label " + String(value) 
    } 

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

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

     let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold") 
     let lineChartData = LineChartData(dataSets: [lineChartDataSet]) 

     // (2) Set delegate for formatting datapoint labels 
     lineChartData.dataSets[0].valueFormatter = self 

     lineChartView.data = lineChartData 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     setChart(dataPoints: months, values: unitsSold) 
    } 
} 
+0

是的,我使用的类似的方法获取我的轴标签。我想我的问题可能不清楚;我试图找到如何编辑数据点上的实际标签,如果可能的话。谢谢你的回答! – holycamolie

+1

@holycamolie,我明白了。我改变了我的答案。您需要使用stringForValue(_:entry:dataSetIndex:viewPortHandler :)方法实现IValueFormatter协议。并将其设置为图表数据集的valueFormatter委托。 – AlexSmet

0
在我的情况下我的数据集具有Y的值

,x是指数

后组轴线

enter image description here

// this shows date string instead of index 
let dates = ["11/01", "11/02", "11/03", "11/04"...etcs] 
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:months) 

enter image description here

+0

请给你的答案添加一些上下文。 SO上仅有代码回答并不被视为“高质量帖子”。花点时间写1-2个句子,说明为什么以及如何解决问题 –

+0

如果我把太多的代码看起来会使答案复杂化。所以我认为在这里保留答案更简单。 –

+0

添加上下文,而不是代码。用单词解释你的代码 –

相关问题