Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 149 additions & 2 deletions demo/src/plot_demo.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::collections::HashMap;
use std::ops::RangeInclusive;
use std::{f64::consts::TAU, sync::Arc};

use egui::mutex::Mutex;
use egui::{
Checkbox, Color32, ComboBox, NumExt as _, Pos2, Response, ScrollArea, Stroke, TextWrapMode,
Checkbox, Color32, ComboBox, Id, NumExt as _, Pos2, Response, ScrollArea, Stroke, TextWrapMode,
Vec2b, WidgetInfo, WidgetType, remap, vec2,
};

Expand All @@ -24,6 +26,7 @@ enum Panel {
Interaction,
CustomAxes,
LinkedAxes,
Userdata,
}

impl Default for Panel {
Expand All @@ -44,6 +47,7 @@ pub struct PlotDemo {
interaction_demo: InteractionDemo,
custom_axes_demo: CustomAxesDemo,
linked_axes_demo: LinkedAxesDemo,
userdata_demo: UserdataDemo,
open_panel: Panel,
}

Expand Down Expand Up @@ -124,6 +128,7 @@ impl PlotDemo {
ui.selectable_value(&mut self.open_panel, Panel::Interaction, "Interaction");
ui.selectable_value(&mut self.open_panel, Panel::CustomAxes, "Custom Axes");
ui.selectable_value(&mut self.open_panel, Panel::LinkedAxes, "Linked Axes");
ui.selectable_value(&mut self.open_panel, Panel::Userdata, "Userdata");
});
ui.separator();

Expand Down Expand Up @@ -152,6 +157,9 @@ impl PlotDemo {
Panel::LinkedAxes => {
self.linked_axes_demo.ui(ui);
}
Panel::Userdata => {
self.userdata_demo.ui(ui);
}
}
}
}
Expand Down Expand Up @@ -642,7 +650,7 @@ impl CustomAxesDemo {
}
};

let label_fmt = |_s: &str, val: &PlotPoint| {
let label_fmt = |_s: &str, val: &PlotPoint, _| {
format!(
"Day {d}, {h}:{m:02}\n{p:.2}%",
d = day(val.x),
Expand Down Expand Up @@ -1197,6 +1205,145 @@ impl ChartsDemo {
}
}

#[derive(PartialEq, serde::Deserialize, serde::Serialize, Default)]
struct UserdataDemo {}

#[derive(Clone)]
struct DemoPoint {
x: f64,
y: f64,
custom_label: String,
importance: f32,
}

impl UserdataDemo {
#[expect(clippy::unused_self, clippy::significant_drop_tightening)]
fn ui(&self, ui: &mut egui::Ui) -> Response {
ui.label(
"This demo shows how to attach custom data to plot items and display it in tooltips.",
);
ui.separator();

// Create multiple datasets with custom metadata
let sine_points = (0..=500)
.map(|i| {
let x = i as f64 / 100.0;
DemoPoint {
x,
y: x.sin(),
custom_label: format!("Sine #{i}"),
importance: (i % 100) as f32 / 100.0,
}
})
.collect::<Vec<_>>();

let cosine_points = (0..=500)
.map(|i| {
let x = i as f64 / 100.0;
DemoPoint {
x,
y: x.cos(),
custom_label: format!("Cosine #{i}"),
importance: (1.0 - (i % 100) as f32 / 100.0),
}
})
.collect::<Vec<_>>();

let damped_points = (0..=500)
.map(|i| {
let x = i as f64 / 100.0;
DemoPoint {
x,
y: (-x * 0.5).exp() * (2.0 * x).sin(),
custom_label: format!("Damped #{i}"),
importance: if i % 50 == 0 { 1.0 } else { 0.3 },
}
})
.collect::<Vec<_>>();

// Store custom data in a shared map
let custom_data = Arc::new(Mutex::new(HashMap::<Id, Vec<DemoPoint>>::new()));

let custom_data_ = custom_data.clone();
Plot::new("Userdata Plot Demo")
.legend(Legend::default().position(Corner::LeftTop))
.label_formatter(move |name, value, item| {
if let Some((id, index)) = item {
let lock = custom_data_.lock();
if let Some(points) = lock.get(&id) {
if let Some(point) = points.get(index) {
return format!(
"{}\nPosition: ({:.3}, {:.3})\nLabel: {}\nImportance: {:.1}%",
name,
value.x,
value.y,
point.custom_label,
point.importance * 100.0
);
}
}
}
format!("{}\n({:.3}, {:.3})", name, value.x, value.y)
})
.show(ui, |plot_ui| {
let mut lock = custom_data.lock();

// Sine wave with custom data
let sine_id = Id::new("sine_wave");
lock.insert(sine_id, sine_points.clone());
plot_ui.line(
Line::new(
"sin(x)",
sine_points.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
)
.id(sine_id)
.color(Color32::from_rgb(200, 100, 100)),
);

// Cosine wave with custom data
let cosine_id = Id::new("cosine_wave");
lock.insert(cosine_id, cosine_points.clone());
plot_ui.line(
Line::new(
"cos(x)",
cosine_points.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
)
.id(cosine_id)
.color(Color32::from_rgb(100, 200, 100)),
);

// Damped sine wave with custom data
let damped_id = Id::new("damped_wave");
lock.insert(damped_id, damped_points.clone());
plot_ui.line(
Line::new(
"e^(-0.5x) · sin(2x)",
damped_points.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
)
.id(damped_id)
.color(Color32::from_rgb(100, 100, 200)),
);

// Add some points with high importance as markers
let important_points: Vec<_> = damped_points
.iter()
.filter(|p| p.importance > 0.9)
.map(|p| [p.x, p.y])
.collect();

if !important_points.is_empty() {
plot_ui.points(
Points::new("Important Points", important_points)
.color(Color32::from_rgb(255, 150, 0))
.radius(4.0)
.shape(MarkerShape::Diamond),
);
}
})
.response
}
}

fn is_approx_zero(val: f64) -> bool {
val.abs() < 1e-6
}
Expand Down
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Charts.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Custom Axes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Interaction.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Items.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Legend.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Lines.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Linked Axes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/demos/Markers.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions demo/tests/snapshots/demos/Userdata.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/light_mode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/scale_0.50.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/scale_1.00.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/scale_1.39.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions demo/tests/snapshots/scale_2.00.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 13 additions & 9 deletions egui_plot/src/items/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ pub trait PlotItem {
match self.geometry() {
PlotGeometry::None => None,

PlotGeometry::Points(points) => points
PlotGeometry::Points(points, _) => points
.iter()
.enumerate()
.map(|(index, value)| {
Expand All @@ -168,8 +168,8 @@ pub trait PlotItem {
plot: &PlotConfig<'_>,
label_formatter: &LabelFormatter<'_>,
) {
let points = match self.geometry() {
PlotGeometry::Points(points) => points,
let (points, id) = match self.geometry() {
PlotGeometry::Points(points, id) => (points, id),
PlotGeometry::None => {
panic!("If the PlotItem has no geometry, on_hover() must not be called")
}
Expand All @@ -192,6 +192,7 @@ pub trait PlotItem {
rulers_and_tooltip_at_value(
plot_area_response,
value,
id.map(|id| (id, elem.index)),
self.name(),
plot,
cursors,
Expand Down Expand Up @@ -603,7 +604,7 @@ impl PlotItem for Line<'_> {
}

fn geometry(&self) -> PlotGeometry<'_> {
PlotGeometry::Points(self.series.points())
PlotGeometry::Points(self.series.points(), Some(self.id()))
}

fn bounds(&self) -> PlotBounds {
Expand Down Expand Up @@ -705,7 +706,7 @@ impl PlotItem for Polygon<'_> {
}

fn geometry(&self) -> PlotGeometry<'_> {
PlotGeometry::Points(self.series.points())
PlotGeometry::Points(self.series.points(), Some(self.id()))
}

fn bounds(&self) -> PlotBounds {
Expand Down Expand Up @@ -1025,7 +1026,7 @@ impl PlotItem for Points<'_> {
}

fn geometry(&self) -> PlotGeometry<'_> {
PlotGeometry::Points(self.series.points())
PlotGeometry::Points(self.series.points(), Some(self.id()))
}

fn bounds(&self) -> PlotBounds {
Expand Down Expand Up @@ -1136,7 +1137,7 @@ impl PlotItem for Arrows<'_> {
}

fn geometry(&self) -> PlotGeometry<'_> {
PlotGeometry::Points(self.origins.points())
PlotGeometry::Points(self.origins.points(), Some(self.id()))
}

fn bounds(&self) -> PlotBounds {
Expand Down Expand Up @@ -1705,6 +1706,7 @@ fn add_rulers_and_text(
pub(super) fn rulers_and_tooltip_at_value(
plot_area_response: &egui::Response,
value: PlotPoint,
item: Option<(Id, usize)>,
name: &str,
plot: &PlotConfig<'_>,
cursors: &mut Vec<Cursor>,
Expand All @@ -1718,7 +1720,7 @@ pub(super) fn rulers_and_tooltip_at_value(
}

let text = if let Some(custom_label) = label_formatter {
let label = custom_label(name, &value);
let label = custom_label(name, &value, None);
if label.is_empty() {
return;
}
Expand All @@ -1732,7 +1734,9 @@ pub(super) fn rulers_and_tooltip_at_value(
let scale = plot.transform.dvalue_dpos();
let x_decimals = ((-scale[0].abs().log10()).ceil().at_least(0.0) as usize).clamp(1, 6);
let y_decimals = ((-scale[1].abs().log10()).ceil().at_least(0.0) as usize).clamp(1, 6);
if plot.show_x && plot.show_y {
if let Some(custom_label) = label_formatter {
custom_label(name, &value, item)
} else if plot.show_x && plot.show_y {
format!(
"{}x = {:.*}\ny = {:.*}",
prefix, x_decimals, value.x, y_decimals, value.y
Expand Down
4 changes: 2 additions & 2 deletions egui_plot/src/items/values.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::ops::{Bound, RangeBounds, RangeInclusive};

use egui::{
Pos2, Rect, Shape, Stroke, Vec2,
Id, Pos2, Rect, Shape, Stroke, Vec2,
epaint::{ColorMode, PathStroke},
lerp, pos2,
};
Expand Down Expand Up @@ -397,7 +397,7 @@ pub enum PlotGeometry<'a> {
None,

/// Point values (X-Y graphs)
Points(&'a [PlotPoint]),
Points(&'a [PlotPoint], Option<Id>),

/// Rectangles (examples: boxes or bars)
// Has currently no data, as it would require copying rects or iterating a list of pointers.
Expand Down
Loading
Loading