How to make 1D Bar Chart fill up entire width in SwiftUI?

190 Views Asked by At

There is an awkward gap on the trailing end of the chart. I want the bar to fill up the entire width so that there are no empty spaces. I tried playing around with the width field but I can't figure it out or know if its even possible. Thank you.

enter image description here

struct ViewStatus {
    var views: Double
    var status: String
}

struct ViewsChartView: View {
    let data: [ViewStatus]

    var body: some View {
        
        Chart(data, id: \.status) {
            
            BarMark(
                x: .value("Views", $0.views)
            )
            .foregroundStyle(by: .value("Status", $0.status))
            
        }
    }
}
1

There are 1 best solutions below

0
son On BEST ANSWER

By default, Chart will draw the next placeholder maximum value, depend on the input. In your example above is 400,000. To fix it you must re-calculate the range of x-axis to provide the minimum value and the maximum value.

...
var maxChartValue: Double {
    data.map { $0.views }.reduce(0, +)
}

...
var body: some View {
    HStack {
    Chart(data) {
        BarMark(
            x: .value("Views", $0.views)
        )
        .foregroundStyle(by: .value("Status", $0.status))
    }
    .chartXScale(domain: 0...maxChartValue) //<- edit range here. It's ClosedRange
}

Output:

enter image description here