Skip to content

3D charts ​

components::plot::Plot3D is the 3D sibling of Plot. It is a real scene renderer, not a 2D chart with a fake perspective: data lives in [x, y, z], a camera projects it, faces are depth-sorted, and the axes are laid out in screen space from the same measured text metrics as the 2D plot.

It keeps its camera, hidden series, legend position, and hover state in a Plot3DState the application owns. Themes, palette, icon cache, legend animations, direction arrow, hover popup, and SVG/PNG export are shared with the 2D component.

See the examples ​

The repository ships one native gallery and four live documentation scenes:

bash
cargo run --example plot3d
cargo run --example scenes -- scene=plot-3d
cargo run --example scenes -- scene=plot-3d-surface
cargo run --example scenes -- scene=plot-3d-bars
cargo run --example scenes -- scene=plot-3d-helix

examples/plot3d/main.rs is a complete native window with a title bar, theme toggle, chart selector, projection selector, the 13 legend animations, easing, wireframe, direction arrow, camera reset, and SVG/PNG export.

Live demo
The gallery: switch between surface, bars, and helix; drag orbits, Shift-drag pans, the wheel zooms, double-click fits.Open in a tab ↗

Quick start ​

rust
use egui_workbench::components::plot::{Plot3D, Plot3DState, Series3D};

let points: Vec<[f64; 3]> = (0..180)
    .map(|index| {
        let angle = index as f64 * 0.14;
        [angle.cos() * 2.0, angle.sin() * 2.0, index as f64 * 0.04]
    })
    .collect();

let mut state = Plot3DState::default();
let response = Plot3D::new("helix")
    .title("Streaming helix")
    .x_label("x")
    .y_label("y")
    .z_label("z")
    .direction_arrow(true)
    .series(Series3D::line("path", &points).width(2.0))
    .series(Series3D::scatter("samples", &points[..12]))
    .show(ui, &mut icons, &mut state);

if let Some(hover) = response.hovered {
    let [x, y, z] = hover.point;
    status = format!("{}: {x:.2}, {y:.2}, {z:.2}", hover.series);
}

What is shared with Plot ​

Area2D3D
Theme, palette, fontsyessame
Legend toggles and dragyessame code path
13 hover animations and easingyessame effects on lines, bars, and cells
Hovered series draws on topyesyes, without reordering legend rows
Direction arrowlines and candles3D lines
Hover popupx and yx, y, and z
Per-series overridesSeriesStyleSeries3DStyle
Axis configx and yx, y, and z
Toolbar settings/exportyesyes
SVG/PNG from the screen sceneyesyes
Reduced motionyesyes

There is no second y axis in 3D; the third dimension is z. Fits, area selection, step lines, candlesticks, heatmaps, radar, gauges, waterfalls, decimation, and smoothing are 2D-only. 3D has its own camera, depth sorting, bars, and surfaces.

Series3D ​

ConstructorDataDrawing
Series3D::line(name, data)&[[f64; 3]]Polyline through the points, 1.6 pt default
Series3D::scatter(name, data)&[[f64; 3]]Markers, 3 pt radius circles default
Series3D::bars(name, data)&[[f64; 3]]Vertical cuboids from z = 0
Series3D::surface(name, x, y, z)x, y, row-major zFilled, wireframed surface
Series3D::surface_fn(name, x_range, y_range, samples, f)a functionRegular grid sampled from the function

All constructors accept borrowed data when possible (&[[f64; 3]]), so a large point cloud is not copied every frame. Data is stored as Cow, like the 2D Series.

Lines and scatter ​

rust
Plot3D::new("path")
    .series(Series3D::line("orbit", &path).width(2.0).color(theme.link))
    .series(
        Series3D::scatter("samples", &marks)
            .marker(Marker::Diamond)
            .radius(4.5),
    )
    .show(ui, &mut icons, &mut state);

