I'm trying to make a line chart with annotations similar to this Cardio Fitness chart in the Apple Health App. Is there a way to do it in Swift Charts?
// Data Model
struct TestWeight: Identifiable {
var id = UUID()
var weight: Double
var date: Date
init(id: UUID = UUID(), weight: Double, day: Int) {
self.id = id
self.weight = weight
let calendar = Calendar.current
self.date = calendar.date(from: DateComponents(year: 2023, month: 10, day: day))!
}
}
// Test data
var weight: [TestWeight] = [
TestWeight(weight: 69.4, day: 2),
TestWeight(weight: 69.2, day: 3),
TestWeight(weight: 70.0, day: 4),
TestWeight(weight: 69.7, day: 5),
TestWeight(weight: 69.0, day: 6),
TestWeight(weight: 68.8, day: 7),
TestWeight(weight: 68.0, day: 8)
]
Chart {
ForEach(weight) { data in
LineMark(
x: .value("Day", data.date, unit: .day),
y: .value("Weight", data.weight)
)
.foregroundStyle(Color.pink)
}
}
.frame(height: 150)
.symbol {
Circle()
.fill(Color.pink)
.frame(width: 8)
}
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { _ in
AxisTick()
AxisGridLine()
AxisValueLabel(format: .dateTime.weekday(.abbreviated), centered: true)
}
}
.chartYScale(domain: 62...70)

To make those horizontal lines with annotations, RuleMark or RectangleMark can be used. Rectangle marks were used in this example:
RectangleMark has a height parameter which was used to create something similar to the thicker lines in Apple's Cardio chart. RectangleMark has multiple inits to create horizontal lines, vertical lines, squares, rectangles and matrices.
A cornerRadius set to 1/2 the height was added to give the horizontal lines round end caps:
Annotations were added to the rectangle marks:
Full code for better context: