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