1

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:

enter image description here

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:

enter image description here

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!

DevB2F
  • 4,674
  • 4
  • 36
  • 60
Pangu
  • 3,721
  • 11
  • 53
  • 120

1 Answers1

0

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 :)

phamot
  • 384
  • 2
  • 12