Non-finite points break the line into segments. Lines support .color, .width, .style(LineStyle::{Solid, Dashed, Dotted}), .marker, and .hide_from_legend. Scatter supports .color, .marker, .radius, and .hide_from_legend.

Live demo
Line, scatter, the direction arrow, and the legend hover animation, live.Open in a tab ↗

Bars ​

Bars are cuboids from a base z to each value. The footprint is bar_width in data units; when unset it is 70 % of the smallest x/y gap. Faces are culled against the camera and sorted by depth, so the top and the two visible sides read as one solid block. Fills are quad meshes, and faces with a projected area below 8 px² are dropped: edge-on faces cannot leave anti-aliasing spikes at any camera angle or projection.

rust
let cells: Vec<[f64; 3]> = (0..8)
    .flat_map(|x| (0..8).map(move |y| [f64::from(x), f64::from(y), revenue(x, y)]))
    .collect();

Plot3D::new("revenue")
    .x_label("Region")
    .y_label("Segment")
    .z_label("Revenue")
    .series(Series3D::bars("revenue", cells).bar_width(0.62).base(0.0))
    .show(ui, &mut icons, &mut state);

Negative bars use the theme danger color, like the 2D waterfall and candles. .base moves the starting plane.

Live demo
Bars from a z base, depth-sorted sides and tops, legend hover, and the toolbar.Open in a tab ↗

Surfaces ​

A surface is a regular grid:

  • x holds the column coordinates (nx values).
  • y holds the row coordinates (ny values).
  • z holds nx * ny heights in row-major order: z[row * nx + column].

Series3D::surface takes the three slices or vectors. Series3D::surface_fn samples a closure:

rust
let surface = Series3D::surface_fn(
    "terrain",
    -2.0..=2.0,          // x range
    -2.0..=2.0,          // y range
    [34, 34],            // columns, rows
    |x, y| (x * x + y * y).sin() * 0.7 + (x * 1.2).cos() * 0.3,
);

Plot3D::new("terrain")
    .surface(Surface3DConfig {
        wireframe: true,
        opacity: 0.92,
        color_scale: true,
    })
    .series(surface)
    .show(ui, &mut icons, &mut state);

Surfaces are colored by height through the theme's blue → purple → amber scale (color_scale: false paints the series color instead), filled as quad meshes, and outlined when wireframe is on. A projected cell may be concave because its four z values need not be planar; the renderer fills it as two triangles so it stays correct at any camera angle.

Live demo
A sampled surface, height color scale, wireframe, orbit camera, and export.Open in a tab ↗

Camera ​

Camera3D is an orbit camera:

FieldMeaning
yawRotation around the vertical axis, radians
pitchElevation, clamped to ±85° by interaction
distanceEye distance from the target
targetPoint the camera looks at, in scaled data units
fovVertical field of view, 15–120°
projectionPerspective or Orthographic

Plot3DConfig::{yaw, pitch, fov, projection} sets the initial camera. The first frame fits the visible data: it centers the target on the bounds and chooses a distance from the bounding sphere, field of view, and aspect ratio. After that, the camera in Plot3DState wins, and Plot3DConfig::projection and fov are reapplied every frame so changing projection in a settings panel takes effect immediately.

rust
let config = Plot3DConfig {
    yaw: -0.8,
    pitch: 0.5,
    fov: 42.0,
    projection: Projection::Orthographic,
    ..Plot3DConfig::default()
};
rust
// Read or place the camera from application code.
if state.is_auto() {
    // The current frame fits the data.
}
state.set_camera(Camera3D {
    yaw: 0.9,
    pitch: 0.3,
    ..state.camera().unwrap_or_default()
});
state.reset_view(); // back to the automatic fit

Interaction ​

GestureAction
DragOrbit around the target
Shift-drag, right-drag, or the pan toolMove the target across the view plane
Wheel or pinchZoom toward or away from the target
Double-click or the fit buttonReset to the automatic fit
Toolbar orbit/panChoose the primary-button behavior
Toolbar zoom in/outZoom around the target

