Skip to main content

ggplot_rs/position/
jitter.rs

1use crate::data::{DataFrame, Value};
2use crate::rng::SplitMix64;
3
4use super::{Position, PositionParams};
5
6/// Default seed: the same data must render the same SVG (stable snapshots,
7/// cacheable output, no flicker when a host re-renders), as with ggplot2's
8/// `position_jitter(seed = …)`.
9pub const JITTER_SEED: u64 = 0x6A17_7E2D;
10
11/// Add random noise to x and y positions to reduce overplotting.
12///
13/// Each value moves by a uniform amount in `[-width, width)` (x) and
14/// `[-height, height)` (y). `None` (the default) means "40% of the data's
15/// resolution", as in ggplot2: the smallest gap between distinct values, or 1
16/// for integer/constant data — so integer-coded categories (1, 2, 3, …) get
17/// ±0.4 and finely-spaced continuous data gets proportionally small noise.
18/// `Some(0.0)` disables jitter along that axis.
19#[derive(Clone, Debug)]
20pub struct PositionJitter {
21    /// Horizontal jitter amount in data units; `None` = 0.4 × resolution(x).
22    pub width: Option<f64>,
23    /// Vertical jitter amount in data units; `None` = 0.4 × resolution(y).
24    pub height: Option<f64>,
25    /// Seed of the deterministic noise stream.
26    pub seed: u64,
27}
28
29impl Default for PositionJitter {
30    fn default() -> Self {
31        PositionJitter {
32            width: None,
33            height: None,
34            seed: JITTER_SEED,
35        }
36    }
37}
38
39impl PositionJitter {
40    /// Explicit jitter amounts (data units), default seed.
41    pub fn new(width: f64, height: f64) -> Self {
42        PositionJitter {
43            width: Some(width),
44            height: Some(height),
45            seed: JITTER_SEED,
46        }
47    }
48
49    /// Set the horizontal jitter amount (data units).
50    pub fn with_width(mut self, width: f64) -> Self {
51        self.width = Some(width);
52        self
53    }
54
55    /// Set the vertical jitter amount (data units).
56    pub fn with_height(mut self, height: f64) -> Self {
57        self.height = Some(height);
58        self
59    }
60
61    /// Use a different seed (ggplot2's `position_jitter(seed = …)`).
62    pub fn with_seed(mut self, seed: u64) -> Self {
63        self.seed = seed;
64        self
65    }
66}
67
68/// ggplot2's `resolution(x, zero = FALSE)`: the smallest positive gap between
69/// distinct finite values; 1 for integer-typed data, a single distinct value, or
70/// no numeric values at all.
71pub fn resolution(values: &[Value]) -> f64 {
72    let mut all_int = true;
73    let mut xs: Vec<f64> = Vec::with_capacity(values.len());
74    for v in values {
75        match v {
76            Value::Integer(i) => xs.push(*i as f64),
77            Value::Float(f) if f.is_finite() => {
78                all_int = false;
79                xs.push(*f);
80            }
81            Value::DateTime(s) => {
82                all_int = false;
83                xs.push(*s as f64);
84            }
85            _ => {}
86        }
87    }
88    if all_int || xs.len() < 2 {
89        return 1.0;
90    }
91    xs.sort_by(|a, b| a.total_cmp(b));
92    let span = xs[xs.len() - 1] - xs[0];
93    // Ignore floating-point dust between "equal" values (ggplot2 uses a
94    // tolerance of sqrt(.Machine$double.eps) relative to the range).
95    let tol = span.abs() * 1e-8;
96    let min_gap = xs
97        .windows(2)
98        .map(|w| w[1] - w[0])
99        .filter(|d| *d > tol)
100        .fold(f64::INFINITY, f64::min);
101    if min_gap.is_finite() && min_gap > 0.0 {
102        min_gap
103    } else {
104        1.0
105    }
106}
107
108fn jitter_column(col: &mut [Value], amount: f64, rng: &mut SplitMix64) {
109    for v in col.iter_mut() {
110        if let Some(x) = v.as_f64() {
111            *v = Value::Float(x + rng.range_f64(-amount, amount));
112        }
113    }
114}
115
116impl Position for PositionJitter {
117    fn compute(&self, data: &mut DataFrame, _params: &PositionParams) {
118        let mut rng = SplitMix64::new(self.seed);
119
120        if let Some(x_col) = data.column_mut("x") {
121            let w = self.width.unwrap_or_else(|| 0.4 * resolution(x_col));
122            if w > 0.0 && w.is_finite() {
123                jitter_column(x_col, w, &mut rng);
124            }
125        }
126
127        if let Some(y_col) = data.column_mut("y") {
128            let h = self.height.unwrap_or_else(|| 0.4 * resolution(y_col));
129            if h > 0.0 && h.is_finite() {
130                jitter_column(y_col, h, &mut rng);
131            }
132        }
133    }
134
135    fn name(&self) -> &str {
136        "jitter"
137    }
138
139    /// ggplot2 4.0.3 measures `position_jitter`'s default width/height
140    /// (`resolution(x) * 0.4`) from each facet panel's own x/y, not the
141    /// rows pooled across panels (#153) — verified with `layer_data()`:
142    /// two panels with very different x spacing (e.g. integers vs.
143    /// hundredths) get differently-scaled jitter even under fixed facet
144    /// scales. The RNG draw is also per panel (it resets from `seed` at
145    /// the top of `compute`, as it already did), matching ggplot2's own
146    /// per-panel restart — verified by the identical normalized jitter
147    /// fractions ggplot2 produces across panels for the same seed.
148    fn per_panel(&self) -> bool {
149        true
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    fn frame(x: Vec<Value>, y: Vec<Value>) -> DataFrame {
158        let mut df = DataFrame::new();
159        df.add_column("x".into(), x);
160        df.add_column("y".into(), y);
161        df
162    }
163
164    fn floats(v: &[f64]) -> Vec<Value> {
165        v.iter().map(|f| Value::Float(*f)).collect()
166    }
167
168    #[test]
169    fn resolution_matches_ggplot2() {
170        assert_eq!(resolution(&floats(&[1.0, 2.0, 3.0])), 1.0);
171        assert_eq!(resolution(&floats(&[0.1, 0.3, 0.2])), 0.09999999999999998);
172        assert_eq!(resolution(&floats(&[5.0])), 1.0);
173        assert_eq!(resolution(&floats(&[2.0, 2.0])), 1.0);
174        assert_eq!(
175            resolution(&[Value::Integer(10), Value::Integer(20)]),
176            1.0,
177            "integer data has resolution 1"
178        );
179        assert_eq!(resolution(&[Value::Str("a".into())]), 1.0);
180    }
181
182    #[test]
183    fn default_width_scales_with_resolution() {
184        // Values spaced 0.01 apart: jitter must stay within ±0.004.
185        let xs: Vec<f64> = (0..50).map(|i| i as f64 * 0.01).collect();
186        let mut df = frame(floats(&xs), floats(&xs));
187        PositionJitter::default().compute(&mut df, &PositionParams::default());
188        for (orig, v) in xs.iter().zip(df.column("x").unwrap()) {
189            let d = (v.as_f64().unwrap() - orig).abs();
190            assert!(d <= 0.004 + 1e-12, "moved {d}");
191        }
192        // Integer-coded positions keep the classic ±0.4.
193        let mut df = frame(floats(&[1.0, 2.0, 3.0]), floats(&[1.0, 2.0, 3.0]));
194        PositionJitter::default().compute(&mut df, &PositionParams::default());
195        let moved: Vec<f64> = df
196            .column("x")
197            .unwrap()
198            .iter()
199            .zip([1.0, 2.0, 3.0])
200            .map(|(v, o)| (v.as_f64().unwrap() - o).abs())
201            .collect();
202        assert!(moved.iter().all(|d| *d <= 0.4));
203        assert!(moved.iter().any(|d| *d > 0.01));
204    }
205
206    #[test]
207    fn seed_controls_output() {
208        let run = |p: PositionJitter| {
209            let mut df = frame(floats(&[1.0, 2.0, 3.0]), floats(&[1.0, 2.0, 3.0]));
210            p.compute(&mut df, &PositionParams::default());
211            df.column("x").unwrap().to_vec()
212        };
213        assert_eq!(
214            run(PositionJitter::default()),
215            run(PositionJitter::default())
216        );
217        assert_ne!(
218            run(PositionJitter::default()),
219            run(PositionJitter::default().with_seed(1))
220        );
221        assert_eq!(
222            run(PositionJitter::default().with_seed(1)),
223            run(PositionJitter::default().with_seed(1))
224        );
225    }
226
227    #[test]
228    fn zero_amount_disables_axis() {
229        let mut df = frame(floats(&[1.0, 2.0]), floats(&[5.0, 6.0]));
230        PositionJitter::new(0.3, 0.0).compute(&mut df, &PositionParams::default());
231        assert_eq!(df.column("y").unwrap(), &floats(&[5.0, 6.0])[..]);
232        assert_ne!(df.column("x").unwrap(), &floats(&[1.0, 2.0])[..]);
233    }
234}