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)
>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.