Curious Jorge
Curious Jorge

Reputation: 1445

How can we exclude a given series from Swift Chart Legend?

I'm curious, is there a way of excluding only certain Series from the automatically generated legends that Swift Charts provides?

In this example, how would I hide "Series 1", from the legend?

private struct PlotPoint {
    let x: Double
    let y: Double
}

// We build a dictionary of the form "Series X": [ (x1, y1), ... ]
private let data: [String : [PlotPoint]] = Dictionary(
    uniqueKeysWithValues: Array(0..<4).map { series in
        (
            // Dict key followed by Dict value
            "Series \(series + 1)",
            stride(from: 0.0, through: 1.0, by: 0.05).map { y in
                PlotPoint(x: y*y, y: y*Double(series + 1)/4.0)
            }
        )
    }
)

struct ChartWithBothStyleAndSymbol: View {
    var body: some View {
        Chart {
            ForEach(Array(data.keys).sorted(), id: \.self) { key in
                LinePlot(
                    data[key] ?? [],
                    x: .value("x", \.x),
                    y: .value("y", \.y)
                )
                .foregroundStyle(by: .value("Series", key))
            }
        }
        .padding()
    }
}

Chart with all Series in Legend

FWIW, I already know I can achieve this by using .foregroundStyle(_:) instead of .foregroundStyle(by:) for the only Series in question (and only if I define it before the other Series). But it feels like this is taking advantage of undocumented and somewhat odd behaviour in Swift Charts, and I'm wondering if there's a better way, more directly supported by the API.

Upvotes: 0

Views: 44

Answers (0)

Related Questions