Skip to content
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

Example: semi-log and log-log plots #4564

Closed
wants to merge 9 commits into from
Closed
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
9 changes: 9 additions & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2825,6 +2825,15 @@ dependencies = [
"time",
]

[[package]]
name = "plot_log_scale"
version = "0.1.0"
dependencies = [
"eframe",
"egui_plot",
"env_logger",
]

[[package]]
name = "png"
version = "0.17.10"
Expand Down
23 changes: 23 additions & 0 deletions examples/plot_log_scale/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "plot_log_scale"
version = "0.1.0"
authors = ["Ygor Souza <[email protected]>"]
license = "MIT OR Apache-2.0"
edition = "2021"
rust-version = "1.76"
publish = false

[lints]
workspace = true


[dependencies]
eframe = { workspace = true, features = [
"default",
"__screenshot", # __screenshot is so we can dump a screenshot using EFRAME_SCREENSHOT_TO
] }
egui_plot.workspace = true
env_logger = { version = "0.10", default-features = false, features = [
"auto-color",
"humantime",
] }
7 changes: 7 additions & 0 deletions examples/plot_log_scale/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Example how to display semi-log and log-log plots

```sh
cargo run -p plot_log_scale
```

![](screenshot.png)
181 changes: 181 additions & 0 deletions examples/plot_log_scale/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
//! This example shows how to implement semi-log and log-log plots
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
#![allow(rustdoc::missing_crate_level_docs)] // it's an example

use std::ops::RangeInclusive;

use eframe::egui::{self};
use egui_plot::{GridInput, GridMark, Legend, Line};

fn main() -> Result<(), eframe::Error> {
env_logger::init(); // Log to stderr (if you run with `RUST_LOG=debug`).
let options = eframe::NativeOptions::default();
eframe::run_native(
"Plot",
options,
Box::new(|_cc| Ok(Box::<PlotExample>::default())),
)
}

struct PlotExample {
log_x: bool,
log_y: bool,
signals: Vec<Signal>,
}

struct Signal {
name: &'static str,
points: Vec<[f64; 2]>,
}

impl Default for PlotExample {
fn default() -> Self {
let x = (-2000..2000).map(|x| x as f64 / 100.0);
let signals = vec![
Signal {
name: "y=x",
points: x.clone().map(|x| [x, x]).collect(),
},
Signal {
name: "y=x^2",
points: x.clone().map(|x| [x, x.powi(2)]).collect(),
},
Signal {
name: "y=exp(x)",
points: x.clone().map(|x| [x, x.exp()]).collect(),
},
Signal {
name: "y=ln(x)",
points: x.clone().map(|x| [x, x.ln()]).collect(),
},
];
Self {
log_x: true,
log_y: true,
signals,
}
}
}

impl eframe::App for PlotExample {
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
egui::SidePanel::left("options").show(ctx, |ui| {
ui.checkbox(&mut self.log_x, "X axis log scale");
ui.checkbox(&mut self.log_y, "Y axis log scale");
});
let log_x = self.log_x;
let log_y = self.log_y;
egui::CentralPanel::default().show(ctx, |ui| {
let mut plot = egui_plot::Plot::new("plot")
.legend(Legend::default())
.label_formatter(|name, value| {
let x = if log_x {
10.0f64.powf(value.x)
} else {
value.x
};
let y = if log_y {
10.0f64.powf(value.y)
} else {
value.y
};
if !name.is_empty() {
format!("{name}: {x:.3}, {y:.3}")
} else {
format!("{x:.3}, {y:.3}")
}
});
if log_x {
plot = plot
.x_grid_spacer(log_axis_spacer)
.x_axis_formatter(log_axis_formatter);
}
if log_y {
plot = plot
.y_grid_spacer(log_axis_spacer)
.y_axis_formatter(log_axis_formatter);
}
plot.show(ui, |plot_ui| {
for signal in &self.signals {
let points: Vec<_> = signal
.points
.iter()
.copied()
.map(|[x, y]| {
let x = if log_x { x.log10() } else { x };
let y = if log_y { y.log10() } else { y };
Comment on lines +105 to +106
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when x or y is negative, log10 is not valid and returns NaN

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, normally you can't represent non-positive numbers on a log scale. Apparently there is a modified transform that allows that, but I think this starts to get too complicated for this example.

It is also noteworthy that the infinity value produced when we take the log of 0 causes the autobounds to stop working (it does not seem to be bothered by the NaNs though), so that is something that could be looked into, but in a separate PR.

Copy link

@hyumo hyumo Jun 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I am basically trying to do a bode plot, I will just do a semi-log! Thanks a lot

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, for a Bode plot the y axis is in dB, so you don't need the log scale for it.

[x, y]
})
.collect();
plot_ui.line(Line::new(points).name(signal.name));
}
});
});
}
}

#[allow(clippy::needless_pass_by_value)]
fn log_axis_spacer(input: GridInput) -> Vec<GridMark> {
let (min, max) = input.bounds;
let min_decade = min.floor().max(-300.0) as i32;
let max_decade = max.ceil().min(300.0) as i32;
let span = max_decade - min_decade;
let mut marks = vec![];
for i in min_decade..=max_decade {
if span >= 100 {
let value = i as f64;
let step_size = if i % 10 == 0 { 10.0 } else { 1.0 };
let mark = GridMark { value, step_size };
marks.push(mark);
} else if span >= 10 {
marks.extend(
(1..10)
.map(|j| {
let value = i as f64 + (j as f64).log10();
let step_size = if j == 1 && i % 10 == 0 {
10.0
} else if j == 1 {
1.0
} else {
0.1
};
GridMark { value, step_size }
})
.filter(|gm| (min..=max).contains(&gm.value)),
);
} else {
marks.extend(
(10..100)
.map(|j| {
let value = i as f64 + (j as f64).log10() - 1.0;
let step_size = if j == 10 {
1.0
} else if j % 10 == 0 {
0.1
} else {
0.01
};
GridMark { value, step_size }
})
.filter(|gm| (min..=max).contains(&gm.value)),
);
}
}
marks
}

fn log_axis_formatter(gm: GridMark, _bounds: &RangeInclusive<f64>) -> String {
let max_size = 5;
let min_precision = (-gm.value + 1.0).ceil().clamp(1.0, 10.0) as usize;
let digits = (gm.value).ceil().max(1.0) as usize;
let size = digits + min_precision + 1;
let value = 10.0f64.powf(gm.value);
if size < max_size {
let precision = max_size.saturating_sub(digits + 1).max(1);
egui::emath::format_with_decimals_in_range(value, 1..=precision)
} else {
let exp_digits = (digits as f64).log10() as usize;
let precision = max_size.saturating_sub(exp_digits).saturating_sub(3);
format!("{value:.precision$e}")
}
}
Loading