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:
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-helixexamples/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.
Quick start
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
| Area | 2D | 3D |
|---|---|---|
| Theme, palette, fonts | yes | same |
| Legend toggles and drag | yes | same code path |
| 13 hover animations and easing | yes | same effects on lines, bars, and cells |
| Hovered series draws on top | yes | yes, without reordering legend rows |
| Direction arrow | lines and candles | 3D lines |
| Hover popup | x and y | x, y, and z |
| Per-series overrides | SeriesStyle | Series3DStyle |
| Axis config | x and y | x, y, and z |
| Toolbar settings/export | yes | yes |
| SVG/PNG from the screen scene | yes | yes |
| Reduced motion | yes | yes |
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
| Constructor | Data | Drawing |
|---|---|---|
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 z | Filled, wireframed surface |
Series3D::surface_fn(name, x_range, y_range, samples, f) | a function | Regular 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
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.
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.
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.
Surfaces
A surface is a regular grid:
xholds the column coordinates (nxvalues).yholds the row coordinates (nyvalues).zholdsnx * nyheights in row-major order:z[row * nx + column].
Series3D::surface takes the three slices or vectors. Series3D::surface_fn samples a closure:
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.
Camera
Camera3D is an orbit camera:
| Field | Meaning |
|---|---|
yaw | Rotation around the vertical axis, radians |
pitch | Elevation, clamped to ±85° by interaction |
distance | Eye distance from the target |
target | Point the camera looks at, in scaled data units |
fov | Vertical field of view, 15–120° |
projection | Perspective 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.
let config = Plot3DConfig {
yaw: -0.8,
pitch: 0.5,
fov: 42.0,
projection: Projection::Orthographic,
..Plot3DConfig::default()
};// 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 fitInteraction
| Gesture | Action |
|---|---|
| Drag | Orbit around the target |
| Shift-drag, right-drag, or the pan tool | Move the target across the view plane |
| Wheel or pinch | Zoom toward or away from the target |
| Double-click or the fit button | Reset to the automatic fit |
| Toolbar orbit/pan | Choose the primary-button behavior |
| Toolbar zoom in/out | Zoom 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 whenNone. - 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.
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.
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.
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.
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.
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:
| Group | Fields |
|---|---|
| Text | title, title_size, title_color, title_align, label_size, tick_size, legend_size |
| Axes | x, y, z (AxisConfig), grid_width, grid_major_opacity, grid_minor_opacity, tick_length |
| Frame | frame_width, line_scale, marker_scale |
| Legend | legend, legend_frame, legend_hover |
| Camera | projection, yaw, pitch, fov |
| Feedback | hover_guides, hover_popup, direction |
| Surface | surface (wireframe, opacity, color_scale) |
| Toolbar | toolbar |
| Colors | colors (PlotColors) |
| Series | series (Series3DStyle) |
Per-series overrides are matched by name:
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:
- Every series extent is computed once and cached by a fingerprint.
- The automatic bounds are padded, fixed limits applied, and stored in scaled space (log10 already applied).
Camera3Dbuilds an orthonormal basis: eye, forward, right, and up.Projectormaps each point to a screen position and a camera-space depth.- The box, grid, ticks, and axis titles are emitted as
Primvalues. - Series are drawn in order; the hovered series is moved to the end.
- Bars and surfaces are sorted back-to-front by average face depth.
- Bar and surface fills become
Prim::Quadmeshes; edge-on bar faces are culled, then the wireframe and outlines are drawn on top. - The legend, hover ring, popup, and toolbar are drawn over the scene.
Source layout for reference:
| File | Responsibility |
|---|---|
three/camera.rs | Camera basis, perspective/orthographic projection, pan/orbit/zoom |
three/series.rs | Series3D, Surface, constructors, bounds, fingerprints |
three/axes.rs | Box, back-wall grid, ticks, labels, axis titles |
three/paint.rs | Lines, markers, bar cuboids, surface cells, legend swatches |
three/scene.rs | Automatic bounds, draw order, one frame of primitives |
three/interact.rs | Camera drag, wheel zoom, hover search |
three/widgets.rs | Toolbar, legend interaction, hover ring, x/y/z popup |
three/export.rs | SVG/PNG from the current camera and scene |
three/config.rs | Plot3DConfig, Series3DStyle, Surface3DConfig |
three/types.rs | Plot3DState, Plot3DResponse, Plot3DHover, Bounds3D |
Performance
- Surface cells and bar faces are depth-sorted; the cost is linear in the number of faces.
Series3D::boundsis 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_fnsamples. - 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:
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.