iOS图表:将数据组合成堆积条形图?

时间:2017-08-06 19:57:20

标签: ios swift charts ios-charts

我使用iOS Charts库时相当新,我能够创建一个条形图,但我很难理解如何#stack; stack"一组包含相同x轴值的数据。

这是我的条形图目前的样子:

enter image description here

实现这一目标的代码:

extension MyViewController: IAxisValueFormatter
{
    func stringForValue(_ value: Double, axis: AxisBase?) -> String
    {
        let record_ARRAY = record_ARRAY.sorted(by: {$0.date < $1.date})

        let date = record_ARRAY[Int(value)].date

        return ReusableClass.typeThreeDateFormat(date: date)
    }
}

var chargeDates_ARRAY = [Date]()
var chargeCosts_ARRAY = [Double]()

override func viewDidLoad()
{
    chargeDates_ARRAY = [2017-08-05 07:00:00 +0000, 2017-08-06 07:00:00 +0000, 2017-08-06 07:00:00 +0000, 2017-08-07 07:00:00 +0000]

    chargeCosts_ARRAY = [8.0, 3.0, 5.6600000000000001, 4.4400000000000004]

    createBarChart(dataPoints: chargeDates_ARRAY, values: chargeCosts_ARRAY)

    barChartView.delegate = self
}

func createBarChart(dataPoints: [Date], values: [Double])
{
    var dataEntries: [BarChartDataEntry] = []

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

        dataEntries.append(dataEntry)
    }

    barChartView.xAxis.valueFormatter = self

    barChartView.xAxis.granularity = 1

    barChartView.xAxis.setLabelCount(dataPoints.count, force: false)

    barChartView.animate(yAxisDuration: 1.0, easingOption: .easeInOutQuad)

    let chartDataSet = BarChartDataSet(values: dataEntries, label: "")
    let chartData = BarChartData(dataSet: chartDataSet)

    barChartView.data = chartData

    barChartView.zoom(scaleX: zoomXMultiplier, scaleY: 0.0, x: 0, y: 0)

    barChartView.barData?.barWidth = barWidthMultiplier
}

我喜欢将包含2个相同x轴值08/06/17的数据合并到一个堆积栏中,并实现以下目标:

enter image description here

我试图按照问题的答案:Stacked bar chart with charts in Swift

但我无法到达任何地方。

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试将chargeCosts_ARRAY = [8.0, 3.0, 5.6600000000000001, 4.4400000000000004]构建为chargeCosts_ARRAY = [[8.0], [3.0, 5.6600000000000001], [4.4400000000000004]],基本上您正在尝试创建[[Double]]()类型的对象。然后将BarChartDataEntry(x: Double(index), y: values[index])更改为BarChartDataEntry(x: Double(index), yValues: values[index])。快乐的编码:)