The orbit tool is the default. The camera is constrained so pitch cannot cross the poles and distance cannot collapse to zero. The wheel is consumed by the plot, so a surrounding scroll area does not move while the pointer is over the chart.

Axes, ticks, and grid ​

Plot3DConfig has three AxisConfig values: x, y, and z. Each supports:

  • Linear or log10 scale.
  • Fixed min/max; automatic when None.
  • Fixed major_step, minor ticks, decimal places.
  • Tick labels on/off, label size and color, tick color.
  • Major and minor grid switches.

The box is drawn around the data. Grid lines go on the floor and the two far walls, chosen from the camera position, so they read as a room without covering the data. The near floor edges get the x and y ticks; the leftmost vertical edge gets the z ticks. Tick labels are measured with egui's real font metrics and placed outside the box. Axis titles come from .x_label, .y_label, and .z_label.

rust
Plot3D::new("log")
    .x_scale(Scale::Log10)
    .z_limits(Some(0.0), Some(1000.0))
    .x_label("Frequency")
    .y_label("Distance")
    .z_label("Power")
    .grid(true)
    .show(ui, &mut icons, &mut state);

Legend ​

The legend is the same component as in 2D:

  • Click a row to hide or show its series; hidden names live in Plot3DState.
  • Drag the legend anywhere inside the frame; the position is stored as fractions.
  • Hover a row to play the configured effect on that series.
  • The hovered series draws last, above every other series, while the legend keeps its order. For a surface, every cell blends and the surface draws over the others.
  • Long names elide, the toolbar is avoided, and the legend is left out of exports when rows are hidden.
rust
let config = Plot3DConfig {
    legend: LegendPosition::BottomRight,
    legend_hover: LegendHoverConfig {
        animation: LegendAnimation::Blink,
        easing: AnimationEasing::Sine,
        period: 1.4,
        ..LegendHoverConfig::default()
    },
    ..Plot3DConfig::default()
};

All 13 effects from Legend animation work: Blink, Fade, Throb, DashMarch, DashToggle, Glow, Sweep, Wiggle, Reveal, MarkerBounce, MarkerPulse, Twinkle, and Wave. Reduced motion disables them.

Hover and response ​

The hover search projects the drawn points and picks the nearest one within 12 pt. Ties prefer the nearer camera depth. Surfaces index their grid vertices; bars index their data rows; lines and scatter index their points.

rust
let response = plot.show(ui, &mut icons, &mut state);

if let Some(hover) = response.hovered {
    // Series name, data index, and the data point.
    let Plot3DHover { series, index, point } = hover;
}

if let Some(pos) = response.screen_pos([1.0, 2.0, 3.0]) {
    // Paint an annotation at the projected position.
}

The plot draws a ring on the hovered point and, when hover_guides is on, a dashed drop line to the floor. hover_popup controls the x/y/z popup. response.clicked reports the same point on click.

Direction arrow ​

Set .direction_arrow(true) or Plot3DConfig::direction.enabled to show an arrow beside the newest point of a 3D line. It uses the last points samples (5 by default) in screen space, so a streaming path gets a shaft and head just like the 2D plot. Per-series overrides live in Series3DStyle::direction_arrow.

rust
Plot3D::new("stream")
    .direction_arrow(true)
    .direction_points(8)
    .series(Series3D::line("sensor", &samples))
    .show(ui, &mut icons, &mut state);

Toolbar and export ​

The toolbar has orbit and pan tools, zoom in/out, fit, settings, and export. Add the last two with .settings_button(true) and .export_button(true); settings_requested and export_requested surface in Plot3DResponse.

rust
let options = ExportOptions {
    width: 1280.0,
    height: 720.0,
    scale: 2.0,
    transparent: false,
};
let svg = plot.to_svg(ctx, &state, &options);
let png = plot.to_png(ctx, &state, &options)?;

