0

I am new in SwiftUI and I am facing creating stack bar chart using iOS 15 and SwiftUI

My code is like this

struct StackedBarChartView: View {
    let dataPoints: [String]
    let dataSets: [[Int]]
    let colors: [Color]
    let fixedWidth: CGFloat

    var body: some View {
        VStack {
            HStack {
                GeometryReader { geometry in
                    HStack{
                        ForEach(dataSets.indices) { index in
                            Spacer()
                            VStack(spacing: 10) {
                                ForEach(dataSets[index].indices) { innerIndex in
                                    let value = dataSets[index][innerIndex]
                                    let barHeight = CGFloat(value) / CGFloat(dataSets[index].reduce(0, +)) * geometry.size.height

                                    RoundedRectangle(cornerRadius: 15)
                                        .fill(colors[innerIndex % colors.count])
                                        .frame(width: fixedWidth, height: barHeight)
                                        .animation(.easeInOut)
                                }
                            }
                            Spacer()
                        }
                    }
                }
            }

            HStack {
                ForEach(dataPoints, id: \.self) { dataPoint in
                    Text(dataPoint)
                        .font(.caption)
                        .padding(.top, 8)
                }
            }
            .padding(.top)
        }
        .padding()
        .frame(height: 300)
    }
}

struct ContentView: View {
    let dataPoints = ["A", "B", "C", "D"]
    let dataSets = [[20, 30, 40, 10], [10, 20, 30, 40], [5, 15, 10, 30]]
    let colors: [Color] = [.red, .green, .blue, .orange] // Define your desired colors here

    var body: some View {
        StackedBarChartView(dataPoints: dataPoints, dataSets: dataSets, colors: colors, fixedWidth: 10)
    }
}

But I am getting chart like this enter image description here

But I want it to look like this

enter image description here

How can I show data on the left hand side of the graph. It is possible?

Muju
  • 884
  • 20
  • 54

0 Answers0