Skip to content

Introduce type parameter for plot points #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
65 changes: 63 additions & 2 deletions demo/src/plot_demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::f64::consts::TAU;
use std::ops::RangeInclusive;

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

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

impl Default for Panel {
Expand All @@ -44,6 +45,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 @@ -88,6 +90,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 @@ -117,6 +120,9 @@ impl PlotDemo {
Panel::LinkedAxes => {
self.linked_axes_demo.ui(ui);
}
Panel::Userdata => {
self.userdata_demo.ui(ui);
}
}
}
}
Expand Down Expand Up @@ -565,7 +571,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 @@ -1101,6 +1107,61 @@ impl ChartsDemo {
}
}

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

struct DemoPoint {
x: f64,
y: f64,
custom_thing: 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_thing: i % 2 == 0,
})
.collect::<Vec<_>>();

let custom_things =
std::sync::Arc::new(egui::mutex::Mutex::new(std::collections::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_thing);
}

plot_ui
.line(Line::new(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.
18 changes: 10 additions & 8 deletions egui_plot/src/items/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,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 @@ -88,8 +88,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 @@ -112,6 +112,7 @@ pub trait PlotItem {
rulers_at_value(
pointer,
value,
id.map(|id| (id, elem.index)),
self.name(),
plot,
shapes,
Expand Down Expand Up @@ -606,7 +607,7 @@ impl<'a> PlotItem for Line<'a> {
}

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

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

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

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

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

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

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

fn bounds(&self) -> PlotBounds {
Expand Down Expand Up @@ -2040,6 +2041,7 @@ fn add_rulers_and_text(
pub(super) fn rulers_at_value(
pointer: Pos2,
value: PlotPoint,
item: Option<(Id, usize)>,
name: &str,
plot: &PlotConfig<'_>,
shapes: &mut Vec<Shape>,
Expand All @@ -2064,7 +2066,7 @@ pub(super) fn rulers_at_value(
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 let Some(custom_label) = label_formatter {
custom_label(name, &value)
custom_label(name, &value, item)
} else if plot.show_x && plot.show_y {
format!(
"{}x = {:.*}\ny = {:.*}",
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,6 +1,6 @@
use std::ops::{Bound, RangeBounds, RangeInclusive};

use egui::{lerp, Pos2, Shape, Stroke, Vec2};
use egui::{lerp, Id, Pos2, Shape, Stroke, Vec2};

use crate::transform::PlotBounds;

Expand Down Expand Up @@ -382,7 +382,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
7 changes: 4 additions & 3 deletions egui_plot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,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 @@ -397,7 +397,7 @@ impl<'a> Plot<'a> {
/// }).collect();
/// let line = Line::new(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 @@ -409,7 +409,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 @@ -1716,6 +1716,7 @@ impl<'a> PreparedPlot<'a> {
items::rulers_at_value(
pointer,
value,
None,
"",
&plot,
shapes,
Expand Down
Loading