You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Swift Chart图例中排除指定数据系列?

在Swift Charts中仅隐藏特定数据系列的图例

可以通过两种官方API支持的方案实现,无需依赖未公开行为:

方案一:自定义图例(完全控制显示内容)

手动构建图例,筛选掉不需要显示的系列(比如"Series 1"),这种方式灵活性最高,能完全定制图例的样式和内容:

struct ChartData: Identifiable {
    let id = UUID()
    let category: String
    let value: Double
    let series: String
}

let data = [
    ChartData(category: "A", value: 10, series: "Series 1"),
    ChartData(category: "A", value: 15, series: "Series 2"),
    ChartData(category: "B", value: 8, series: "Series 1"),
    ChartData(category: "B", value: 12, series: "Series 2"),
]

// 辅助函数:匹配系列对应的颜色
func seriesColor(_ series: String) -> Color {
    switch series {
    case "Series 2": return .blue
    default: return .gray
    }
}

Chart(data) { datum in
    BarMark(
        x: .value("Category", datum.category),
        y: .value("Value", datum.value),
        stack: .value("Series", datum.series)
    )
    .foregroundStyle(by: .value("Series", datum.series))
}
.chartLegend {
    Legend {
        // 过滤掉"Series 1",仅保留需要显示的系列
        ForEach(Array(Set(data.map(\.series))).filter { $0 != "Series 1" }, id: \.self) { series in
            LegendEntry(
                label: Text(series),
                symbol: Rectangle().fill(seriesColor(series))
            )
        }
    }
}

方案二:使用symbolVisibility修饰符(简洁高效)

直接针对目标系列设置符号可见性为隐藏,Swift Charts会自动将该系列从自动生成的图例中排除,代码更简洁:

Chart(data) { datum in
    BarMark(
        x: .value("Category", datum.category),
        y: .value("Value", datum.value),
        stack: .value("Series", datum.series)
    )
    .foregroundStyle(by: .value("Series", datum.series))
    // 对"Series 1"隐藏符号,图例自动排除该系列
    .symbolVisibility(datum.series == "Series 1" ? .hidden : .visible)
}
.chartLegend(position: .bottom)

两种方案均基于官方公开API,不存在依赖未定义行为的风险,可根据需求选择:如果需要定制图例样式选方案一,仅需隐藏特定系列选方案二更便捷。

内容的提问来源于stack exchange,提问作者Curious Jorge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:12:09