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