facett-plotters 0.1.6

facett — immediate-mode charts egui_plot lacks (box/violin/heatmap/candlestick/treemap), hand-painted on egui::Painter with themeable colour ramps
Documentation
//! **Box plot** — quartiles + whiskers + outliers, one box per named group.
//! The data→geometry math ([`Quartiles::from_sorted`] / [`Quartiles::compute`])
//! is a pure function with its own tests; [`BoxPlotView`] is the themeable
//! [`Facet`] that paints it and emits the underlying data as CSV/JSON.

use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, vec2};
use facett_core::{Facet, FacetCaps, Semantics, a11y_node, theme};

/// Five-number summary + the 1.5·IQR whisker fences and the points beyond them.
#[derive(Clone, Debug, PartialEq)]
pub struct Quartiles {
    pub min: f64,
    pub q1: f64,
    pub median: f64,
    pub q3: f64,
    pub max: f64,
    /// Lower whisker end: smallest datum ≥ `q1 - 1.5·IQR`.
    pub lower_fence: f64,
    /// Upper whisker end: largest datum ≤ `q3 + 1.5·IQR`.
    pub upper_fence: f64,
    /// Points outside the fences.
    pub outliers: Vec<f64>,
}

impl Quartiles {
    /// Compute from an arbitrary (unsorted) sample. Empty input → `None`.
    pub fn compute(values: &[f64]) -> Option<Self> {
        if values.is_empty() {
            return None;
        }
        let mut v: Vec<f64> = values.iter().copied().filter(|x| x.is_finite()).collect();
        if v.is_empty() {
            return None;
        }
        v.sort_by(|a, b| a.partial_cmp(b).unwrap());
        Some(Self::from_sorted(&v))
    }

    /// Compute from an already-sorted, finite, non-empty slice. Uses linear
    /// interpolation between order statistics (the "type-7"/`numpy` default), so
    /// it matches what analysts expect from Plotly/pandas.
    pub fn from_sorted(v: &[f64]) -> Self {
        debug_assert!(!v.is_empty());
        let pct = |p: f64| percentile_sorted(v, p);
        let q1 = pct(0.25);
        let median = pct(0.5);
        let q3 = pct(0.75);
        let iqr = q3 - q1;
        let lo = q1 - 1.5 * iqr;
        let hi = q3 + 1.5 * iqr;
        // Whisker ends snap to the most extreme data points still inside the fence.
        let lower_fence = *v.iter().find(|&&x| x >= lo).unwrap_or(&v[0]);
        let upper_fence = *v.iter().rev().find(|&&x| x <= hi).unwrap_or(v.last().unwrap());
        let outliers: Vec<f64> = v.iter().copied().filter(|&x| x < lo || x > hi).collect();
        Self {
            min: v[0],
            q1,
            median,
            q3,
            max: *v.last().unwrap(),
            lower_fence,
            upper_fence,
            outliers,
        }
    }
}

/// Linear-interpolated percentile of a sorted slice. `p ∈ 0..=1`.
pub fn percentile_sorted(sorted: &[f64], p: f64) -> f64 {
    let n = sorted.len();
    if n == 1 {
        return sorted[0];
    }
    let rank = p.clamp(0.0, 1.0) * (n as f64 - 1.0);
    let lo = rank.floor() as usize;
    let hi = rank.ceil() as usize;
    let frac = rank - lo as f64;
    sorted[lo] + (sorted[hi] - sorted[lo]) * frac
}

/// A box plot: named groups of raw samples.
pub struct BoxPlotView {
    pub title: String,
    /// `(group label, raw values)`.
    pub groups: Vec<(String, Vec<f64>)>,
}

impl BoxPlotView {
    pub fn new(title: impl Into<String>, groups: Vec<(String, Vec<f64>)>) -> Self {
        Self { title: title.into(), groups }
    }

    /// Per-group quartiles (skipping empty groups), paired with the label.
    pub fn summaries(&self) -> Vec<(String, Quartiles)> {
        self.groups
            .iter()
            .filter_map(|(name, vals)| Quartiles::compute(vals).map(|q| (name.clone(), q)))
            .collect()
    }

