Skip to main content

ggplot_rs/
summary.rs

1//! What a built plot draws, as numbers: per layer (and facet panel) and per
2//! series, how many marks, the x range, the y minimum / maximum and where,
3//! the first and last y, and a band's extent. A caller that writes about a
4//! chart (a title, an answer) can quote these instead of guessing them.
5//!
6//! ```
7//! use ggplot_rs::prelude::*;
8//! let df = vec![
9//!     ("x".to_string(), vec![Value::Str("a".into()), Value::Str("b".into())]),
10//!     ("y".to_string(), vec![Value::Float(3.0), Value::Float(5.0)]),
11//! ];
12//! let built = GGPlot::new(df).aes(Aes::new().x("x").y("y")).geom_col().build();
13//! assert_eq!(built.summary_text(), "col: 2 marks, x a … b; y first 3, last 5, min 3 at a, max 5 at b");
14//! ```
15
16use crate::build::BuiltPlot;
17use crate::data::{format_epoch_secs, DataFrame, Value};
18
19/// Columns that name a layer's series, in order of preference.
20const SERIES_COLS: &[&str] = &["colour", "color", "fill", "group"];
21/// At most this many series per layer are listed; the rest are counted.
22pub const MAX_SERIES: usize = 12;
23
24/// One layer of one panel.
25#[derive(Debug, Clone, PartialEq)]
26pub struct LayerSummary {
27    /// The geom's name (`line`, `col`, `smooth`, …).
28    pub geom: String,
29    /// The facet panel's label, when the plot is faceted.
30    pub panel: Option<String>,
31    pub series: Vec<SeriesSummary>,
32}
33
34/// One series of a layer (all its rows when the layer has no series column).
35#[derive(Debug, Clone, PartialEq)]
36pub struct SeriesSummary {
37    /// The series' value (its colour / fill / group), `None` for a single one.
38    pub key: Option<String>,
39    /// Rows with a finite y.
40    pub n: usize,
41    /// The x extent: the smallest and largest of a numeric or date x, the
42    /// first and last (in the order drawn) of a discrete one.
43    pub x_from: String,
44    pub x_to: String,
45    pub y_first: f64,
46    pub y_last: f64,
47    /// `(y, x)` of the smallest and largest y (the first, on a tie).
48    pub y_min: (f64, String),
49    pub y_max: (f64, String),
50    /// `(lowest ymin, highest ymax)` of a band (ribbon, smooth, interval).
51    pub band: Option<(f64, f64)>,
52    /// The band's width (ymax − ymin) at `x_from` and at `x_to`: whether
53    /// the uncertainty widens or narrows along x.
54    pub band_width: Option<(f64, f64)>,
55    /// Every mark's `(x label, y)`, in the order drawn.
56    pub points: Vec<(String, f64)>,
57    /// How y goes with a numeric x on a point layer (a scatter, a bubble
58    /// chart) of at least [`MIN_COR_POINTS`] marks.
59    pub cor: Option<Correlation>,
60}
61
62/// A point layer needs this many marks for a correlation.
63pub const MIN_COR_POINTS: usize = 5;
64
65/// How two things go together in a scatter: y with x, and a bubble's size
66/// with x and with y.
67#[derive(Debug, Clone, PartialEq)]
68pub struct Correlation {
69    /// Pearson's r of x and y.
70    pub r: f64,
71    /// Spearman's ρ of x and y (ranks: any monotone trend).
72    pub rho: f64,
73    /// Spearman's ρ of the size with x and with y, for a bubble chart.
74    pub size_rho: Option<(f64, f64)>,
75}
76
77/// The summaries of every layer, panel by panel.
78#[derive(Debug, Clone, PartialEq, Default)]
79pub struct PlotSummary {
80    pub layers: Vec<LayerSummary>,
81    /// Two series over the same x values: their difference per x.
82    pub compare: Option<Comparison>,
83}
84
85/// `b − a` per shared x, for a plot of exactly two series (2025 against
86/// 2024, actual against plan): where the gap is largest and smallest.
87#[derive(Debug, Clone, PartialEq)]
88pub struct Comparison {
89    pub a: String,
90    pub b: String,
91    /// `(b − a, (b − a) / |a| in %, x)` of the largest and smallest difference.
92    pub largest: (f64, Option<f64>, String),
93    pub smallest: (f64, Option<f64>, String),
94    /// The same by the % change, when that ranks the x values differently.
95    pub largest_pct: Option<(f64, Option<f64>, String)>,
96    pub smallest_pct: Option<(f64, Option<f64>, String)>,
97}
98
99impl BuiltPlot {
100    /// What the plot draws, as numbers (see the [module docs](crate::summary)).
101    pub fn summary(&self) -> PlotSummary {
102        // a date x stays a date in the stat output too (a smooth's grid is
103        // plain numbers): format those as dates as well
104        let date_x = self.layers.iter().any(|l| {
105            l.data
106                .column("x")
107                .is_some_and(|c| c.iter().any(|v| v.is_datetime()))
108        });
109        let mut layers = Vec::new();
110        let faceted = self.panels.len() > 1 && !self.panels_data.is_empty();
111        if faceted {
112            for (p, data) in self.panels.iter().zip(&self.panels_data) {
113                for (l, d) in self.layers.iter().zip(data) {
114                    if let Some(s) = layer_summary(l.geom.name(), d, date_x) {
115                        layers.push(LayerSummary {
116                            panel: Some(p.label.clone()),
117                            ..s
118                        });
119                    }
120                }
121            }
122        } else {
123            for l in &self.layers {
124                layers.extend(layer_summary(l.geom.name(), &l.data, date_x));
125            }
126        }
127        // a layer repeating the one before it (a line's point markers) is
128        // one entry: `line+point`
129        let mut merged: Vec<LayerSummary> = Vec::new();
130        for l in layers {
131            match merged.last_mut() {
132                Some(m) if m.panel == l.panel && m.series == l.series => {
133                    m.geom = format!("{}+{}", m.geom, l.geom);
134                }
135                _ => merged.push(l),
136            }
137        }
138        let compare = compare(&merged);
139        PlotSummary {
140            layers: merged,
141            compare,
142        }
143    }
144
145    /// [`summary`](Self::summary) as text, one line per layer and panel.
146    pub fn summary_text(&self) -> String {
147        self.summary().to_string()
148    }
149}
150
151impl std::fmt::Display for PlotSummary {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        for (i, l) in self.layers.iter().enumerate() {
154            if i > 0 {
155                writeln!(f)?;
156            }
157            match &l.panel {
158                Some(p) => write!(f, "{} [{p}]:", l.geom)?,
159                None => write!(f, "{}:", l.geom)?,
160            }
161            let shown = l.series.len().min(MAX_SERIES);
162            for (j, s) in l.series[..shown].iter().enumerate() {
163                if j > 0 {
164                    write!(f, ";")?;
165                }
166                if let Some(k) = &s.key {
167                    write!(f, " {k} —")?;
168                }
169                // a ribbon is its band: its y is only the lower edge
170                if let (true, Some((lo, hi))) = (l.geom == "ribbon", s.band) {
171                    write!(
172                        f,
173                        " {} mark{}, x {} … {}, band {} … {}",
174                        s.n,
175                        if s.n == 1 { "" } else { "s" },
176                        s.x_from,
177                        s.x_to,
178                        num(lo),
179                        num(hi)
180                    )?;
181                    write_width(f, s)?;
182                    continue;
183                }
184                write!(
185                    f,
186                    " {} mark{}, x {} … {}; y first {}, last {}, min {} at {}, max {} at {}",
187                    s.n,
188                    if s.n == 1 { "" } else { "s" },
189                    s.x_from,
190                    s.x_to,
191                    num(s.y_first),
192                    num(s.y_last),
193                    num(s.y_min.0),
194                    s.y_min.1,
195                    num(s.y_max.0),
196                    s.y_max.1
197                )?;
198                if let Some((lo, hi)) = s.band {
199                    write!(f, ", band {} … {}", num(lo), num(hi))?;
200                    write_width(f, s)?;
201                }
202                if let Some(c) = &s.cor {
203                    write!(
204                        f,
205                        "; y {} with x (r {}, ρ {})",
206                        trend(c.rho),
207                        num(round2(c.r)),
208                        num(round2(c.rho))
209                    )?;
210                    if let Some((sx, sy)) = c.size_rho {
211                        write!(
212                            f,
213                            "; size {} with x (ρ {}), {} with y (ρ {})",
214                            trend(sx),
215                            num(round2(sx)),
216                            trend(sy),
217                            num(round2(sy))
218                        )?;
219                    }
220                }
221            }
222            if l.series.len() > shown {
223                write!(f, "; +{} more series", l.series.len() - shown)?;
224            }
225        }
226        if let Some(c) = &self.compare {
227            let one = |(d, p, x): &(f64, Option<f64>, String)| {
228                let sign = if *d >= 0.0 { "+" } else { "" };
229                match p {
230                    Some(p) => format!("{sign}{} ({sign}{} %) at {x}", num(*d), num(*p)),
231                    None => format!("{sign}{} at {x}", num(*d)),
232                }
233            };
234            write!(
235                f,
236                "\n{} − {}: largest {}, smallest {}",
237                c.b,
238                c.a,
239                one(&c.largest),
240                one(&c.smallest)
241            )?;
242            if let (Some(l), Some(s)) = (&c.largest_pct, &c.smallest_pct) {
243                write!(f, "; by %: largest {}, smallest {}", one(l), one(s))?;
244            }
245        }
246        Ok(())
247    }
248}
249
250/// The plot's series outside bands and ribbons; exactly two named ones over
251/// the same (at least two) x values are compared.
252fn compare(layers: &[LayerSummary]) -> Option<Comparison> {
253    let series: Vec<&SeriesSummary> = layers
254        .iter()
255        .filter(|l| l.panel.is_none() && l.geom != "ribbon" && l.geom != "smooth")
256        .flat_map(|l| &l.series)
257        .collect();
258    let [a, b] = series.as_slice() else {
259        return None;
260    };
261    let (ka, kb) = (a.key.clone()?, b.key.clone()?);
262    if ka == kb || a.points.len() < 2 || a.points.len() != b.points.len() {
263        return None;
264    }
265    let diffs: Vec<(f64, Option<f64>, String)> = a
266        .points
267        .iter()
268        .map(|(x, ya)| {
269            let yb = b.points.iter().find(|(xb, _)| xb == x)?.1;
270            let d = yb - ya;
271            Some((d, (*ya != 0.0).then(|| 100.0 * d / ya.abs()), x.clone()))
272        })
273        .collect::<Option<_>>()?;
274    let pick = |better: fn(f64, f64) -> bool| {
275        diffs
276            .iter()
277            .fold(None::<&(f64, Option<f64>, String)>, |m, d| match m {
278                Some(m) if !better(d.0, m.0) => Some(m),
279                _ => Some(d),
280            })
281            .cloned()
282    };
283    let largest = pick(|x, y| x > y)?;
284    let smallest = pick(|x, y| x < y)?;
285    let by_pct = |better: fn(f64, f64) -> bool| {
286        diffs
287            .iter()
288            .filter_map(|d| d.1.map(|p| (p, d)))
289            .fold(
290                None::<(f64, &(f64, Option<f64>, String))>,
291                |m, (p, d)| match m {
292                    Some(m) if !better(p, m.0) => Some(m),
293                    _ => Some((p, d)),
294                },
295            )
296            .map(|(_, d)| d.clone())
297    };
298    let (lp, sp) = (by_pct(|x, y| x > y), by_pct(|x, y| x < y));
299    // only when % ranks them differently (else it repeats the line above)
300    let differs = lp.as_ref().map(|l| &l.2) != Some(&largest.2)
301        || sp.as_ref().map(|s| &s.2) != Some(&smallest.2);
302    Some(Comparison {
303        a: ka,
304        b: kb,
305        largest,
306        smallest,
307        largest_pct: lp.filter(|_| differs),
308        smallest_pct: sp.filter(|_| differs),
309    })
310}
311
312/// A correlation in words: how strongly, and which way.
313fn trend(rho: f64) -> &'static str {
314    match (rho.abs(), rho > 0.0) {
315        (a, _) if a < 0.2 => "shows no clear trend",
316        (a, true) if a < 0.4 => "rises weakly",
317        (a, false) if a < 0.4 => "falls weakly",
318        (a, true) if a < 0.7 => "rises moderately",
319        (a, false) if a < 0.7 => "falls moderately",
320        (_, true) => "rises strongly",
321        (_, false) => "falls strongly",
322    }
323}
324
325fn round2(v: f64) -> f64 {
326    (v * 100.0).round() / 100.0
327}
328
329/// Pearson's r, `None` when either side doesn't vary.
330fn pearson(a: &[f64], b: &[f64]) -> Option<f64> {
331    let n = a.len() as f64;
332    let (ma, mb) = (a.iter().sum::<f64>() / n, b.iter().sum::<f64>() / n);
333    let (mut sab, mut saa, mut sbb) = (0.0, 0.0, 0.0);
334    for (x, y) in a.iter().zip(b) {
335        sab += (x - ma) * (y - mb);
336        saa += (x - ma) * (x - ma);
337        sbb += (y - mb) * (y - mb);
338    }
339    (saa > 0.0 && sbb > 0.0).then(|| (sab / (saa * sbb).sqrt()).clamp(-1.0, 1.0))
340}
341
342/// Average ranks (ties share their mean rank).
343fn ranks(v: &[f64]) -> Vec<f64> {
344    let mut ix: Vec<usize> = (0..v.len()).collect();
345    ix.sort_by(|&i, &j| v[i].total_cmp(&v[j]));
346    let mut r = vec![0.0; v.len()];
347    let mut k = 0;
348    while k < ix.len() {
349        let mut e = k;
350        while e + 1 < ix.len() && v[ix[e + 1]] == v[ix[k]] {
351            e += 1;
352        }
353        let avg = (k + e) as f64 / 2.0 + 1.0;
354        for &i in &ix[k..=e] {
355            r[i] = avg;
356        }
357        k = e + 1;
358    }
359    r
360}
361
362fn spearman(a: &[f64], b: &[f64]) -> Option<f64> {
363    pearson(&ranks(a), &ranks(b))
364}
365
366/// `, width 16 at a → 25.3 at b (widens)` for a band.
367fn write_width(f: &mut std::fmt::Formatter<'_>, s: &SeriesSummary) -> std::fmt::Result {
368    let Some((a, b)) = s.band_width else {
369        return Ok(());
370    };
371    let trend = if (b - a).abs() <= 0.02 * a.abs().max(b.abs()) {
372        "about even"
373    } else if b > a {
374        "widens"
375    } else {
376        "narrows"
377    };
378    write!(
379        f,
380        ", width {} at {} → {} at {} ({trend})",
381        num(a),
382        s.x_from,
383        num(b),
384        s.x_to
385    )
386}
387
388fn layer_summary(geom: &str, d: &DataFrame, date_x: bool) -> Option<LayerSummary> {
389    let x = d.column("x")?;
390    // a stacked layer keeps each mark's own value in `.y_raw`
391    let y = d.column(".y_raw").or_else(|| d.column("y"))?;
392    let key = SERIES_COLS.iter().find_map(|c| d.column(c));
393    let (ymin, ymax) = (d.column("ymin"), d.column("ymax"));
394    // a band is drawn only by a layer whose ymin/ymax differ from its y
395    // (a bar's ymin = 0 is its base, not a band)
396    let banded = matches!(
397        geom,
398        "ribbon" | "smooth" | "errorbar" | "linerange" | "pointrange" | "crossbar"
399    );
400    let mut order: Vec<String> = Vec::new();
401    let mut rows: Vec<Vec<usize>> = Vec::new();
402    for i in 0..d.nrows() {
403        let k = key.map(|k| label(&k[i], false)).unwrap_or_default();
404        let at = match order.iter().position(|o| *o == k) {
405            Some(at) => at,
406            None => {
407                order.push(k);
408                rows.push(Vec::new());
409                order.len() - 1
410            }
411        };
412        rows[at].push(i);
413    }
414    let series: Vec<SeriesSummary> = order
415        .into_iter()
416        .zip(rows)
417        .filter_map(|(k, ix)| {
418            let pts: Vec<(usize, f64)> = ix
419                .into_iter()
420                .filter_map(|i| y[i].as_f64().filter(|v| v.is_finite()).map(|v| (i, v)))
421                .collect();
422            let (&(i0, y0), &(i1, y1)) = (pts.first()?, pts.last()?);
423            let lo = pts
424                .iter()
425                .fold(pts[0], |a, b| if b.1 < a.1 { *b } else { a });
426            let hi = pts
427                .iter()
428                .fold(pts[0], |a, b| if b.1 > a.1 { *b } else { a });
429            let xl = |i: usize| label(&x[i], date_x);
430            let band = banded.then(|| {
431                let f = |c: Option<&[Value]>, pick: fn(f64, f64) -> f64| {
432                    c.and_then(|c| {
433                        pts.iter()
434                            .filter_map(|(i, _)| c[*i].as_f64().filter(|v| v.is_finite()))
435                            .reduce(pick)
436                    })
437                };
438                f(ymin, f64::min).zip(f(ymax, f64::max))
439            });
440            // a numeric / date x: its extent, not the row order (a scatter's
441            // rows are in no x order)
442            let xs: Vec<(usize, f64)> = pts
443                .iter()
444                .filter(|(i, _)| !matches!(x[*i], Value::Str(_)))
445                .filter_map(|(i, _)| x[*i].as_f64().map(|v| (*i, v)))
446                .collect();
447            let (ia, ib) = if xs.len() == pts.len() {
448                let a = xs.iter().fold(xs[0], |a, b| if b.1 < a.1 { *b } else { a });
449                let b = xs.iter().fold(xs[0], |a, b| if b.1 > a.1 { *b } else { a });
450                (a.0, b.0)
451            } else {
452                (i0, i1)
453            };
454            let (x_from, x_to) = (xl(ia), xl(ib));
455            let width = |i: usize| {
456                let lo = ymin?.get(i)?.as_f64()?;
457                let hi = ymax?.get(i)?.as_f64()?;
458                (lo.is_finite() && hi.is_finite()).then_some(hi - lo)
459            };
460            let band_width = band
461                .as_ref()
462                .and_then(|b| b.as_ref())
463                .and_then(|_| width(ia).zip(width(ib)))
464                .filter(|_| ia != ib);
465            // a scatter or bubble chart: how y (and the size) go with x
466            let cor =
467                (geom.starts_with("point") && xs.len() == pts.len() && pts.len() >= MIN_COR_POINTS)
468                    .then(|| {
469                        let xv: Vec<f64> = xs.iter().map(|p| p.1).collect();
470                        let yv: Vec<f64> = pts.iter().map(|p| p.1).collect();
471                        let size_rho = d.column("size").and_then(|sc| {
472                            let sv: Vec<f64> = pts
473                                .iter()
474                                .map(|(i, _)| sc[*i].as_f64().filter(|v| v.is_finite()))
475                                .collect::<Option<_>>()?;
476                            Some((spearman(&sv, &xv)?, spearman(&sv, &yv)?))
477                        });
478                        Some(Correlation {
479                            r: pearson(&xv, &yv)?,
480                            rho: spearman(&xv, &yv)?,
481                            size_rho,
482                        })
483                    })
484                    .flatten();
485            Some(SeriesSummary {
486                key: key.map(|_| k),
487                n: pts.len(),
488                x_from,
489                x_to,
490                y_first: y0,
491                y_last: y1,
492                y_min: (lo.1, xl(lo.0)),
493                y_max: (hi.1, xl(hi.0)),
494                band: band.flatten(),
495                band_width,
496                points: pts.iter().map(|(i, v)| (xl(*i), *v)).collect(),
497                cor,
498            })
499        })
500        .collect();
501    (!series.is_empty()).then(|| LayerSummary {
502        geom: geom.to_string(),
503        panel: None,
504        series,
505    })
506}
507
508/// A value as the summary shows it: a date as `YYYY-MM-DD` (with the time
509/// when it has one), a number trimmed, text as is.
510fn label(v: &Value, date_x: bool) -> String {
511    let date = |secs: f64| {
512        let s = format_epoch_secs(secs.round() as i64);
513        s.strip_suffix(" 00:00:00").map(str::to_string).unwrap_or(s)
514    };
515    match v {
516        Value::DateTime(_) => date(v.as_f64().unwrap_or(0.0)),
517        Value::Str(s) => s.clone(),
518        Value::Na => "NA".into(),
519        _ => match v.as_f64() {
520            Some(n) if date_x => date(n),
521            Some(n) => num(n),
522            None => v.key_str().into_owned(),
523        },
524    }
525}
526
527/// A number with at most 4 significant decimals, no trailing zeros.
528fn num(n: f64) -> String {
529    if n == n.trunc() && n.abs() < 1e15 {
530        return format!("{}", n as i64);
531    }
532    let digits = (4 - n.abs().log10().floor() as i32).clamp(0, 6) as usize;
533    let s = format!("{n:.digits$}");
534    let s = s.trim_end_matches('0').trim_end_matches('.');
535    s.to_string()
536}
537
538#[cfg(test)]
539mod tests {
540    use crate::prelude::*;
541
542    fn strs(v: &[&str]) -> Vec<Value> {
543        v.iter().map(|s| Value::Str(s.to_string())).collect()
544    }
545
546    #[test]
547    fn a_scatter_says_how_y_and_the_size_go_with_x() {
548        let f = |v: &[f64]| v.iter().map(|x| Value::Float(*x)).collect::<Vec<_>>();
549        let x = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
550        let y = [2.0, 3.0, 5.0, 4.0, 7.0, 8.0];
551        // the size falls as y rises (big districts sit low)
552        let size = [90.0, 80.0, 50.0, 60.0, 20.0, 10.0];
553        let df = vec![
554            ("x".to_string(), f(&x)),
555            ("y".to_string(), f(&y)),
556            ("s".to_string(), f(&size)),
557        ];
558        let built = GGPlot::new(df)
559            .aes(Aes::new().x("x").y("y").size("s"))
560            .geom_point()
561            .build();
562        let c = built.summary().layers[0].series[0].cor.clone().unwrap();
563        assert!(c.r > 0.9 && c.rho > 0.9, "{c:?}");
564        let (sx, sy) = c.size_rho.unwrap();
565        assert!(sx < -0.9 && sy < -0.9, "{c:?}");
566        let text = built.summary_text();
567        assert!(
568            text.contains("; y rises strongly with x (r 0.95, ρ 0.94)"),
569            "{text}"
570        );
571        assert!(
572            text.contains("size falls strongly with x (ρ -0.94), falls strongly with y (ρ -1)"),
573            "{text}"
574        );
575
576        // too few marks, or a line: no correlation
577        let df = vec![("x".to_string(), f(&x[..4])), ("y".to_string(), f(&y[..4]))];
578        let few = GGPlot::new(df)
579            .aes(Aes::new().x("x").y("y"))
580            .geom_point()
581            .build();
582        assert!(few.summary().layers[0].series[0].cor.is_none());
583        let df = vec![("x".to_string(), f(&x)), ("y".to_string(), f(&y))];
584        let line = GGPlot::new(df)
585            .aes(Aes::new().x("x").y("y"))
586            .geom_line()
587            .build();
588        assert!(line.summary().layers[0].series[0].cor.is_none());
589        assert!(!line.summary_text().contains(" with x"));
590    }
591
592    #[test]
593    fn series_dates_and_a_smooth_band() {
594        let day = |d: i64| Value::from_timestamp(1_700_006_400 + d * 86_400);
595        let df = vec![
596            (
597                "x".to_string(),
598                vec![day(0), day(1), day(2), day(0), day(1), day(2)],
599            ),
600            (
601                "y".to_string(),
602                [3.0, 5.0, 1.0, 2.0, 2.5, 4.0].map(Value::Float).to_vec(),
603            ),
604            ("g".to_string(), strs(&["A", "A", "A", "B", "B", "B"])),
605        ];
606        let s = GGPlot::new(df)
607            .aes(Aes::new().x("x").y("y").color("g"))
608            .geom_line()
609            .geom_smooth()
610            .build()
611            .summary();
612        let line = &s.layers[0];
613        assert_eq!(line.geom, "line");
614        assert_eq!(line.series.len(), 2);
615        let a = &line.series[0];
616        assert_eq!(a.key.as_deref(), Some("A"));
617        assert_eq!(
618            (a.n, a.x_from.as_str(), a.x_to.as_str()),
619            (3, "2023-11-15", "2023-11-17")
620        );
621        assert_eq!(a.y_max, (5.0, "2023-11-16".to_string()));
622        assert_eq!(a.y_min, (1.0, "2023-11-17".to_string()));
623        let smooth = &s.layers[1];
624        assert_eq!(smooth.geom, "smooth");
625        // the fitted grid's x is a date too, and its band is reported
626        assert!(
627            smooth.series[0].x_from.starts_with("2023-11-15"),
628            "{smooth:?}"
629        );
630        assert!(smooth.series[0].band.is_some());
631    }
632
633    #[test]
634    fn stacked_bars_report_their_own_values_and_facets_their_panel() {
635        let df = vec![
636            ("x".to_string(), strs(&["W1", "W1", "W2", "W2"])),
637            (
638                "y".to_string(),
639                [3.0, 5.0, 7.0, 2.0].map(Value::Float).to_vec(),
640            ),
641            ("c".to_string(), strs(&["a", "b", "a", "b"])),
642        ];
643        let s = GGPlot::new(df.clone())
644            .aes(Aes::new().x("x").y("y").fill("c"))
645            .geom_col()
646            .position(PositionStack)
647            .build()
648            .summary();
649        let b = &s.layers[0].series[1];
650        assert_eq!(b.key.as_deref(), Some("b"));
651        assert_eq!(
652            (b.y_first, b.y_last),
653            (5.0, 2.0),
654            "own values, not the stack tops"
655        );
656        assert_eq!(b.band, None, "a bar's base is not a band");
657
658        let s = GGPlot::new(df)
659            .aes(Aes::new().x("x").y("y"))
660            .geom_col()
661            .facet_wrap("c", None)
662            .build()
663            .summary();
664        let panels: Vec<_> = s.layers.iter().map(|l| l.panel.clone().unwrap()).collect();
665        assert_eq!(panels, ["a", "b"]);
666        assert_eq!(s.layers[1].series[0].y_max, (5.0, "W1".to_string()));
667    }
668
669    #[test]
670    fn scatter_x_extent_ribbon_band_and_markers_merged() {
671        let df = vec![
672            ("x".to_string(), [5.0, 1.0, 9.0].map(Value::Float).to_vec()),
673            ("y".to_string(), [2.0, 4.0, 3.0].map(Value::Float).to_vec()),
674            ("lo".to_string(), [1.0, 3.0, 2.0].map(Value::Float).to_vec()),
675            ("hi".to_string(), [3.0, 6.0, 4.0].map(Value::Float).to_vec()),
676        ];
677        let t = GGPlot::new(df)
678            .aes(Aes::new().x("x").y("y").ymin("lo").ymax("hi"))
679            .geom_ribbon()
680            .geom_line()
681            .geom_point()
682            .build()
683            .summary_text();
684        let lines: Vec<&str> = t.lines().collect();
685        // widths: x=1 → 6−3 = 3, x=9 → 4−2 = 2
686        assert_eq!(
687            lines[0], "ribbon: 3 marks, x 1 … 9, band 1 … 6, width 3 at 1 → 2 at 9 (narrows)",
688            "{t}"
689        );
690        assert!(
691            lines[1].starts_with("line+point: 3 marks, x 1 … 9; y first"),
692            "{t}"
693        );
694        assert_eq!(lines.len(), 2, "{t}");
695    }
696
697    #[test]
698    fn two_series_over_the_same_x_are_compared() {
699        let m: Vec<Value> = (1..=3).map(|i| Value::Float(i as f64)).collect();
700        let df = vec![
701            ("x".to_string(), [m.clone(), m].concat()),
702            (
703                "y".to_string(),
704                [100.0, 200.0, 50.0, 130.0, 220.0, 51.0]
705                    .map(Value::Float)
706                    .to_vec(),
707            ),
708            (
709                "g".to_string(),
710                strs(&["2024", "2024", "2024", "2025", "2025", "2025"]),
711            ),
712        ];
713        let t = GGPlot::new(df)
714            .aes(Aes::new().x("x").y("y").color("g"))
715            .geom_line()
716            .build()
717            .summary_text();
718        assert!(
719            t.ends_with("2025 − 2024: largest +30 (+30 %) at 1, smallest +1 (+2 %) at 3"),
720            "{t}"
721        );
722    }
723
724    #[test]
725    fn a_comparison_by_percent_when_it_ranks_differently() {
726        let df = vec![
727            (
728                "x".to_string(),
729                [1.0, 2.0, 1.0, 2.0].map(Value::Float).to_vec(),
730            ),
731            (
732                "y".to_string(),
733                [10.0, 200.0, 15.0, 260.0].map(Value::Float).to_vec(),
734            ),
735            ("g".to_string(), strs(&["a", "a", "b", "b"])),
736        ];
737        let t = GGPlot::new(df)
738            .aes(Aes::new().x("x").y("y").color("g"))
739            .geom_line()
740            .build()
741            .summary_text();
742        assert!(
743            t.ends_with("by %: largest +5 (+50 %) at 1, smallest +60 (+30 %) at 2"),
744            "{t}"
745        );
746    }
747
748    #[test]
749    fn many_series_are_counted() {
750        let n = 15;
751        let df = vec![
752            (
753                "x".to_string(),
754                (0..n).map(|i| Value::Float(i as f64)).collect(),
755            ),
756            (
757                "y".to_string(),
758                (0..n).map(|i| Value::Float(i as f64 * 1.5)).collect(),
759            ),
760            (
761                "g".to_string(),
762                (0..n).map(|i| Value::Str(format!("s{i}"))).collect(),
763            ),
764        ];
765        let t = GGPlot::new(df)
766            .aes(Aes::new().x("x").y("y").color("g"))
767            .geom_point()
768            .build()
769            .summary_text();
770        assert!(t.ends_with("; +3 more series"), "{t}");
771        assert!(t.contains("s1 — 1 mark, x 1 … 1; y first 1.5"), "{t}");
772    }
773}