2017-04-05 85 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

添加上下文,而不是代碼。用單詞解釋你的代碼 –

相關問題