Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add a border around a BarMark in SwiftCharts?

I am working with SwiftCharts and displaying a bar chart using BarMark to visualize data points. However, I want to add a visible border or outline around each bar to make them stand out more. I successfully added a border around the entire chart, but how can I add a border to each individual bar in SwiftCharts?

Here’s a simplified version of my code for context:

Chart {
    ForEach(matchs, id: \.day) { match in
        BarMark(x: .value("day", match.day),
                y: .value("point", match.point)
            )
            .opacity(1.0)
            .foregroundStyle(.red)
            .clipShape(RoundedRectangle(cornerRadius: 0))
    }
}
.chartPlotStyle { content incontent.border(.white, width: 1)}
.frame(height: 250)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To add a border around each BarMark, you can use an annotation on each bar. Within this annotation, draw a Rectangle that matches the size of the bar and apply a stroke to it to create the border.

You can update your code like this:

Chart {
    ForEach(matchs, id: \.day) { match in
        BarMark(
            x: .value("day", match.day),
            y: .value("point", match.point)
        )
        .foregroundStyle(.red)
        .annotation(position: .overlay) {
            Rectangle()
                .stroke(Color.black, lineWidth: 1)
        }
    }
}
.frame(height: 250)

This way, you’ll add a black border around each bar.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading