8

I have a Swift Chart that can toggle between line and bar marks. I've added annotations to the top of each mark to display the value for each data point. On the bar chart, the annotations display correctly. However, on the line chart, only the first annotation shows. Is that a bug or by design?

Annotations Working correctly on Bar Marks

Annotations not showing on Line Marks

Here is the code that I used to show the annotation on the bar marks:

 BarMark (
                                x: PlottableValue.value("Date", "\(day.name) \(day.date)") ,
                                y: PlottableValue.value("Miles", lookupDict[day] ?? 0)
                            )
                            .annotation {
                                if let miles = lookupDict[day] {
                                    Text(verbatim: "\(miles)")
                                        .font(.caption)
                                } else {
                                    EmptyView()
                                }
                            }

I used the same annotation modifier block on the line marks, but can't understand why it doesn't work the same way.

1 Answers1

4

I don't know the answer to why this doesn't work, but as a workaround, you can draw clear BarMarks with the annotation. Something like this:

  BarMark (
    x: PlottableValue.value("Date", "\(day.name) \(day.date)") ,
    y: PlottableValue.value("Miles", lookupDict[day] ?? 0))
    .foregroundStyle(Color.clear)
    .annotation { Text("...") }

  LineMark (
    x: PlottableValue.value("Date", "\(day.name) \(day.date)") ,
    y: PlottableValue.value("Miles", lookupDict[day] ?? 0)

kodai
  • 3,080
  • 5
  • 32
  • 34