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

如何在SwiftUI Chart中按Invoice.category对发票数据分组?

按Category分组生成饼图的解决方案

要实现按Category分组展示饼图,核心是先把同一分类下的Invoice总金额求和,再用汇总后的数据绘制扇区。具体操作如下:

1. 分组并计算分类总金额

先将原始invoices数组按category分组,再对每个分组内的total字段求和。可以借助Dictionary(grouping:)完成分组,再通过map转换为适合图表使用的数据结构:

// 定义结构体存储分类与对应总金额(也可用元组替代)
struct CategoryExpense {
    let category: Category
    let total: Double // 根据你的Invoice.total实际类型调整
}

// 生成分组汇总数据
let groupedExpenses = Dictionary(grouping: store.profile!.invoices, by: \.category)
    .map { category, invoices in
        CategoryExpense(
            category: category,
            total: invoices.reduce(0) { $0 + $1.total }
        )
    }

2. 修改Chart代码使用分组数据

把Chart的数据源替换为上面生成的groupedExpenses,并调整SectorMark的绑定字段:

Chart(groupedExpenses) { expense in
    SectorMark(
        angle: .value("Total Expense", expense.total),
        innerRadius: .ratio(0.618),
        angularInset: 1.5
    )
    .cornerRadius(5)
    .foregroundStyle(by: .value("Category", expense.category.rawValue))
    .annotation(position: .overlay) {
        Text("\(expense.total)")
            .font(.headline)
            .foregroundStyle(.white)
    }
}
.chartLegend(alignment: .center, spacing: 18)
.chartAngleSelection($selectedAngel)
.scaledToFit()
#if os(macOS)
.transaction {
    $0.animation = nil // Do not animate on MacOS.
}
#endif

关键说明

  • 分组逻辑:Dictionary(grouping:by:)会自动将相同category的Invoice归为一组,再通过reduce计算该组的总金额。
  • 图表适配:替换数据源后,每个SectorMark对应一个分类的总金额,而非单个Invoice,饼图就会按分类展示汇总数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:22:33