Contents

Chart3D

A SwiftUI view that displays interactive 3D charts and visualizations.

Declaration

@MainActor @preconcurrency struct Chart3D<Content> where Content : Chart3DContent

Overview

Use Chart3D to create three-dimensional data visualizations with compatible mark types. To add content to your chart, use the 3D-only SurfacePlot or the 3D initializers of PointMark, RuleMark, and RectangleMark.

For example, you can use a SurfacePlot to visualize a 3D surface for the function y = cos(2 * x) * sin(2 * x):

Chart3D {
    SurfacePlot(x: "x", y: "y", z: "z") { x, z in
        sin(2 * x) * cos(2 * z)
    }
}

You can also use the 3D initializers for PointMark init(x:y:z:), RuleMark init(x:y:z:), RectangleMark init(x:y:z:) to plot 3D visualizations of your data.

For example, suppose you have an array of Penguin structures that define datapoints composed of beakLength, weight flipperLength:

struct Penguin: Identifiable {
    let id: Int
    let flipperLength: Double
    let weight: Double
    let beakLength: Double
}

let penguins: [Penguin] = [
    Penguin(id: 0, flipperLength: 197, weight: 4.2, beakLength: 59),
    Penguin(id: 1, flipperLength: 220, weight: 4.7, beakLength: 48),
    Penguin(id: 2, flipperLength: 235, weight: 5.8, beakLength: 42),
    ...
]

You can also use the 3D initializer ofPointMark init(x:y:z:) to represent the flipperLength property as the x value, the weight property as the y value, and the beakLength property as the z value:

Chart3D(penguins) {
    PointMark(
        x: .value("Flipper Length (mm)", $0.flipperLength),
        y: .value("Weight (kg)", $0.weight),
        z: .value("Beak Length (mm)", $0.beakLength)
    )
}

Customizing interactivity

To make your 3D Chart interactive, declare a @State property of type Chart3DPose and pass it as a binding to the chart3DPose(_:)-(Binding<Chart3DPose>) view modifier:

@State private var pose: Chart3DPose = .default
var body: some View {
    Chart3D(penguins) {
        PointMark(
            x: .value("Flipper Length (mm)", $0.flipperLength),
            y: .value("Weight (kg)", $0.weight),
            z: .value("Beak Length (mm)", $0.beakLength)
        )
    }
    .chart3DPose($pose)
}

On available platforms, you can use the chart3DCameraProjection(_:) modifier to switch from orthographic to perspective projection.

Chart3D(penguins) {
    ...
}
.chart3DCameraProjection(.perspective)

A SwiftUI view that displays a three-dimensional chart.

Topics

Creating 3D charts

Configuring chart shapes

Configuring surfaces

Customizing chart presentation

See Also

3D charts