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    /// The right axis for this frame: the state's range, or the automatic one.
196    /// Keep `state.extents` to one current entry per series, computing only new ones.
197    fn refresh_extents(&self, state: &mut PlotState) {
198        let mut extents = Vec::with_capacity(self.series.len());
199        for series in &self.series {
200            let y_scale = match self.axis_of(series) {
201                YAxis::Left => self.config.y.scale,
202                YAxis::Right => self.config.y2.scale,
203            };
204            let key = series.fingerprint(self.config.x.scale, y_scale);
205            let bounds = state
206                .extents
207                .iter()
208                .find(|(cached, _)| *cached == key)
209                .map_or_else(|| series.bounds(self.config.x.scale, y_scale), |(_, bounds)| *bounds);
210            extents.push((key, bounds));
211        }
212        state.extents = extents;
213    }
214
215    fn second_axis(&self, state: &PlotState) -> Option<SecondAxis> {
216        if !self.has_y2() {
217            return None;
218        }
219        let [min, max] = state.y2_view.unwrap_or_else(|| self.auto_y2(state));
220        Some(SecondAxis {
221            min,
222            max,
223            scale: self.config.y2.scale,
224        })
225    }
226}
227
228impl Plot<'_> {
229    /// Paint the plot and handle its interaction.
230    pub fn show(self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
231        if state.pipeline.is_active() {
232            let series = state.pipeline.process(&self.series);
233            if !series.is_empty() {
234                let processed = Plot {
235                    id: self.id,
236                    series,
237                    config: self.config,
238                    width: self.width,
239                    height: self.height,
240                    x_window: self.x_window,
241                    include: self.include,
242                    settings_button: self.settings_button,
243                    export_button: self.export_button,
244                };
245                return processed.show_inner(ui, icons, state);
246            }
247        }
248        self.show_inner(ui, icons, state)
249    }
250
251    fn show_inner(self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> PlotResponse {
252        if !state.measurement_customized {
253            state.measurement = self.config.measurement;
254        }
255        let available = ui.available_size();
256        let width = self.width.unwrap_or(available.x).max(120.0);
257        let height = self
258            .height
259            .unwrap_or(if available.y.is_finite() && available.y < 4000.0 {
260                available.y
261            } else {
262                320.0
263            })
264            .max(120.0);
265        let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::click_and_drag());
266        let measure = Measure {
267            ctx: ui.ctx().clone(),
268            pixels_per_point: ui.ctx().pixels_per_point(),
269        };
270        self.refresh_extents(state);
271        let view = state.view.unwrap_or_else(|| self.auto_bounds(state));
272        let y2 = self.second_axis(state);
273        let mode = self.chart_mode();
274        let layout = overlay::layout(&measure, &self.config, rect, view, y2, mode);
275        let transform = Transform {
276            frame: layout.frame,
277            view,
278            x_scale: self.config.x.scale,
279            y_scale: self.config.y.scale,
280            y2,
281        };
282
283        let mut selection_changed = false;
284        let pointer = response.hover_pos().filter(|pos| layout.frame.contains(*pos));
285        if mode == ChartMode::Cartesian {
286            self.interact(ui, &response, &transform, state, pointer, &mut selection_changed);
287        } else if pointer.is_some() {
288            ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
289        }
290        // The transform may have changed; paint with the new view this same frame.
291        let view = state.view.unwrap_or(view);
292        let y2 = y2.map(|axis| match state.y2_view {
293            Some([min, max]) => SecondAxis { min, max, ..axis },
294            None => axis,
295        });
296        let transform = Transform { view, y2, ..transform };
297
298        // The legend interaction runs before the scene: the hovered row feeds the
299        // animation the data layer draws this same frame.
300        let now = ui.input(|input| input.time);
301        let legend = if let Some(legend) = legend::layout(&measure, &self, layout.frame, state, true) {
302            Some(widgets::legend(ui, &self, &legend, layout.frame, state))
303        } else {
304            state.set_legend_hover(None, now);
305            None
306        };
307        let motion = crisol_ui_kit::theme::motion_enabled(ui.ctx());
308        let theme = crisol_ui_kit::theme::current(ui.ctx());
309        let colors = overlay::Colors::resolve(&self.config, ui.visuals());
310        let mut scene = overlay::build_scene(
311            &measure,
312            &self,
313            &layout,
314            &transform,
315            state,
316            &colors,
317            &theme,
318            false,
319            mode,
320            now,
321            motion,
322            {
323                #[cfg(feature = "gpu")]
324                {
325                    self.config.renderer == Renderer::Gpu
326                }
327                #[cfg(not(feature = "gpu"))]
328                {
329                    false
330                }
331            },
332        );
333        // The points each series drew; hover searches these instead of every point.
334        let drawn = std::mem::take(&mut scene.drawn);
335        annotations::paint(&mut scene.data, &transform, &state.annotations, &theme);
336        measure::paint(&mut scene, &measure, &transform, &self, state, &theme);
337        let painter = ui.painter_at(rect);
338        #[cfg(feature = "gpu")]
339        let gpu = self.config.renderer == Renderer::Gpu;
340        #[cfg(feature = "gpu")]
341        if gpu {
342            let lines = gpu::collect(&self, &transform, state, &theme);
343            gpu::paint_lines(ui, layout.frame, &lines, self.id);
344        }
345        scene::paint(&painter, &painter.with_clip_rect(layout.frame), scene);
346        if let (Some(Drag::Box { start, select }), Some(current)) = (state.drag, response.interact_pointer_pos()) {
347            let fill = colors.selection.gamma_multiply(if select { 0.12 } else { 0.06 });
348            painter.with_clip_rect(layout.frame).rect(
349                Rect::from_two_pos(start, current).intersect(layout.frame),
350                0.0,
351                fill,
352                egui::Stroke::new(1.0, colors.selection),
353                egui::StrokeKind::Inside,
354            );
355        }
356        if let (Some(Drag::Measure { start, distance }), Some(current)) = (state.drag, response.interact_pointer_pos())
357        {
358            let clipped = painter.with_clip_rect(layout.frame);
359            if distance || state.measurement.mode == MeasurementMode::CurveSegment {
360                clipped.line_segment([start, current], egui::Stroke::new(1.0, colors.selection));
361            } else {
362                clipped.rect(
363                    Rect::from_two_pos(start, current).intersect(layout.frame),
364                    0.0,
365                    colors.selection.gamma_multiply(0.06),
366                    egui::Stroke::new(1.0, colors.selection),
367                    egui::StrokeKind::Inside,
368                );
369            }
370        }
371
372        let toolbar = widgets::toolbar(ui, icons, &self, layout.frame, &transform, state);
373        let blocked = |pos: Pos2| {
374            legend.is_some_and(|rect| rect.contains(pos)) || toolbar.rect.is_some_and(|rect| rect.contains(pos))
375        };
376        if state.drag.is_none() && toolbar.rect.zip(pointer).is_some_and(|(rect, pos)| rect.contains(pos)) {
377            // Buttons get the ordinary pointer, not the frame's crosshair.
378            ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
379        }
380        let hovered = pointer
381            .filter(|pos| !blocked(*pos) && state.drag.is_none())
382            .and_then(|pointer| {
383                (mode == ChartMode::Cartesian)
384                    .then(|| self.hover(ui, &transform, state, pointer, &theme, &drawn))
385                    .flatten()
386            });
387
388        let clicked = if response.clicked() && state.drag.is_none() {
389            hovered.clone()
390        } else {
391            None
392        };
393        if response.clicked() && state.tool == PlotTool::Select && hovered.is_none() && state.selection.is_some() {
394            state.selection = None;
395            selection_changed = true;
396        }
397
398        let (x_scale, y_scale) = (self.config.x.scale, self.config.y.scale);
399        let data_view = Bounds::from_corners(
400            [x_scale.inverse(view.min_x), y_scale.inverse(view.min_y)],
401            [x_scale.inverse(view.max_x), y_scale.inverse(view.max_y)],
402        );
403        PlotResponse {
404            response,
405            pointer: pointer.map(|pos| transform.to_data(pos)),
406            hovered,
407            clicked,
408            selection_changed,
409            view: data_view,
410            y2_view: y2.map(|axis| [axis.scale.inverse(axis.min), axis.scale.inverse(axis.max)]),
411            frame: transform.frame,
412            settings_requested: toolbar.settings,
413            export_requested: toolbar.export,
414            transform,
415        }
416    }
417}
418
419/// The default series colors: theme tokens first, then fixed hues.
420fn palette(theme: &crisol_ui_kit::theme::Theme, index: usize) -> Color32 {
421    let colors = [
422        theme.link,
423        theme.warning,
424        theme.success,
425        theme.danger,
426        theme.done,
427        Color32::from_rgb(0x1f, 0xb5, 0xb5),
428        Color32::from_rgb(0xd9, 0x5d, 0xb4),
429        Color32::from_rgb(0x8c, 0x8c, 0x3c),
430    ];
431    colors[index % colors.len()]
432}
433
434impl IconComponent for Plot<'_> {
435    type Output = PlotResponse;
436
437    fn show(self, ui: &mut Ui, icons: &mut Icons) -> PlotResponse {
438        let id = self.id;
439        let mut state = ui
440            .ctx()
441            .data_mut(|data| data.get_temp::<PlotState>(id).unwrap_or_default());
442        let response = Plot::show(self, ui, icons, &mut state);
443        ui.ctx().data_mut(|data| data.insert_temp(id, state));
444        response
445    }
446}
447
448#[cfg(test)]
449mod tests;