0
votes

I'm using charts library for creating graph like this

enter image description here

I'm using this code to populate the chart. The data that is sent in the below code is

[[1.6667000000000001, 2.0], [1.6667000000000001, 1.0], [1.6667000000000001, 1.0], [2.3333000000000004, 2.0], [1.3332999999999999, 1.0], [1.6667000000000001, 3.0], [1.3332999999999999, 2.0], [1.3332999999999999, 1.0], [2.3333000000000004, 3.0], [2.0, 2.0], [2.6666999999999996, 3.0], [2.3333000000000004, 1.0], [2.3333000000000004, 2.0]]

func setChart(data:[[Double]]) {
    barChartView.noDataText = "You need to provide data for the chart."
    var dataEntries: [[BarChartDataEntry]] = []

    for _ in 0..<data.first!.count{
        dataEntries.append([])
    }

    for i in 0..<data.count {

        for g in 0..<dataEntries.count{
            dataEntries[g].append(BarChartDataEntry(x: Double(i), y: data[i][g]))
        }

    }

    var dataSet = [BarChartDataSet]()

    for i  in 0..<dataEntries.count {

        let some = BarChartDataSet(values: dataEntries[i], label: nil)
        some.colors = ChartColorTemplates.colorful()
        dataSet.append(some)

    }



    let chartData = BarChartData(dataSets: dataSet)


    let groupSpace = 0.025
    let barSpace = 0.4
    let barWidth = 0.8
    // (0.05 + 0.03) * 3 + 0.3 = 1.00 -> interval per "group"
    //(groupSpace * barSpace) * n + groupSpace = 1
    //()*13
    let startYear = 0


    chartData.barWidth = barWidth;
    barChartView.xAxis.axisMinimum = Double(startYear)
    let gg = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
    print("Groupspace: \(gg)")
//        barChartView.xAxis.axisMaximum = Double(startYear) + gg * Double(groupCount)
    barChartView.xAxis.axisMaximum = 25
    barChartView.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace)
    //chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
    barChartView.notifyDataSetChanged()

    barChartView.data = chartData






    //background color
    barChartView.backgroundColor = UIColor(red: 189/255, green: 195/255, blue: 199/255, alpha: 1)

    //chart animation
    barChartView.animate(xAxisDuration: 1.5, yAxisDuration: 1.5, easingOption: .linear)
}

This is not working correctly I'm having overlapped bars. the X-Axis maximum is not creating automatically. I don't know what I am doing wrong here. Anyone can please tell me where I'm wrong. The number of bars per group is 13 and the number of groups can vary till 50.

1

1 Answers

0
votes

Its very simple and you are setting groupBars for barChartView. Its wrong.

barChartView.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace)

You have to set groupBars for chartData. Like below

chartData.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace)