Search code examples
swiftuiswiftui-charts

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?

enter image description here

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:

enter image description here

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

Solution

  • 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:

    enter image description here

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

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