【问题标题】:How to create a chart without the legend when using Apple's Charts?使用 Apple 的 Charts 时如何创建没有图例的图表?
【发布时间】:2022-06-16 04:40:08
【问题描述】:

Apple 的 Swift Charts 最近在 WWDC 上推出。但是,我的练习表有冗余。不需要图例。如何创建包含所有颜色但没有图例的图表?

使用“.foregroundStyle(by: .value("Shape", shape.type))”会导致图表自动为条形添加多种颜色。但是foregroundStyle 也带有图例。删除 foregroundStyle 会同时删除图例和颜色:

这是最小的可重现代码:

import Charts
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Swift Chart Example")
            BarChart()
                .frame(width: 350, height: 350, alignment: .center)
        }
    }
}

struct Shape: Identifiable {
    var type: String
    var count: Double
    var id = UUID()
}

let data: [Shape] = [
    .init(type: "Square",    count: 12),
    .init(type: "Heart",     count: 10),
    .init(type: "Rectangle", count: 21),
    .init(type: "Star",      count: 15),
    .init(type: "Circle",    count: 8),
    .init(type: "Triangle",  count: 6),
]

struct BarChart: View {
    var body: some View {
        Chart {
            ForEach (data) { shape in
                BarMark (
                    x: .value("Shape", shape.type),
                    y: .value("Count", shape.count)
                )
                .foregroundStyle(by: .value("Shape", shape.type))
            }
        }
    }
}

【问题讨论】:

    标签: swift swiftui charts


    【解决方案1】:

    要删除图例,请将这行代码添加到图表中:

    .chartLegend(.hidden)
    

    像这样:

    struct BarChart: View {
        var body: some View {
            Chart {
                ForEach (data) { shape in
                    BarMark (
                        x: .value("Shape", shape.type),
                        y: .value("Count", shape.count)
                    )
                    .foregroundStyle(by: .value("Shape", shape.type))
                }
            }
            .chartLegend(.hidden)
        }
    }
    

    结果:

    此外,这些也可以类似地用于从 X 和 Y 轴上删除标签:

    .chartXAxis(.hidden)
    .chartYAxis(.hidden)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2012-04-15
      • 2016-08-13
      • 2016-05-14
      • 2012-01-06
      • 1970-01-01
      相关资源
      最近更新 更多