简体   繁体   中英

How to create a chart without the legend when using Apple's Charts?

Apple's Swift Charts was recently introduced at WWDC. However, my practice chart has a redundancy. The legend is not needed. How do I create the chart with all the colors but no legend?

在此处输入图像描述

Using “.foregroundStyle(by: .value("Shape", shape.type))” causes Charts to automatically add multiple colors to the bars. But foregroundStyle also comes with the legend. Removing foregroundStyle removes both the legend and the colors:

在此处输入图像描述

This is the minimum reproducible code:

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))
            }
        }
    }
}

To remove the legend, add this line of code to the Chart:

.chartLegend(.hidden)

Like this:

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)
    }
}

Result:

在此处输入图像描述

Also, these can be used similarly to remove the labels from the X and Y axes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM