1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! Custom tick label formatting (matplotlib `FuncFormatter` / `StrMethodFormatter`).
use std::fmt;
use std::sync::Arc;
/// Formats a tick value as a label string.
///
/// Use [`TickFormatter::new`] for arbitrary closures (matplotlib
/// `FuncFormatter`), or the helpers [`fixed`](Self::fixed) /
/// [`percent`](Self::percent) / [`scientific`](Self::scientific).
///
/// ```
/// use plotine::prelude::*;
///
/// let png = Figure::new().size(4.0, 3.0).dpi(72.0).axes(|ax| {
/// ax.line([0.0, 1.0, 2.0], [0.0, 0.5, 1.0]);
/// ax.y_tick_formatter(TickFormatter::percent(0));
/// ax.title("pct");
/// }).render_png().unwrap();
/// assert!(!png.is_empty());
/// ```
#[derive(Clone)]
pub struct TickFormatter {
format: Arc<dyn Fn(f64) -> String + Send + Sync>,
}
impl fmt::Debug for TickFormatter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("TickFormatter")
}
}
impl TickFormatter {
/// Wrap a custom formatter closure.
pub fn new<F>(f: F) -> Self
where
F: Fn(f64) -> String + Send + Sync + 'static,
{
Self {
format: Arc::new(f),
}
}
/// Fixed decimal places (`"{x:.{n}f}"` style).
pub fn fixed(decimals: usize) -> Self {
let n = decimals.min(12);
Self::new(move |v| {
if !v.is_finite() {
return String::new();
}
let s = format!("{v:.n$}");
s.replace('-', "\u{2212}")
})
}
/// Percentage of the raw value (`v * 100` with `decimals` places + `%`).
pub fn percent(decimals: usize) -> Self {
let n = decimals.min(12);
Self::new(move |v| {
if !v.is_finite() {
return String::new();
}
let s = format!("{:.n$}%", v * 100.0);
s.replace('-', "\u{2212}")
})
}
/// Scientific notation with `decimals` digits after the point.
pub fn scientific(decimals: usize) -> Self {
let n = decimals.min(12);
Self::new(move |v| {
if !v.is_finite() {
return String::new();
}
let s = format!("{v:.n$e}");
s.replace('-', "\u{2212}")
})
}
/// Format one tick value.
pub fn format(&self, value: f64) -> String {
(self.format)(value)
}
}