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
68 changes: 66 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 @@ -131,6 +135,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 @@ -160,6 +165,9 @@ impl PlotDemo {
Panel::LinkedAxes => {
self.linked_axes_demo.ui(ui);
}
Panel::Userdata => {
self.userdata_demo.ui(ui);
}
}
}
}
Expand Down Expand Up @@ -636,7 +644,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 @@ -1191,6 +1199,62 @@ impl ChartsDemo {
}
}

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

struct DemoPoint {
x: f64,
y: f64,
custom_info: bool,
}

impl UserdataDemo {
#[allow(clippy::unused_self, clippy::significant_drop_tightening)]
fn ui(&self, ui: &mut egui::Ui) -> Response {
let points = (1..=1000)
.map(|i| DemoPoint {
x: i as f64 / 1000.0,
y: ((i as f64) / 1000.0 * std::f64::consts::PI * 2.0).sin(),
custom_info: i % 2 == 0,
})
.collect::<Vec<_>>();

let custom_things = Arc::new(Mutex::new(HashMap::<Id, Vec<bool>>::new()));

let custom_things_ = custom_things.clone();
Plot::new("Userdata Plot Demo")
.legend(Legend::default())
.label_formatter(|_, _, item| {
format!(
"item: {:?}\ncustom_thing: {:?}",
item,
item.and_then(|(id, index)| custom_things_
.lock()
.get(&id)
.and_then(|vec| vec.get(index).copied()))
)
})
.show(ui, |plot_ui| {
let id = Id::new(1234);
let mut lock = custom_things.lock();
let entry = lock.entry(id).or_default();

for p in &points {
entry.push(p.custom_info);
}

plot_ui.line(
Line::new(
"test",
points.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
)
.id(id),
);
})
.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 @@ -138,7 +138,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 @@ -163,8 +163,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 @@ -187,6 +187,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 @@ -590,7 +591,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 @@ -692,7 +693,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 @@ -1013,7 +1014,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 @@ -1124,7 +1125,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 @@ -1694,6 +1695,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 @@ -1707,7 +1709,7 @@ pub(super) fn rulers_and_tooltip_at_value(
}

let text = if let Some(custom_label) = label_formatter {
custom_label(name, &value)
custom_label(name, &value, None)
} else {
let prefix = if name.is_empty() {
String::new()
Expand All @@ -1717,7 +1719,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
11 changes: 8 additions & 3 deletions egui_plot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use axis::AxisWidget;
use items::{horizontal_line, rulers_color, vertical_line};
use legend::LegendWidget;

type LabelFormatterFn<'a> = dyn Fn(&str, &PlotPoint) -> String + 'a;
type LabelFormatterFn<'a> = dyn Fn(&str, &PlotPoint, Option<(Id, usize)>) -> String + 'a;
pub type LabelFormatter<'a> = Option<Box<LabelFormatterFn<'a>>>;

type GridSpacerFn<'a> = dyn Fn(GridInput) -> Vec<GridMark> + 'a;
Expand Down Expand Up @@ -402,6 +402,10 @@ impl<'a> Plot<'a> {
}

/// Provide a function to customize the on-hover label for the x and y axis
/// ## `build_fn` parameter
/// The third parameter, `build_fn`, is a closure that is called with a mutable reference to a [`PlotUi`] instance.
/// Within this closure, you can add items (such as lines, points, bars, etc.) to the plot and interact with the plot UI.
/// The closure should return any value you wish to propagate from the plot construction (for example, a reference to a plot item, or a custom result).
///
/// ```
/// # egui::__run_test_ui(|ui| {
Expand All @@ -412,7 +416,7 @@ impl<'a> Plot<'a> {
/// }).collect();
/// let line = Line::new("sin", sin);
/// Plot::new("my_plot").view_aspect(2.0)
/// .label_formatter(|name, value| {
/// .label_formatter(|name, value, _| {
/// if !name.is_empty() {
/// format!("{}: {:.*}%", name, 1, value.y)
/// } else {
Expand All @@ -424,7 +428,7 @@ impl<'a> Plot<'a> {
/// ```
pub fn label_formatter(
mut self,
label_formatter: impl Fn(&str, &PlotPoint) -> String + 'a,
label_formatter: impl Fn(&str, &PlotPoint, Option<(Id, usize)>) -> String + 'a,
) -> Self {
self.label_formatter = Some(Box::new(label_formatter));
self
Expand Down Expand Up @@ -1858,6 +1862,7 @@ impl PreparedPlot<'_> {
items::rulers_and_tooltip_at_value(
plot_area_response,
value,
None,
"",
&plot,
&mut cursors,
Expand Down
Loading