简体   繁体   中英

iOS Charts: Combined data into stacked bar chart?

I'm fairly new to using the iOS Charts library and I was able to make a bar chart, but I'm having trouble understanding how to "stack" a set of data containing the same x-axis value.

Here's what my bar chart currently looks like:

在此处输入图片说明

And the code to achieve this:

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
}

What I like to do is combine the data containing the 2 same x-axis values 08/06/17 into one stacked bar, and achieve something like this:

在此处输入图片说明

I've tried to follow the answer from the question: Stacked bar chart with charts in Swift

But I couldn't get anywhere.

Can someone help? Thanks!

Try to construct your chargeCosts_ARRAY = [8.0, 3.0, 5.6600000000000001, 4.4400000000000004] as chargeCosts_ARRAY = [[8.0], [3.0, 5.6600000000000001], [4.4400000000000004]] basically you are trying to create an object of type [[Double]]() . Then change BarChartDataEntry(x: Double(index), y: values[index]) to BarChartDataEntry(x: Double(index), yValues: values[index]) . Happy coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM