Skip to main content

ggplot_rs/stat/
mod.rs

1pub mod align;
2pub mod arcdiagram;
3pub mod bin;
4pub mod bin2d;
5pub mod bindot;
6pub mod binhex;
7pub mod boxplot;
8pub mod calendar;
9pub mod chord;
10#[cfg(feature = "ggpubr")]
11pub mod compare_means;
12pub mod connect;
13pub mod contour;
14pub mod contour_filled;
15#[cfg(feature = "ggpubr")]
16pub mod cor;
17pub mod count;
18pub mod density;
19pub mod density2d;
20pub mod dist;
21pub mod distribution;
22pub mod ecdf;
23pub mod ellipse;
24pub mod function;
25pub mod funnel;
26pub(crate) mod gam;
27pub mod hclust;
28pub mod heikin_ashi;
29pub mod identity;
30pub mod indicator;
31pub mod loess;
32pub mod manual;
33pub mod marching_squares;
34pub mod marimekko;
35pub mod network;
36pub mod pack;
37pub mod pareto;
38pub mod partition;
39pub mod qq;
40#[cfg(feature = "regression")]
41pub mod quantile;
42pub mod renko;
43pub mod sankey;
44#[cfg(feature = "sf")]
45pub mod sf_coordinates;
46pub mod smooth;
47pub mod sum;
48pub mod summary;
49pub mod summary2d;
50pub mod summary_bin;
51pub mod tree;
52pub mod treemap;
53pub mod unique;
54pub mod venn;
55pub mod waffle;
56pub mod waterfall;
57pub mod xdensity_ridges;
58pub mod ydensity;
59
60use crate::aes::{Aes, Aesthetic};
61use crate::data::DataFrame;
62use crate::scale::ScaleSet;
63
64/// Trait for statistical transformations.
65pub trait Stat: Send + Sync {
66    /// Transform data for a single group.
67    fn compute_group(&self, data: &DataFrame, scales: &ScaleSet) -> DataFrame;
68
69    /// Required aesthetics this stat needs.
70    fn required_aes(&self) -> Vec<Aesthetic>;
71
72    /// Default aesthetic mappings this stat produces.
73    fn default_aes(&self) -> Aes {
74        Aes::default()
75    }
76
77    /// If true, the stat receives every row of a panel at once (grouped only by
78    /// facet variables) instead of once per aesthetic group. Needed for
79    /// cross-group comparisons such as `stat_compare_means`, which must see all
80    /// groups together. Defaults to per-group behaviour.
81    fn panelwise(&self) -> bool {
82        false
83    }
84
85    /// True when the stat computes `y` itself in data units (a count, a
86    /// density, an ECDF) — ggplot2's `y = after_stat(count)` default. The
87    /// build then passes it through the y scale's transform (#490).
88    fn computed_y(&self) -> bool {
89        false
90    }
91
92    /// Name for debug/display.
93    fn name(&self) -> &str;
94
95    /// Validate the stat's own fixed configuration (not the data) and push
96    /// a human-readable warning for each problem found — e.g.
97    /// `StatBinHex::binwidth` being NaN, zero or negative. Called once per
98    /// layer, before [`compute_group`](Self::compute_group) runs (which has
99    /// no warnings channel of its own: the per-group call only sees
100    /// `&DataFrame` and `&ScaleSet`, not the plot's warnings sink). Default:
101    /// no-op.
102    fn validate(&self, _warnings: &mut Vec<String>) {}
103}
104
105/// R's `bw.nrd0`: Silverman's rule of thumb, `0.9 · min(sd, IQR/1.34) · n^-0.2`,
106/// with R's fallbacks when the spread is zero — `sd`, then `|x[0]|`, then `1` —
107/// so a constant sample still gets a positive bandwidth (never 0 → NaN).
108pub(crate) fn bw_nrd0(values: &[f64]) -> f64 {
109    let n = values.len();
110    if n < 2 {
111        return 1.0;
112    }
113    let nf = n as f64;
114    let mean = values.iter().sum::<f64>() / nf;
115    let sd = (values.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (nf - 1.0)).sqrt();
116    let mut sorted = values.to_vec();
117    sorted.sort_by(|a, b| a.total_cmp(b));
118    let q = |p: f64| {
119        let h = (n - 1) as f64 * p;
120        let lo = h.floor() as usize;
121        let hi = (lo + 1).min(n - 1);
122        sorted[lo] + (h - lo as f64) * (sorted[hi] - sorted[lo])
123    };
124    let iqr = q(0.75) - q(0.25);
125    let mut lo = sd.min(iqr / 1.34);
126    for fallback in [sd, values[0].abs(), 1.0] {
127        if lo > 0.0 && lo.is_finite() {
128            break;
129        }
130        lo = fallback;
131    }
132    0.9 * lo * nf.powf(-0.2)
133}