Skip to main content

crisol_plot/plot/
mod.rs

1//! A fast, interactive 2D plot in the spirit of matplotlib.
2//!
3//! - Series: lines, areas, steps, scatter with seven markers, bars, error bars,
4//!   functions, and horizontal/vertical reference lines; plus pie/donut slices,
5//!   candlesticks, heatmaps, radar polygons, gauges, and waterfalls.
6//! - Axes: linear or log10 scales, 1-2-5 ticks that never overlap, minor log ticks,
7//!   grid, and a title and axis titles with their own size, color, and alignment; every line is snapped to the pixel grid.
8//! - Two y axes: series marked [`YAxis::Right`] get their own axis on the right, with
9//!   its own range, scale, ticks, and title.
10//! - Legend hover animations: 13 effects with user-defined easing, plus a direction
11//!   arrow beside the newest sample of streaming line series.
12//! - Interaction: drag to pan, wheel to zoom around the cursor (Shift: x only, Alt: y
13//!   only; with two y axes, Alt zooms the left axis over the left half of the frame and
14//!   the right axis over the right half), right-drag or the zoom tool to zoom to a box, Shift-drag or the select tool
15//!   to select an area, double-click to fit the data again, and a hover popup with the
16//!   nearest point. A small toolbar switches tools; the legend toggles series and can be
17//!   dragged anywhere inside the frame (the position lives in the [`PlotState`]).
18//! - Lines can be smoothed with a spline or a monotone cubic ([`Smoothing`]).
19//! - Analysis: least-squares fits ([`Fit`]) with their equation and R².
20//! - Speed: dense sorted lines are decimated per pixel column, so a million points
21//!   draw in a few milliseconds; nothing repaints while idle.
22//!
23//! [`Plot3D`] is the 3D sibling: an orbit camera, x/y/z axes, lines, scatter, bars, and
24//! surfaces, with the same legend, hover animations, direction arrow, themes, and
25//! SVG/PNG export.
26//!
27//! The view, the selection, the active tool, and hidden series live in a
28//! [`PlotState`] the caller owns, like every other component.
29
30mod analysis;
31mod animation;
32mod annotations;
33mod axis;
34mod builder;
35mod chart_config;
36mod colormap;
37mod config;
38mod dataset;
39mod decimate;
40mod direction;
41mod export;
42mod extra;
43mod families;
44mod filter;
45mod fit;
46#[cfg(feature = "gpu")]
47mod gpu;
48#[cfg(feature = "gpu")]
49mod gpu_line;
50mod grid;
51mod history;
52mod interact;
53mod layout;
54mod legend;
55mod math_text;
56mod measure;
57mod overlay;
58mod paint;
59mod pdf;
60mod pipeline;
61mod scene;
62mod series;
63mod series_bounds;
64mod series_charts;
65mod smooth;
66mod snap;
67mod special;
68mod three;
69mod transform;
70mod transforms;
71mod types;
72mod widgets;
73pub use analysis::{
74    Complex, Model, ModelFit, Peak, Statistics, derivative, fft, find_peaks, fit_model, integral, remove_baseline,
75    resample, rolling_baseline, savgol, savgol_derivative, spectrum,
76};
77pub use animation::{AnimationEasing, LegendAnimation, LegendHoverConfig};
78pub use annotations::{PlotAnnotation, region_size};
79pub use axis::{Bounds, Scale};
80use axis::{SecondAxis, Transform};
81pub use chart_config::{DirectionArrowConfig, GaugeConfig, HeatmapConfig, PieConfig, RadarConfig, WaterfallConfig};
82pub use colormap::Colormap;
83pub use config::{AxisConfig, Minor, PlotColors, PlotConfig, Renderer, SeriesStyle, TitleAlign};
84use crisol_ui_kit::Icons;
85use crisol_ui_kit::components::IconComponent;
86pub use dataset::{DatasetPlot, DatasetPlotKind};
87use egui::{Color32, Id, Pos2, Rect, Sense, Ui, vec2};
88pub use export::{ExportOptions, ExportPreset};
89pub use families::{box_plot, contour, hexbin, histogram, histogram_density, polar, show_colorbar, smith, violin};
90pub use filter::{FilterKind, FilterSettings};
91pub use fit::{Fit, FitKind};
92#[cfg(feature = "gpu")]
93pub use gpu::set_output_format;
94pub use grid::PlotGrid;
95pub use history::ViewHistory;
96pub use math_text::to_unicode_math;
97pub use measure::{
98    CurveAreaSummary, DistanceSummary, Extremum, MeasurementAreaStyle, MeasurementConfig, MeasurementMode,
99    PlotMeasurement, SeriesMeasurement, curve_area_summary, region_measurements,
100};
101pub use pipeline::{Pipeline, PipelineSeries};
102use scene::Measure;
103pub use series::{LineStyle, Marker, Series, Smoothing, YAxis, points_in};
104pub use three::{
105    Bounds3D, Camera3D, Plot3D, Plot3DConfig, Plot3DHover, Plot3DResponse, Plot3DState, Plot3DTool, Projection,
106    Series3D, Series3DStyle, Surface, Surface3DConfig,
107};
108pub use transforms::{TransformKind, TransformSettings};
109use types::Drag;
110pub use types::{ChartMode, ExportFormat, LegendPosition, PlotHover, PlotResponse, PlotTool};
111
112mod state;
113
114pub use state::PlotState;
115
116/// The plot builder. Add series, then call `show` with the icon cache and a
117/// [`PlotState`].
118///
119/// ```
120/// # use crisol_plot::plot::{Plot, PlotState, Series, Fit, FitKind};
121/// # let ctx = egui::Context::default();
122/// # let mut icons = crisol_plot::Icons::new();
123/// let data: Vec<[f64; 2]> = (0..100).map(|i| [i as f64 * 0.1, (i as f64 * 0.1).sin()]).collect();
124/// let mut state = PlotState::default();
125/// # let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
126/// let response = Plot::new("signal")
127///     .title("Signal")
128///     .x_label("t (s)")
129///     .y_label("V")
130///     .height(280.0)
131///     .series(Series::line("sin", &data))
132///     .series(Series::scatter("samples", &data[..10]))
133///     .show(ui, &mut icons, &mut state);
134/// if let Some(hover) = response.hovered {
135///     let _ = hover.point;
136/// }
137/// # });
138/// # output.textures_delta.clear();
139/// ```
140#[derive(Clone)]
141pub struct Plot<'a> {
142    id: Id,
143    series: Vec<Series<'a>>,
144    config: PlotConfig,
145    width: Option<f32>,
146    height: Option<f32>,
147    x_window: Option<f64>,
148    include: Bounds,
149    settings_button: bool,
150    export_button: bool,
151}
152
153impl<'a> Plot<'a> {
154    pub(super) fn visible<'s>(&'s self, state: &'s PlotState) -> impl Iterator<Item = &'s Series<'a>> {
155        self.series.iter().filter(|series| !state.is_hidden(&series.name))
156    }
157
158    /// The chart family: the first special series wins (pie, then radar, then gauge).
159    /// Mixing families in one plot is not meaningful; cartesian series need no marker.
160    pub fn chart_mode(&self) -> ChartMode {
161        let mut mode = ChartMode::Cartesian;
162        for series in &self.series {
163            match series.kind {
164                series::Kind::Pie { .. } => return ChartMode::Pie,
165                series::Kind::Radar if mode == ChartMode::Cartesian => mode = ChartMode::Radar,
166                series::Kind::Gauge { .. } if mode == ChartMode::Cartesian => mode = ChartMode::Gauge,
167                _ => {}
168            }
169        }
170        mode
171    }
172
173    /// Whether the direction arrow draws for series `index` after the overrides.
174    pub(super) fn draws_direction(&self, index: usize) -> bool {
175        self.config
176            .series_style(&self.series[index].name)
177            .and_then(|style| style.direction_arrow)
178            .unwrap_or(self.config.direction.enabled)
179    }
180
181    /// The axis series `index` is measured on, after the config override.
182    fn axis_of(&self, series: &Series<'_>) -> YAxis {
183        self.config
184            .series_style(&series.name)
185            .and_then(|style| style.y_axis)
186            .unwrap_or(series.axis)
187    }
188
189    /// Whether the right axis is shown (hidden series keep it, so the layout holds
190    /// still while toggling them).
191    fn has_y2(&self) -> bool {
192        self.series.iter().any(|series| self.axis_of(series) == YAxis::Right)
193    }
194
195    /// Fetch the visible tiles for every streaming series into owned points. The
196    /// automatic view uses the full row range; a zoomed view asks the pyramid for the
197    /// finest level that fits the series budget.
198    fn materialize_lod(&mut self, state: &PlotState) {
199        let view = state.view();
200        for series in &mut self.series {
201            let Some((pyramid, budget)) = &series.lod else {
202                continue;
203            };
204            let points = match view {
205                Some(bounds) => pyramid.polyline_in_x(bounds.min_x, bounds.max_x, *budget),
206                None => pyramid.polyline(0..pyramid.row_count(), *budget),
207            };
208            if let Ok(points) = points {
209                series.data = std::borrow::Cow::Owned(points);
210            }
211        }
212    }
213
214    /// The right axis for this frame: the state's range, or the automatic one.
215    /// Keep `state.extents` to one current entry per series, computing only new ones.
216    fn refresh_extents(&self, state: &mut PlotState) {
217        let mut extents = Vec::with_capacity(self.series.len());
218        for series in &self.series {
219            let y_scale = match self.axis_of(series) {
220                YAxis::Left => self.config.y.scale,
221                YAxis::Right => self.config.y2.scale,
222            };
223            let key = series.fingerprint(self.config.x.scale, y_scale);
224            let bounds = state
225                .extents
226                .iter()
227                .find(|(cached, _)| *cached == key)
228                .map_or_else(|| series.bounds(self.config.x.scale, y_scale), |(_, bounds)| *bounds);
229            extents.push((key, bounds));
230        }
231        state.extents = extents;
232    }
233
234    fn second_axis(&self, state: &PlotState) -> Option<SecondAxis> {
235        if !self.has_y2() {
236            return None;
237        }
238        let [min, max] = state.y2_view.unwrap_or_else(|| self.auto_y2(state));
239        Some(SecondAxis {
240            min,
241            max,
242            scale: self.config.y2.scale,
243        })
244    }
245}
246
247impl Plot<'_> {
248    /// Paint the plot and handle its interaction.
249    pub fn show(self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
250        if state.pipeline.is_active() {
251            let series = state.pipeline.process(&self.series);
252            if !series.is_empty() {
253                let processed = Plot {
254                    id: self.id,
255                    series,
256                    config: self.config,
257                    width: self.width,
258                    height: self.height,
259                    x_window: self.x_window,
260                    include: self.include,
261                    settings_button: self.settings_button,
262                    export_button: self.export_button,
263                };
264                return processed.show_inner(ui, icons, state);
265            }
266        }
267        self.show_inner(ui, icons, state)
268    }
269
270    fn show_inner(mut self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
271        self.materialize_lod(state);
272        if !state.measurement_customized {
273            state.measurement = self.config.measurement;
274        }
275        let available = ui.available_size();
276        let width = self.width.unwrap_or(available.x).max(120.0);
277        let height = self
278            .height
279            .unwrap_or(if available.y.is_finite() && available.y < 4000.0 {
280                available.y
281            } else {
282                320.0
283            })
284            .max(120.0);
285        let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::click_and_drag());
286        let measure = Measure {
287            ctx: ui.ctx().clone(),
288            pixels_per_point: ui.ctx().pixels_per_point(),
289        };
290        self.refresh_extents(state);
291        let view = state.view.unwrap_or_else(|| self.auto_bounds(state));
292        let y2 = self.second_axis(state);
293        let mode = self.chart_mode();
294        let layout = overlay::layout(&measure, &self.config, rect, view, y2, mode);
295        let transform = Transform {
296            frame: layout.frame,
297            view,
298            x_scale: self.config.x.scale,
299            y_scale: self.config.y.scale,
300            y2,
301        };
302
303        let mut selection_changed = false;
304        let pointer = response.hover_pos().filter(|pos| layout.frame.contains(*pos));
305        if mode == ChartMode::Cartesian {
306            self.interact(ui, &response, &transform, state, pointer, &mut selection_changed);
307        } else if pointer.is_some() {
308            ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
309        }
310        // The transform may have changed; paint with the new view this same frame.
311        let view = state.view.unwrap_or(view);
312        let y2 = y2.map(|axis| match state.y2_view {
313            Some([min, max]) => SecondAxis { min, max, ..axis },
314            None => axis,
315        });
316        let transform = Transform { view, y2, ..transform };
317
318        // The legend interaction runs before the scene: the hovered row feeds the
319        // animation the data layer draws this same frame.
320        let now = ui.input(|input| input.time);
321        let legend = if let Some(legend) = legend::layout(&measure, &self, layout.frame, state, true) {
322            Some(widgets::legend(ui, &self, &legend, layout.frame, state))
323        } else {
324            state.set_legend_hover(None, now);
325            None
326        };
327        let motion = crisol_ui_kit::theme::motion_enabled(ui.ctx());
328        let theme = crisol_ui_kit::theme::current(ui.ctx());
329        let colors = overlay::Colors::resolve(&self.config, ui.visuals());
330        let mut scene = overlay::build_scene(
331            &measure,
332            &self,
333            &layout,
334            &transform,
335            state,
336            &colors,
337            &theme,
338            false,
339            mode,
340            now,
341            motion,
342            {
343                #[cfg(feature = "gpu")]
344                {
345                    self.config.renderer == Renderer::Gpu
346                }
347                #[cfg(not(feature = "gpu"))]
348                {
349                    false
350                }
351            },
352        );
353        // The points each series drew; hover searches these instead of every point.
354        let drawn = std::mem::take(&mut scene.drawn);
355        annotations::paint(&mut scene.data, &transform, &state.annotations, &theme);
356        measure::paint(&mut scene, &measure, &transform, &self, state, &theme);
357        let painter = ui.painter_at(rect);
358        #[cfg(feature = "gpu")]
359        let gpu = self.config.renderer == Renderer::Gpu;
360        #[cfg(feature = "gpu")]
361        if gpu {
362            let lines = gpu::collect(&self, &transform, state, &theme);
363            gpu::paint_lines(ui, layout.frame, &lines, self.id);
364            let triangles = gpu::scene_triangles(&mut scene);
365            gpu::paint_triangles(ui, layout.frame, &triangles, self.id);
366        }
367        scene::paint(&painter, &painter.with_clip_rect(layout.frame), scene);
368        if let (Some(Drag::Box { start, select }), Some(current)) = (state.drag, response.interact_pointer_pos()) {
369            let fill = colors.selection.gamma_multiply(if select { 0.12 } else { 0.06 });
370            painter.with_clip_rect(layout.frame).rect(
371                Rect::from_two_pos(start, current).intersect(layout.frame),
372                0.0,
373                fill,
374                egui::Stroke::new(1.0, colors.selection),
375                egui::StrokeKind::Inside,
376            );
377        }
378        if let (Some(Drag::Measure { start, distance }), Some(current)) = (state.drag, response.interact_pointer_pos())
379        {
380            let clipped = painter.with_clip_rect(layout.frame);
381            if distance || state.measurement.mode == MeasurementMode::CurveSegment {
382                clipped.line_segment([start, current], egui::Stroke::new(1.0, colors.selection));
383            } else {
384                clipped.rect(
385                    Rect::from_two_pos(start, current).intersect(layout.frame),
386                    0.0,
387                    colors.selection.gamma_multiply(0.06),
388                    egui::Stroke::new(1.0, colors.selection),
389                    egui::StrokeKind::Inside,
390                );
391            }
392        }
393
394        let toolbar = widgets::toolbar(ui, icons, &self, layout.frame, &transform, state);
395        let blocked = |pos: Pos2| {
396            legend.is_some_and(|rect| rect.contains(pos)) || toolbar.rect.is_some_and(|rect| rect.contains(pos))
397        };
398        if state.drag.is_none() && toolbar.rect.zip(pointer).is_some_and(|(rect, pos)| rect.contains(pos)) {
399            // Buttons get the ordinary pointer, not the frame's crosshair.
400            ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
401        }
402        let hovered = pointer
403            .filter(|pos| !blocked(*pos) && state.drag.is_none())
404            .and_then(|pointer| {
405                (mode == ChartMode::Cartesian)
406                    .then(|| self.hover(ui, &transform, state, pointer, &theme, &drawn))
407                    .flatten()
408            });
409
410        let clicked = if response.clicked() && state.drag.is_none() {
411            hovered.clone()
412        } else {
413            None
414        };
415        if response.clicked() && state.tool == PlotTool::Select && hovered.is_none() && state.selection.is_some() {
416            state.selection = None;
417            selection_changed = true;
418        }
419
420        let (x_scale, y_scale) = (self.config.x.scale, self.config.y.scale);
421        let data_view = Bounds::from_corners(
422            [x_scale.inverse(view.min_x), y_scale.inverse(view.min_y)],
423            [x_scale.inverse(view.max_x), y_scale.inverse(view.max_y)],
424        );
425        PlotResponse {
426            response,
427            pointer: pointer.map(|pos| transform.to_data(pos)),
428            hovered,
429            clicked,
430            selection_changed,
431            view: data_view,
432            y2_view: y2.map(|axis| [axis.scale.inverse(axis.min), axis.scale.inverse(axis.max)]),
433            frame: transform.frame,
434            settings_requested: toolbar.settings,
435            export_requested: toolbar.export,
436            transform,
437        }
438    }
439}
440
441/// The default series colors: theme tokens first, then fixed hues.
442fn palette(theme: &crisol_ui_kit::theme::Theme, index: usize) -> Color32 {
443    let colors = [
444        theme.link,
445        theme.warning,
446        theme.success,
447        theme.danger,
448        theme.done,
449        Color32::from_rgb(0x1f, 0xb5, 0xb5),
450        Color32::from_rgb(0xd9, 0x5d, 0xb4),
451        Color32::from_rgb(0x8c, 0x8c, 0x3c),
452    ];
453    colors[index % colors.len()]
454}
455
456impl IconComponent for Plot<'_> {
457    type Output = PlotResponse;
458
459    fn show(self, ui: &mut Ui, icons: &mut Icons) -> PlotResponse {
460        let id = self.id;
461        let mut state = ui
462            .ctx()
463            .data_mut(|data| data.get_temp::<PlotState>(id).unwrap_or_default());
464        let response = Plot::show(self, ui, icons, &mut state);
465        ui.ctx().data_mut(|data| data.insert_temp(id, state));
466        response
467    }
468}
469
470#[cfg(test)]
471mod tests;