The export builds the same scene as the screen with the current camera, axes, surface shading, legend, hidden series, and styles. It leaves out the toolbar, hover ring, popup, and guides. SVG uses the same primitive list as the screen; PNG rasterizes it with resvg and egui's own fonts.

Configuration ​

Plot3DConfig mirrors the 2D configuration where it makes sense:

GroupFields
Texttitle, title_size, title_color, title_align, label_size, tick_size, legend_size
Axesx, y, z (AxisConfig), grid_width, grid_major_opacity, grid_minor_opacity, tick_length
Frameframe_width, line_scale, marker_scale
Legendlegend, legend_frame, legend_hover
Cameraprojection, yaw, pitch, fov
Feedbackhover_guides, hover_popup, direction
Surfacesurface (wireframe, opacity, color_scale)
Toolbartoolbar
Colorscolors (PlotColors)
Seriesseries (Series3DStyle)

Per-series overrides are matched by name:

rust
let mut config = Plot3DConfig::default();
config.series_style_mut("terrain").color = Some(theme.done);
config.series_style_mut("terrain").fill_opacity = Some(0.7);
config.series_style_mut("path").width = Some(2.5);
config.series_style_mut("path").direction_arrow = Some(false);

Series3DStyle has color, width, line_style, marker, marker_size, fill_opacity, and direction_arrow. Plot3DConfig::sanitize clamps sizes, opacity, pitch, field of view, tick divisions, and fixed limits after a settings dialog edits them.

How it is drawn ​

The 3D plot uses the same scene pipeline as 2D:

  1. Every series extent is computed once and cached by a fingerprint.
  2. The automatic bounds are padded, fixed limits applied, and stored in scaled space (log10 already applied).
  3. Camera3D builds an orthonormal basis: eye, forward, right, and up.
  4. Projector maps each point to a screen position and a camera-space depth.
  5. The box, grid, ticks, and axis titles are emitted as Prim values.
  6. Series are drawn in order; the hovered series is moved to the end.
  7. Bars and surfaces are sorted back-to-front by average face depth.
  8. Bar and surface fills become Prim::Quad meshes; edge-on bar faces are culled, then the wireframe and outlines are drawn on top.
  9. The legend, hover ring, popup, and toolbar are drawn over the scene.

Source layout for reference:

FileResponsibility
three/camera.rsCamera basis, perspective/orthographic projection, pan/orbit/zoom
three/series.rsSeries3D, Surface, constructors, bounds, fingerprints
three/axes.rsBox, back-wall grid, ticks, labels, axis titles
three/paint.rsLines, markers, bar cuboids, surface cells, legend swatches
three/scene.rsAutomatic bounds, draw order, one frame of primitives
three/interact.rsCamera drag, wheel zoom, hover search
three/widgets.rsToolbar, legend interaction, hover ring, x/y/z popup
three/export.rsSVG/PNG from the current camera and scene
three/config.rsPlot3DConfig, Series3DStyle, Surface3DConfig
three/types.rsPlot3DState, Plot3DResponse, Plot3DHover, Bounds3D

Performance ​

  • Surface cells and bar faces are depth-sorted; the cost is linear in the number of faces.
  • Series3D::bounds is cached by a fingerprint of the buffers and sampled values, so the automatic view does not rescan a million points every frame.
  • Hover checks the projected points of visible series within 12 pt; a surface with a large grid can be reduced with surface_fn samples.
  • A still plot does not repaint. Orbit, pan, zoom, and legend hover request repaint only while they are active.

Ownership ​

Plot3D is Clone and borrows its data. Plot3DState owns the camera, hidden series, legend position, and hover state. Keep both in the application model:

rust
struct TabData {
    points: Vec<[f64; 3]>,
    surface: Vec<f64>,
    plot: Plot3DState,
}

Build the plot once when you need it for show and for to_svg/to_png; both use the same configuration and camera.

Released under MIT OR Apache-2.0. Icons: Lucide (ISC) and Material Icon Theme (MIT).