Why do annotations only show correctly on bar marks?
Asked Answered
F

1

9

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.

Fluted answered 11/9, 2022 at 5:56 Comment(1)
This is by design. See this answer: stackoverflow.com/a/75461921. An invisible PointMark will also work.Sharlasharleen
S
6

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)

Sawyor answered 20/9, 2022 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.