iosswiftuicharts

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")
}

Solution

  • 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
    
    }