1mod 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#[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 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 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 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 fn has_y2(&self) -> bool {
192 self.series.iter().any(|series| self.axis_of(series) == YAxis::Right)
193 }
194
195 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 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 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 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 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 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
419fn 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;