    /// Global value range across every group (for the shared y-axis).
    fn value_range(&self) -> Option<(f64, f64)> {
        let mut r: Option<(f64, f64)> = None;
        for (_, vals) in &self.groups {
            for &x in vals {
                if x.is_finite() {
                    r = Some(match r {
                        None => (x, x),
                        Some((lo, hi)) => (lo.min(x), hi.max(x)),
                    });
                }
            }
        }
        r
    }

    /// CSV of the five-number summary per group (the `copy()` payload).
    fn to_csv(&self) -> String {
        let mut s = String::from("group,min,q1,median,q3,max,outliers\n");
        for (name, q) in self.summaries() {
            s.push_str(&format!(
                "{},{},{},{},{},{},{}\n",
                name, q.min, q.q1, q.median, q.q3, q.max, q.outliers.len()
            ));
        }
        s
    }
}

impl Facet for BoxPlotView {
    fn title(&self) -> &str {
        &self.title
    }
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().copyable().resizable()
    }
    fn copy(&mut self) -> Option<String> {
        Some(self.to_csv())
    }
    fn ui(&mut self, ui: &mut Ui) {
        let th = theme(ui);
        let summaries = self.summaries();
        let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
        let painter = ui.painter_at(rect);
        painter.rect_filled(rect, egui::CornerRadius::ZERO, th.bg);
        let Some((vmin, vmax)) = self.value_range() else {
            painter.text(rect.center(), Align2::CENTER_CENTER, "no data", FontId::proportional(13.0), th.text_dim);
            return;
        };
        if summaries.is_empty() {
            painter.text(rect.center(), Align2::CENTER_CENTER, "no data", FontId::proportional(13.0), th.text_dim);
            return;
        }
        let plot = rect.shrink2(vec2(28.0, 24.0));
        let span = (vmax - vmin).max(1e-9);
        let y_of = |v: f64| plot.bottom() - ((v - vmin) / span) as f32 * plot.height();

        let n = summaries.len();
        let slot = plot.width() / n as f32;
        let box_w = (slot * 0.5).min(60.0);
        let hover = resp.hover_pos();
        let mut tip: Option<(Pos2, String)> = None;
        let base = ui.id().with("boxplot");

        for (i, (name, q)) in summaries.iter().enumerate() {
            let cx = plot.left() + slot * (i as f32 + 0.5);
            let color = facett_core::hash_color(name);
            let stroke = Stroke::new(1.5, th.accent);

            // Whiskers.
            painter.line_segment([Pos2::new(cx, y_of(q.lower_fence)), Pos2::new(cx, y_of(q.q1))], Stroke::new(1.0, th.text_dim));
            painter.line_segment([Pos2::new(cx, y_of(q.q3)), Pos2::new(cx, y_of(q.upper_fence))], Stroke::new(1.0, th.text_dim));
            // Whisker caps.
            let cap = box_w * 0.3;
            for &v in &[q.lower_fence, q.upper_fence] {
                painter.line_segment([Pos2::new(cx - cap, y_of(v)), Pos2::new(cx + cap, y_of(v))], Stroke::new(1.0, th.text_dim));
            }
            // The box (q1..q3).
            let box_rect = Rect::from_min_max(Pos2::new(cx - box_w * 0.5, y_of(q.q3)), Pos2::new(cx + box_w * 0.5, y_of(q.q1)));
            painter.rect_filled(box_rect, egui::CornerRadius::same(2), color.gamma_multiply(0.55));
            painter.rect_stroke(box_rect, egui::CornerRadius::same(2), stroke, egui::StrokeKind::Middle);
            // AccessKit node over the box body (FC-4): role=Image, label = the
            // group name, numeric_value = the median (the box's headline stat).
            // Keyed on the group name (stable across reorder, FC-5).
            a11y_node(
                ui,
                base,
                name,
                Sense::hover(),
                box_rect,
                Semantics::image(name.clone()).value(q.median),
            );
            // Median line.
            painter.line_segment(
                [Pos2::new(box_rect.left(), y_of(q.median)), Pos2::new(box_rect.right(), y_of(q.median))],
                Stroke::new(2.0, th.glow),
            );
            // Outliers.
            for &o in &q.outliers {
                painter.circle_stroke(Pos2::new(cx, y_of(o)), 2.5, Stroke::new(1.0, th.point));
            }
            // Group label.
            painter.text(Pos2::new(cx, plot.bottom() + 12.0), Align2::CENTER_CENTER, name, FontId::proportional(11.0), th.text);

            // Hover readout when the cursor is over this slot.
            if let Some(hp) = hover {
                if hp.x >= cx - slot * 0.5 && hp.x < cx + slot * 0.5 && plot.y_range().contains(hp.y) {
                    tip = Some((
                        hp,
                        format!(
                            "{name}\nmax {:.3}\nq3  {:.3}\nmed {:.3}\nq1  {:.3}\nmin {:.3}\noutliers {}",
                            q.max, q.q3, q.median, q.q1, q.min, q.outliers.len()
                        ),
                    ));
                }
            }
        }

        if let Some((at, text)) = tip {
            paint_tooltip(&painter, &th, at, &text);
        }
    }
    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "kind": "boxplot",
            "groups": self.summaries().iter().map(|(n, q)| serde_json::json!({
                "name": n, "min": q.min, "q1": q.q1, "median": q.median,
                "q3": q.q3, "max": q.max, "outliers": q.outliers.len(),
            })).collect::<Vec<_>>(),
        })
    }
}

