Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change spacing between BarMarks in SwiftUI Charts

How do I change spacing between BarMarks in SwiftUI Charts. There seems to be no documentation for this. Here is my chart and it gets crowded when I putit inside ScrollView:

ScrollView(.vertical) {
    Chart {
        ForEach(0...csv.rows.count-1, id: \.self) { i in
            let movie = csv.rows[i][0]
            let rating = Double(csv.rows[i][2]) ?? 0
            BarMark(
                x: .value("Rating", rating),
                y: .value("Movie", movie),
                width: 30
            )
            .annotation(position: .trailing) {
                Text(String(format: "%.0f%", rating))
                .foregroundColor(Color.gray)
               .font(.system(size: 12, weight: .bold))
            }
            .foregroundStyle(.linearGradient(
                colors: [.mint, .green],
                startPoint: .leading,
                endPoint: .trailing)
            )
            .cornerRadius(10)
        }
    }
    .chartXAxisLabel("Rating")
    .chartYAxisLabel("Movie")
}
like image 384
Kashif Avatar asked Sep 19 '25 08:09

Kashif


1 Answers

The Chart adapts to the given space, and unfortunately, ScrollView only offers minimum height. So you have to add a defined height for your chart based on the number of entries, e.g. like this:

ScrollView(.vertical) {
    Chart {
        ForEach(0...csv.rows.count-1, id: \.self) { i in
            let movie = csv.rows[i][0]
            let rating = Double(csv.rows[i][2]) ?? 0
            BarMark(
                x: .value("Rating", rating),
                y: .value("Movie", movie),
                width: 30
            )
            .annotation(position: .trailing) {
                Text(String(format: "%.0f%", rating))
                .foregroundColor(Color.gray)
               .font(.system(size: 12, weight: .bold))
            }
            .foregroundStyle(.linearGradient(
                colors: [.mint, .green],
                startPoint: .leading,
                endPoint: .trailing)
            )
            .cornerRadius(10)
        }
    }
    .chartXAxisLabel("Rating")
    .chartYAxisLabel("Movie")

    .frame(height: csv.rows.count * 60) // << HERE

}
like image 136
ChrisR Avatar answered Sep 20 '25 23:09

ChrisR