一个图表上具有不同点数的多个数据集(iOS-Charts)

时间:2015-09-06 21:49:28

标签: xcode swift ios-charts

当我尝试在同一个图表上使用不同数量的数据点放置两行时,我遇到iOS图表问题。我在下面粘贴了我的测试代码。

    testLineChartView.delegate = self
    testLineChartView.xAxis.enabled = true
    testLineChartView.xAxis.labelPosition = .Bottom
    testLineChartView.rightAxis.drawLabelsEnabled = false

    var allLineChartDataSets: [LineChartDataSet] = [LineChartDataSet]()

    var dataEntries: [ChartDataEntry] = []
    let dataPoints = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
    let values = [18.0, 4.0, 6.0, 3.0, 12.0, 16.0, 30]
    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
        println(dataPoints[i])
    }

    let lineChartDataSet1: LineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Temperature")
    allLineChartDataSets.append(lineChartDataSet1)


    var dataEntries2: [ChartDataEntry] = []
    let dataPoints2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Aug"]
    let values2 = [21.0, 5.0, 7.0, 10.0, 11.0, 18.0, 20]
    for i in 0..<dataPoints2.count {
        let dataEntry2 = ChartDataEntry(value: values2[i], xIndex: i)
        dataEntries2.append(dataEntry2)
        println(dataPoints2[i])
    }

    let lineChartDataSet2 = LineChartDataSet(yVals: dataEntries2, label: "Units Sold")
    lineChartDataSet2.setColor(UIColor.redColor())
    lineChartDataSet2.setCircleColor(UIColor.redColor())
    allLineChartDataSets.append(lineChartDataSet2)

    let allDataPoints: [String] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"]

     let lineChartData = LineChartData(xVals: allDataPoints, dataSets: allLineChartDataSets)

    testLineChartView.data = lineChartData

以下是生成的图表: enter image description here

如您所见,数据集2的8月条目显示为7月。我试图为dataset2的July值添加额外的nil值,但这不起作用。如何才能正确显示?

1 个答案:

答案 0 :(得分:3)

你误解了它的运作方式。每个xIndex都有它的值,称为dataEntry。首先创建两个系列的7个值,但最后放大了xAxis。 ios-charts使用xIndex来跟踪它应该绘制值的位置,而不是标签。 8月和7月的标签都在xIndex:6中,在您的dataSet中。这就是为什么你看到他们都是在Jul上绘制的,因为它的xIndex是6。

你应该做的是首先创建像

这样的x值

let allDataPoints: [String] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"]表示我有8个x值,而不是7,

然后使用xIndex值插入值,如果在特定xIndex处没有值,则忽略它并继续下一个值。不要按照建议插入nil值。

例如,对于数据

let values2 = [21.0, 5.0, 7.0, 10.0, 11.0, 18.0, 20](有8月数据,但没有7月数据)

在创建dataEntry时,每个值的xIndex应为[0,1,2,3,4,5,7],而不是[0,1,2,3,4,5,6]。