/// Shared themed tooltip box used by the chart facets.
pub(crate) fn paint_tooltip(painter: &egui::Painter, th: &facett_core::Theme, at: Pos2, text: &str) {
    let font = FontId::proportional(11.0);
    let galley = painter.layout(text.to_string(), font, th.text, 240.0);
    let pad = vec2(6.0, 4.0);
    let pos = at + vec2(12.0, 12.0);
    let bg = Rect::from_min_size(pos, galley.size() + pad * 2.0);
    painter.rect_filled(bg, egui::CornerRadius::same(3), th.panel_bg);
    painter.rect_stroke(bg, egui::CornerRadius::same(3), Stroke::new(1.0, th.panel_stroke), egui::StrokeKind::Middle);
    painter.galley(pos + pad, galley, Color32::WHITE);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn percentile_matches_numpy_type7() {
        // numpy.percentile([1..=10], [25,50,75]) = 3.25, 5.5, 7.75
        let v: Vec<f64> = (1..=10).map(|x| x as f64).collect();
        assert!((percentile_sorted(&v, 0.25) - 3.25).abs() < 1e-9);
        assert!((percentile_sorted(&v, 0.50) - 5.5).abs() < 1e-9);
        assert!((percentile_sorted(&v, 0.75) - 7.75).abs() < 1e-9);
    }

    #[test]
    fn quartiles_basic_no_outliers() {
        let q = Quartiles::compute(&[1.0, 2.0, 3.0, 4.0, 5.0]).unwrap();
        assert_eq!(q.min, 1.0);
        assert_eq!(q.max, 5.0);
        assert_eq!(q.median, 3.0);
        assert_eq!(q.q1, 2.0);
        assert_eq!(q.q3, 4.0);
        assert!(q.outliers.is_empty());
        // fences cover the whole range when there are no outliers
        assert_eq!(q.lower_fence, 1.0);
        assert_eq!(q.upper_fence, 5.0);
    }

    #[test]
    fn quartiles_detects_high_outlier() {
        let mut data: Vec<f64> = (1..=10).map(|x| x as f64).collect();
        data.push(100.0); // far above q3 + 1.5 IQR
        let q = Quartiles::compute(&data).unwrap();
        assert!(q.outliers.contains(&100.0), "100 must be flagged as an outlier");
        assert!(q.upper_fence <= 10.0, "upper whisker snaps to in-fence data");
    }

    #[test]
    fn quartiles_empty_and_nonfinite() {
        assert!(Quartiles::compute(&[]).is_none());
        assert!(Quartiles::compute(&[f64::NAN, f64::INFINITY]).is_none());
    }

    #[test]
    fn single_value() {
        let q = Quartiles::compute(&[7.0]).unwrap();
        assert_eq!(q.median, 7.0);
        assert_eq!(q.q1, 7.0);
        assert_eq!(q.q3, 7.0);
        assert!(q.outliers.is_empty());
    }

    #[test]
    fn csv_has_header_and_row_per_group() {
        let v = BoxPlotView::new("t", vec![("a".into(), vec![1.0, 2.0, 3.0]), ("b".into(), vec![4.0, 5.0, 6.0])]);
        let csv = v.to_csv();
        assert!(csv.starts_with("group,min,q1,median,q3,max,outliers\n"));
        assert_eq!(csv.lines().count(), 3); // header + 2 groups
    }
}