Skip to main content

ggplot_rs/
build.rs

1use crate::aes::{mapping::apply_after_stat, mapping::resolve_mappings, Aes, Aesthetic};
2use crate::annotate::Annotation;
3use crate::coord::Coord;
4use crate::data::DataFrame;
5use crate::facet::{Facet, FacetScales, Panel};
6use crate::geom::Geom;
7use crate::plot::{GGError, GGPlot, Labels, Layer};
8use crate::position::PositionParams;
9use crate::scale::ScaleSet;
10use crate::theme::Theme;
11
12/// A built layer ready for rendering.
13pub struct BuiltLayer {
14    pub data: DataFrame,
15    pub geom: Box<dyn Geom>,
16    pub show_legend: Option<bool>,
17}
18
19/// A fully built plot ready for rendering.
20pub struct BuiltPlot {
21    pub layers: Vec<BuiltLayer>,
22    pub scales: ScaleSet,
23    pub coord: Box<dyn Coord>,
24    pub theme: Theme,
25    pub labels: Labels,
26    pub facet: Facet,
27    pub panels: Vec<Panel>,
28    /// Per-panel layer data. panels_data[panel_idx][layer_idx] = data for that panel+layer.
29    pub panels_data: Vec<Vec<DataFrame>>,
30    pub annotations: Vec<Annotation>,
31    pub guide_legend: crate::guide::config::GuideLegend,
32    /// Aesthetics suppressed from the legend (all layers with that aes set show_legend=false).
33    pub suppressed_aes: std::collections::HashSet<Aesthetic>,
34    /// Per-panel scale sets for free facets. Empty when FacetScales::Fixed.
35    pub panel_scales: Vec<ScaleSet>,
36    /// Non-fatal problems found while building (ggplot2's warnings), e.g.
37    /// "geom_point: removed 2 rows containing non-finite values". See
38    /// [`BuiltPlot::warnings`].
39    pub warnings: Vec<String>,
40    /// Every discrete legend's B3-2 layout plan (explicit `nrow`/`ncol`
41    /// grid, or auto-wrap), keyed by aesthetic, computed exactly once in
42    /// `layout_built` and reused as-is by `draw_legend_planned` — never
43    /// recomputed at draw time, so the warning (based on these same
44    /// plans) always matches what's drawn (review #158 finding 2:
45    /// computing it twice, once against the pre-reservation panel height
46    /// and once against the post-reservation one, could warn "+7 more"
47    /// while drawing "+15 more"). A guide missing from this map draws via
48    /// the 0.21 single-row/single-column path unchanged. Several
49    /// simultaneous discrete guides each get their own independent entry
50    /// (sipemu/ggplot-rs#155) — previously this only ever held at most
51    /// one plan, for a single discrete guide.
52    pub(crate) legend_plans: std::collections::HashMap<Aesthetic, crate::guide::legend::LegendPlan>,
53}
54
55impl BuiltPlot {
56    /// Non-fatal build warnings, in layer order: rows dropped for non-finite
57    /// positions, and layers skipped because their stat produced no data
58    /// (e.g. a density of a single value). Rendering still succeeds.
59    pub fn warnings(&self) -> &[String] {
60        &self.warnings
61    }
62}
63
64/// Columns holding *position* values: rows with non-finite values here are
65/// dropped before stats (and again after, for stat output).
66const POSITION_COLS: &[&str] = &[
67    "x",
68    "y",
69    "xmin",
70    "xmax",
71    "ymin",
72    "ymax",
73    "xend",
74    "yend",
75    "open",
76    "high",
77    "low",
78    "close",
79    "xintercept",
80    "yintercept",
81    "slope",
82    "intercept",
83    // Boxplot stat="identity" hinges (B3-5). `outliers` is a comma-list
84    // string, not a position value, so it's not listed here — a non-finite
85    // outlier is skipped individually with its own warning when parsed.
86    "lower",
87    "middle",
88    "upper",
89];
90
91/// Columns a position scale's transformation applies to (pre-stat).
92const X_FAMILY: &[&str] = &["x", "xmin", "xmax", "xend", "xintercept"];
93const Y_FAMILY: &[&str] = &[
94    "y",
95    "ymin",
96    "ymax",
97    "yend",
98    "open",
99    "high",
100    "low",
101    "close",
102    "yintercept",
103    "lower",
104    "middle",
105    "upper",
106];
107
108/// Reference-line intercept columns and the position scale they train
109/// (ggplot2: `xintercept`/`yintercept` are x/y aesthetics).
110const INTERCEPT_COLS: [(&str, Aesthetic); 2] =
111    [("xintercept", Aesthetic::X), ("yintercept", Aesthetic::Y)];
112
113/// Train `scale` on reference-line intercepts. A numeric intercept on a
114/// discrete axis is a position *between* categories (ggplot2), not a level.
115fn train_intercepts(scale: &mut Box<dyn crate::scale::Scale>, values: &[crate::data::Value]) {
116    if scale.is_discrete() && values.iter().all(|v| v.as_f64().is_some() || v.is_na()) {
117        return;
118    }
119    scale.train(values);
120}
121
122/// Map a canonical column name to the aesthetic whose scale formats it
123/// (B2-5 tooltip templates / B2-4 `data-fvalue`-style formatting). Columns
124/// outside this list (group, label, or a stat output like `count`) have no
125/// scale of their own: [`render_tooltip_template`] falls back to the plain
126/// display format for them.
127fn column_aesthetic(name: &str) -> Option<Aesthetic> {
128    match name {
129        "x" => Some(Aesthetic::X),
130        "y" => Some(Aesthetic::Y),
131        "fill" => Some(Aesthetic::Fill),
132        "color" | "colour" => Some(Aesthetic::Color),
133        "size" => Some(Aesthetic::Size),
134        "linewidth" => Some(Aesthetic::Linewidth),
135        "alpha" => Some(Aesthetic::Alpha),
136        // Position columns (B3-5, D9 allowed #7): formatted through the
137        // x/y scale, same as the bare `x`/`y` they're derived from.
138        "xmin" | "xmax" | "xend" => Some(Aesthetic::X),
139        "ymin" | "ymax" | "yend" | "lower" | "middle" | "upper" => Some(Aesthetic::Y),
140        _ => None,
141    }
142}
143
144/// Render one row of a `GGPlot::tooltip` template: `{column}` is filled
145/// from `data`'s row `row`, formatted through that column's scale when
146/// [`column_aesthetic`] names one and it has a
147/// [`Scale::format_value`](crate::scale::Scale::format_value) (else the
148/// plain display format); a column that doesn't exist on this layer is
149/// empty, not literally `{column}`. `{{`/`}}` are literal braces.
150fn render_tooltip_template(
151    template: &str,
152    data: &DataFrame,
153    scales: &ScaleSet,
154    row: usize,
155) -> String {
156    let mut out = String::new();
157    let mut chars = template.chars().peekable();
158    while let Some(c) = chars.next() {
159        match c {
160            '{' if chars.peek() == Some(&'{') => {
161                chars.next();
162                out.push('{');
163            }
164            '}' if chars.peek() == Some(&'}') => {
165                chars.next();
166                out.push('}');
167            }
168            '{' => {
169                let mut name = String::new();
170                let mut closed = false;
171                for nc in chars.by_ref() {
172                    if nc == '}' {
173                        closed = true;
174                        break;
175                    }
176                    name.push(nc);
177                }
178                if closed {
179                    out.push_str(&render_placeholder(&name, data, scales, row));
180                } else {
181                    // Unterminated `{…` to end of string: not a placeholder,
182                    // kept literally.
183                    out.push('{');
184                    out.push_str(&name);
185                }
186            }
187            c => out.push(c),
188        }
189    }
190    out
191}
192
193fn render_placeholder(name: &str, data: &DataFrame, scales: &ScaleSet, row: usize) -> String {
194    let Some(col) = data.column(name) else {
195        return String::new();
196    };
197    let Some(v) = col.get(row) else {
198        return String::new();
199    };
200    if v.is_na() {
201        return String::new();
202    }
203    if let Some(formatted) = column_aesthetic(name)
204        .and_then(|aes| scales.get(&aes))
205        .and_then(|s| s.format_value(v))
206    {
207        return formatted;
208    }
209    crate::geom::tip_value(v)
210}
211
212/// The grammar pipeline: transforms a GGPlot specification into render-ready data.
213pub struct PlotBuilder;
214
215impl PlotBuilder {
216    pub fn build(plot: GGPlot) -> Result<BuiltPlot, GGError> {
217        let GGPlot {
218            data: plot_data,
219            mapping: plot_mapping,
220            layers,
221            scales: user_scales,
222            mut coord,
223            theme,
224            labels,
225            facet,
226            annotations,
227            guide_legend,
228            warnings: plot_warnings,
229            default_aspect_ratio,
230            locale,
231            svg_root_data: _,
232            root_attrs: _,
233            svg_warnings_attr: _,
234            svg_formatted_values: _,
235        } = plot;
236        let mut theme = theme;
237        if theme.aspect_ratio.is_none() {
238            theme.aspect_ratio = default_aspect_ratio;
239        }
240
241        // Malformed input (e.g. mismatched column lengths) is reported here as
242        // a validation error instead of panicking when the frame is assembled.
243        plot_data.validate()?;
244        for layer in &layers {
245            if let Some(d) = &layer.data {
246                d.validate()?;
247            }
248        }
249
250        let mut scale_set = ScaleSet::new();
251
252        // Add user-specified scales
253        for s in user_scales {
254            scale_set.add(s);
255        }
256
257        let mut built_layers = Vec::new();
258        let mut warnings: Vec<String> = plot_warnings;
259
260        // Faceting variables — used to group stat computation per panel so a
261        // computed stat (density/histogram) is estimated per panel, not pooled.
262        let facet_vars = Self::facet_vars(&facet);
263
264        for layer in layers {
265            let built = Self::build_layer(
266                layer,
267                &plot_data,
268                &plot_mapping,
269                &mut scale_set,
270                &theme,
271                &facet_vars,
272                &mut warnings,
273            )?;
274            built_layers.push(built);
275        }
276
277        // Final scale training pass across all layers
278        for bl in &built_layers {
279            scale_set.train_layer(&bl.data);
280            for (col, aes) in &INTERCEPT_COLS {
281                // No layer created this position scale: the intercepts do.
282                if let (Some(values), None) = (bl.data.column(col), scale_set.get(aes)) {
283                    let mut frame = DataFrame::new();
284                    frame.add_column(aes.col_name().to_string(), values.to_vec());
285                    scale_set.ensure_scale(aes, &frame);
286                }
287                if let (Some(values), Some(scale)) = (bl.data.column(col), scale_set.get_mut(aes)) {
288                    train_intercepts(scale, values);
289                }
290            }
291        }
292
293        // Validate each scale's final configuration (e.g. a transform
294        // undefined at its own domain limits) now that training is done —
295        // `map`/`map_to_size` run per mark at draw time and have no
296        // warnings sink of their own.
297        for scale in scale_set.iter() {
298            scale.validate(&mut warnings);
299        }
300
301        // An empty plot (no layers, or only layers without data) still gets a
302        // panel with axes: make sure both position scales exist. They stay
303        // untrained, so they draw no breaks and map everything to the centre.
304        if built_layers.iter().all(|bl| bl.data.nrows() == 0) {
305            for aes in [Aesthetic::X, Aesthetic::Y] {
306                if scale_set.get(&aes).is_none() {
307                    scale_set.add(Box::new(
308                        crate::scale::continuous::ScaleContinuous::new().for_aesthetic(aes),
309                    ));
310                }
311            }
312        }
313
314        // Apply coord zoom limits (coord_cartesian xlim/ylim)
315        if let Some((min, max)) = coord.zoom_x() {
316            scale_set.set_limits(&Aesthetic::X, min, max);
317        }
318        if let Some((min, max)) = coord.zoom_y() {
319            scale_set.set_limits(&Aesthetic::Y, min, max);
320        }
321
322        // Let the coordinate system adjust/inspect the trained scales.
323        coord.train_scales(&mut scale_set);
324
325        // Supply trained axis spans to the coordinate system (used by coord_trans).
326        // pmin/pmax are the panel positions of the domain endpoints, so the coord
327        // can invert the scale's (linearly expanded) mapping exactly.
328        let axis_span = |aes: &Aesthetic| {
329            scale_set.get(aes).and_then(|s| {
330                s.domain().map(|(min, max)| crate::coord::AxisSpan {
331                    min,
332                    max,
333                    pmin: s.map(&crate::data::Value::Float(min)),
334                    pmax: s.map(&crate::data::Value::Float(max)),
335                })
336            })
337        };
338        let x_span = axis_span(&Aesthetic::X);
339        let y_span = axis_span(&Aesthetic::Y);
340        coord.set_domains(x_span, y_span);
341
342        // Apply after_scale() color derivations: copy the source aesthetic's
343        // column to the target and register a lightness-modified clone of the
344        // source scale, so the target aesthetic draws the mapped source color
345        // adjusted in lightness (e.g. a darker border derived from the fill).
346        for spec in &plot_mapping.after_scale {
347            if let Some(src_scale) = scale_set.get(&spec.source) {
348                let modified = crate::scale::modified::ScaleColorModified::new(
349                    src_scale.clone_box(),
350                    spec.target.clone(),
351                    spec.lightness,
352                );
353                let (src_col, tgt_col) = (spec.source.col_name(), spec.target.col_name());
354                for bl in &mut built_layers {
355                    if !bl.data.has_column(tgt_col) {
356                        if let Some(vals) = bl.data.column(src_col) {
357                            let vals = vals.to_vec();
358                            bl.data.add_column(tgt_col.to_string(), vals);
359                        }
360                    }
361                }
362                scale_set.add(Box::new(modified));
363            }
364        }
365
366        // Plot-level locale for default break labels (before panel scales are
367        // cloned from the base set, so free facets inherit it).
368        if let Some(locale) = &locale {
369            scale_set.set_default_locale(locale);
370        }
371
372        // Compute facet panels
373        let (panels, panels_data) = Self::compute_facets(&facet, &built_layers, &plot_data);
374
375        // Compute suppressed aesthetics from show_legend flags.
376        let suppressed_aes = Self::compute_suppressed_aes(&built_layers);
377
378        // Compute per-panel scales for free facets
379        let facet_scales_mode = match &facet {
380            Facet::Wrap { scales, .. } => scales.clone(),
381            Facet::Grid { scales, .. } => scales.clone(),
382            Facet::None => FacetScales::Fixed,
383        };
384        let panel_scales = Self::compute_panel_scales(&facet_scales_mode, &panels_data, &scale_set);
385
386        Ok(BuiltPlot {
387            layers: built_layers,
388            scales: scale_set,
389            coord,
390            theme,
391            labels,
392            facet,
393            panels,
394            panels_data,
395            annotations,
396            guide_legend,
397            suppressed_aes,
398            panel_scales,
399            warnings,
400            legend_plans: std::collections::HashMap::new(),
401        })
402    }
403
404    /// Keep only the rows whose `keep` flag is set.
405    fn retain_rows(data: &mut DataFrame, keep: &[bool]) {
406        if keep.iter().all(|&k| k) {
407            return;
408        }
409        let mut result = DataFrame::new();
410        for col_name in data.column_names() {
411            if let Some(src) = data.column(col_name) {
412                let vals: Vec<_> = src
413                    .iter()
414                    .zip(keep)
415                    .filter(|(_, &k)| k)
416                    .map(|(v, _)| v.clone())
417                    .collect();
418                result.add_column(col_name.to_string(), vals);
419            }
420        }
421        *data = result;
422    }
423
424    /// Drop rows with a non-finite value in any position column (`NaN` always;
425    /// `±Inf` unless the geom gives infinities meaning). Returns the number of
426    /// rows removed.
427    /// `keep_as_break`: for a connecting geom ([`Geom::keeps_na_as_break`]),
428    /// a bad row is counted (for the warning) but not deleted — it stays in
429    /// `data` as a non-finite pixel position, which `DrawBackend::draw_line`
430    /// splits the polyline on, instead of being spliced out and silently
431    /// joining the finite points across the gap.
432    /// `exclude`: column names to skip entirely this call — `lower`/
433    /// `middle`/`upper` present in the raw data but not mapped as that
434    /// aesthetic on this layer (review #158's final check: these must
435    /// never cost an unrelated geom its rows; see `raw_unmapped` at the
436    /// call site).
437    fn drop_non_finite(
438        data: &mut DataFrame,
439        allow_infinite: bool,
440        keep_as_break: bool,
441        exclude: &[&str],
442    ) -> usize {
443        let n = data.nrows();
444        let mut keep = vec![true; n];
445        for col in POSITION_COLS {
446            if exclude.contains(col) {
447                continue;
448            }
449            if let Some(values) = data.column(col) {
450                // Several position columns are legitimately discrete
451                // (`Value::Str`) in this codebase — not just `x`/`y`, e.g.
452                // `geom_bracket`'s `xmin`/`xmax` hold category names for a
453                // bracket spanning two discrete groups. `Value::Na` is
454                // unambiguously missing everywhere, though (review #158
455                // finding 4: a SQL NULL in a boxplot position column used
456                // to silently map to 0 instead of being dropped with the
457                // standard warning; only `Float(NaN)` was caught before).
458                // The new boxplot-only `lower`/`middle`/`upper` columns
459                // have no legitimate discrete use anywhere, so a
460                // non-numeric, non-`Na` value there (a stray string) is
461                // missing too.
462                let strictly_numeric = matches!(*col, "lower" | "middle" | "upper");
463                for (i, v) in values.iter().enumerate() {
464                    let bad = match v {
465                        crate::data::Value::Na => true,
466                        crate::data::Value::Float(f) => {
467                            f.is_nan() || (f.is_infinite() && !allow_infinite)
468                        }
469                        _ if strictly_numeric => v.as_f64().is_none(),
470                        _ => false,
471                    };
472                    if bad {
473                        keep[i] = false;
474                    }
475                }
476            }
477        }
478        let removed = keep.iter().filter(|&&k| !k).count();
479        if removed > 0 && !keep_as_break {
480            Self::retain_rows(data, &keep);
481        }
482        removed
483    }
484
485    /// The column name(s) a facet splits on, if any.
486    fn facet_vars(facet: &Facet) -> Vec<String> {
487        match facet {
488            Facet::None => vec![],
489            Facet::Wrap { var, .. } => vec![var.clone()],
490            Facet::Grid {
491                row_var, col_var, ..
492            } => row_var.iter().chain(col_var.iter()).cloned().collect(),
493        }
494    }
495
496    fn compute_facets(
497        facet: &Facet,
498        built_layers: &[BuiltLayer],
499        _plot_data: &DataFrame,
500    ) -> (Vec<Panel>, Vec<Vec<DataFrame>>) {
501        match facet {
502            Facet::None => (vec![], vec![]),
503            Facet::Wrap {
504                var,
505                ncol,
506                labeller,
507                ..
508            } => {
509                // Collect unique levels from all layers' data
510                let mut levels: Vec<String> = Vec::new();
511                for bl in built_layers {
512                    if let Some(col) = bl.data.column(var) {
513                        for v in col {
514                            let key = v.to_group_key();
515                            if !levels.contains(&key) {
516                                levels.push(key);
517                            }
518                        }
519                    }
520                }
521
522                // Panels will be positioned during rendering (depends on layout)
523                let panels: Vec<Panel> = levels
524                    .iter()
525                    .enumerate()
526                    .map(|(i, value)| {
527                        let ncols =
528                            ncol.unwrap_or_else(|| (levels.len() as f64).sqrt().ceil() as usize);
529                        let formatted = labeller.format(var, value);
530                        Panel {
531                            row: i / ncols.max(1),
532                            col: i % ncols.max(1),
533                            label: formatted.clone(),
534                            row_label: None,
535                            col_label: Some(formatted),
536                            rect: crate::render::Rect {
537                                x: 0.0,
538                                y: 0.0,
539                                width: 0.0,
540                                height: 0.0,
541                            },
542                        }
543                    })
544                    .collect();
545
546                // Split data per panel per layer
547                let panels_data: Vec<Vec<DataFrame>> = levels
548                    .iter()
549                    .map(|level| {
550                        built_layers
551                            .iter()
552                            .map(|bl| Self::filter_data_by_var(&bl.data, var, level))
553                            .collect()
554                    })
555                    .collect();
556
557                (panels, panels_data)
558            }
559            Facet::Grid {
560                row_var,
561                col_var,
562                labeller,
563                ..
564            } => {
565                let mut row_levels: Vec<String> = Vec::new();
566                let mut col_levels: Vec<String> = Vec::new();
567
568                for bl in built_layers {
569                    if let Some(rv) = row_var {
570                        if let Some(col) = bl.data.column(rv) {
571                            for v in col {
572                                let key = v.to_group_key();
573                                if !row_levels.contains(&key) {
574                                    row_levels.push(key);
575                                }
576                            }
577                        }
578                    }
579                    if let Some(cv) = col_var {
580                        if let Some(col) = bl.data.column(cv) {
581                            for v in col {
582                                let key = v.to_group_key();
583                                if !col_levels.contains(&key) {
584                                    col_levels.push(key);
585                                }
586                            }
587                        }
588                    }
589                }
590
591                if row_levels.is_empty() {
592                    row_levels.push("".to_string());
593                }
594                if col_levels.is_empty() {
595                    col_levels.push("".to_string());
596                }
597
598                let mut panels = Vec::new();
599                let mut panels_data = Vec::new();
600
601                for (ri, rl) in row_levels.iter().enumerate() {
602                    for (ci, cl) in col_levels.iter().enumerate() {
603                        let row_fmt = if rl.is_empty() {
604                            None
605                        } else {
606                            let rv = row_var.as_deref().unwrap_or("");
607                            Some(labeller.format(rv, rl))
608                        };
609                        let col_fmt = if cl.is_empty() {
610                            None
611                        } else {
612                            let cv = col_var.as_deref().unwrap_or("");
613                            Some(labeller.format(cv, cl))
614                        };
615                        let label = match (&row_fmt, &col_fmt) {
616                            (Some(r), Some(c)) => format!("{r} | {c}"),
617                            (Some(r), None) => r.clone(),
618                            (None, Some(c)) => c.clone(),
619                            (None, None) => String::new(),
620                        };
621                        panels.push(Panel {
622                            row: ri,
623                            col: ci,
624                            label,
625                            row_label: row_fmt,
626                            col_label: col_fmt,
627                            rect: crate::render::Rect {
628                                x: 0.0,
629                                y: 0.0,
630                                width: 0.0,
631                                height: 0.0,
632                            },
633                        });
634
635                        let layer_data: Vec<DataFrame> = built_layers
636                            .iter()
637                            .map(|bl| {
638                                let mut data = bl.data.clone();
639                                if let Some(rv) = row_var {
640                                    if !rl.is_empty() {
641                                        data = Self::filter_data_by_var(&data, rv, rl);
642                                    }
643                                }
644                                if let Some(cv) = col_var {
645                                    if !cl.is_empty() {
646                                        data = Self::filter_data_by_var(&data, cv, cl);
647                                    }
648                                }
649                                data
650                            })
651                            .collect();
652                        panels_data.push(layer_data);
653                    }
654                }
655
656                (panels, panels_data)
657            }
658        }
659    }
660
661    fn filter_data_by_var(data: &DataFrame, var: &str, level: &str) -> DataFrame {
662        if let Some(col) = data.column(var) {
663            let indices: Vec<usize> = col
664                .iter()
665                .enumerate()
666                .filter(|(_, v)| v.to_group_key() == level)
667                .map(|(i, _)| i)
668                .collect();
669
670            let mut result = DataFrame::new();
671            for col_name in data.column_names() {
672                if let Some(src) = data.column(col_name) {
673                    let vals: Vec<_> = indices.iter().map(|&i| src[i].clone()).collect();
674                    result.add_column(col_name.to_string(), vals);
675                }
676            }
677            result
678        } else {
679            data.clone()
680        }
681    }
682
683    fn build_layer(
684        layer: Layer,
685        plot_data: &DataFrame,
686        plot_mapping: &Aes,
687        scale_set: &mut ScaleSet,
688        theme: &Theme,
689        facet_vars: &[String],
690        warnings: &mut Vec<String>,
691    ) -> Result<BuiltLayer, GGError> {
692        let primary = theme.primary;
693        let geom_theme = &theme.geom;
694        let Layer {
695            data: layer_data,
696            mapping: layer_mapping,
697            mut geom,
698            stat,
699            position,
700            params: _,
701            show_legend,
702            explicit_style,
703            tooltip_template,
704        } = layer;
705
706        // Step 1: Resolve data — use layer data if provided, else plot data
707        // Borrow the plot data when the layer has none of its own (no per-layer
708        // full-frame clone; `resolve_mappings` copies only the columns it needs).
709        let source_data = layer_data.as_ref().unwrap_or(plot_data);
710
711        // Step 2: Merge mappings — layer overrides plot-level
712        // (Reference lines don't inherit the plot mapping — ggplot2's
713        // `inherit.aes = FALSE`.)
714        let merged_mapping = if geom.inherit_aes() {
715            plot_mapping.merge(&layer_mapping)
716        } else {
717            layer_mapping.clone()
718        };
719
720        // B2-7: geom ink/paper/accent palette, applied before the brand
721        // colour below so a primary colour still wins when both are set.
722        // Skipped when the layer was configured explicitly
723        // (`geom_*_with(...)`) — the same `explicit_style` gate
724        // `set_series_color` uses below, and for the same reason: a
725        // field-value comparison against the hard-coded default (e.g.
726        // `color == (0, 0, 0)`) can't tell an explicitly-set black apart
727        // from a black that was simply never touched (review PR#141
728        // finding 4), but `explicit_style` can.
729        if !explicit_style {
730            geom.apply_element_geom(geom_theme);
731        }
732
733        // Brand/primary color: apply to a single-series geom only when the layer
734        // maps neither color nor fill (an explicit aesthetic always wins) and
735        // the geom wasn't configured explicitly via `geom_*_with(...)`.
736        if let Some(color) = primary.filter(|_| !explicit_style) {
737            let has_color = merged_mapping.get_mapping(&Aesthetic::Color).is_some();
738            let has_fill = merged_mapping.get_mapping(&Aesthetic::Fill).is_some();
739            if !has_color && !has_fill {
740                geom.set_series_color(color);
741            }
742        }
743
744        // Step 3: Evaluate aes — rename columns to canonical names
745        let mut working_data = resolve_mappings(source_data, &merged_mapping, warnings);
746
747        // D3 (B3-5): drop a "mapped-only" column (e.g. `lower`/`middle`/
748        // `upper`/`outliers` for the boxplot) unless the user actually
749        // mapped that aesthetic — so a raw column that merely happens to
750        // share the name (a SQL alias, say) is never mistaken for one, and
751        // so a raw `lower` is never drawn as a boxplot hinge on
752        // `geom_boxplot` itself.
753        //
754        // Review #158's *final check* found that making this drop
755        // universal (every geom, round 3's `MAPPED_ONLY_COLS`) was itself
756        // a regression: it removed the raw `lower`/`middle`/`upper`/
757        // `outliers` columns from a layer's data entirely, so a forecast
758        // chart's `tooltip("{y} [{lower}, {upper}]")` on an unmapped
759        // `geom_line` rendered `[, ]` instead of the actual bounds, and
760        // `facet_wrap("upper")` on an unmapped column silently rendered
761        // unfaceted. ggplot2 never drops a raw data column just because
762        // its name matches an unused extension aesthetic — it only ever
763        // special-cases `lower`/`middle`/`upper`/`outliers` for
764        // `geom_boxplot`'s own hinges, so this drop goes back to being
765        // scoped to `geom.mapped_only_columns()` alone (empty by default,
766        // `GeomBoxplot` returns the four names). The narrower position/
767        // non-finite/y-scale-training concerns from the *previous*
768        // re-review (the forecast y-domain-stretch/row-drop regression)
769        // are instead handled per layer below (`raw_unmapped`), without
770        // ever removing the columns from `working_data`.
771        for col in geom.mapped_only_columns() {
772            let is_mapped = merged_mapping
773                .mappings
774                .iter()
775                .any(|m| m.aesthetic.col_name() == *col);
776            if !is_mapped {
777                working_data.remove_column(col);
778            }
779        }
780
781        // `lower`/`middle`/`upper` present in the raw (pre-stat) data under
782        // their canonical name, but *not* actually mapped as that
783        // aesthetic on this layer — e.g. a forecast's confidence-bound
784        // columns, never mapped on a plain `geom_line`/`geom_point` layer.
785        // These stay in `working_data` (see above), but mustn't be treated
786        // as position data a geom never asked for: excluded below from the
787        // non-finite/NA position drop, the `Y_FAMILY` pre-stat scale
788        // transform, and the y-scale training.
789        //
790        // Computed once, right here (before the stat runs), so it reflects
791        // only what the *raw* data actually had under these names.
792        // `GeomBoxplot`'s own default (non-identity) stat produces *fresh*
793        // `lower`/`middle`/`upper` columns later (not present yet, so never
794        // in this set) — those stay subject to all three, unaffected; an
795        // identity-stat boxplot has them mapped (required by
796        // `validate_layer` below), so they're not in this set either.
797        let raw_unmapped: Vec<&'static str> = ["lower", "middle", "upper"]
798            .into_iter()
799            .filter(|col| {
800                working_data.has_column(col)
801                    && !merged_mapping
802                        .mappings
803                        .iter()
804                        .any(|m| m.aesthetic.col_name() == *col)
805            })
806            .collect();
807
808        // Remember which columns the user actually supplied (pre-stat). A required
809        // aesthetic is satisfied if it was present here OR is synthesized by the
810        // stat (checked after Step 6) — e.g. boxplot maps `y` then the stat turns
811        // it into ymin/ymax, while StatEcdf produces `y` that wasn't mapped.
812        let pre_stat_columns: Vec<String> = working_data
813            .column_names()
814            .iter()
815            .map(|s| s.to_string())
816            .collect();
817
818        // B3-5: stat-dependent validation beyond `required_aes` (e.g.
819        // `geom_boxplot` requires lower/middle/upper under stat="identity",
820        // else y) — before Step 4, so a bad mapping fails before any scale
821        // work happens.
822        if let Err(msg) = geom.validate_layer(&pre_stat_columns, stat.name()) {
823            return Err(GGError::ValidationError(msg));
824        }
825
826        // Step 4: Ensure scales exist for each mapped aesthetic
827        for m in &merged_mapping.mappings {
828            scale_set.ensure_scale(&m.aesthetic, &working_data);
829        }
830
831        // Step 5: Scale transformation (e.g., log10 before stats). A position
832        // scale transforms every column of its family (y also ymin/ymax/…).
833        for scale in scale_set.iter() {
834            let aes = scale.aesthetic();
835            let cols: Vec<&str> = match aes {
836                Aesthetic::X => X_FAMILY.to_vec(),
837                // `lower`/`middle`/`upper` present but unmapped (raw
838                // forecast-shaped passthrough columns, say) are not
839                // position data this layer's geom reads, so a log/sqrt/…
840                // y-scale transform must not touch them (review #158's
841                // final check).
842                Aesthetic::Y => Y_FAMILY
843                    .iter()
844                    .copied()
845                    .filter(|c| !raw_unmapped.contains(c))
846                    .collect(),
847                _ => vec![aes.col_name()],
848            };
849            for col_name in cols {
850                let Some(col) = working_data.column(col_name) else {
851                    continue;
852                };
853                // A transform that is undefined for a value (log of 0 or a
854                // negative) yields NaN, so the non-finite filter below drops
855                // the row with a warning instead of drawing it at 0.
856                let transformed: Vec<_> = col
857                    .iter()
858                    .map(|v| match (scale.transform(v), v.as_f64()) {
859                        (crate::data::Value::Na, Some(_)) => crate::data::Value::Float(f64::NAN),
860                        (t, _) => t,
861                    })
862                    .collect();
863                let any_changed = transformed.iter().zip(col.iter()).any(|(t, o)| {
864                    match (t.as_f64(), o.as_f64()) {
865                        (Some(a), Some(b)) => a.is_nan() || (a - b).abs() > f64::EPSILON,
866                        _ => false,
867                    }
868                });
869                if any_changed {
870                    if let Some(col_mut) = working_data.column_mut(col_name) {
871                        *col_mut = transformed;
872                    }
873                }
874            }
875        }
876
877        // Step 5b: Filter out-of-bounds data (xlim/ylim filter before stats)
878        Self::filter_oob_data(&mut working_data, scale_set);
879
880        // Step 5c: Drop rows whose position is NaN (or ±Inf, unless the geom
881        // reads infinities as "panel edge"), like ggplot2's
882        // "Removed n rows containing non-finite values".
883        let geom_label = format!("geom_{}", geom.name());
884        let removed = Self::drop_non_finite(
885            &mut working_data,
886            geom.allows_infinite(),
887            geom.keeps_na_as_break(),
888            &raw_unmapped,
889        );
890        if removed > 0 {
891            warnings.push(format!(
892                "{geom_label}: removed {removed} row{} containing non-finite values",
893                if removed == 1 { "" } else { "s" }
894            ));
895        }
896        let input_rows = working_data.nrows();
897
898        // Validate the stat's own configuration once per layer (e.g.
899        // `StatBinHex::binwidth` — a problem with fixed parameters, not
900        // with the data), before it runs per-group below.
901        stat.validate(warnings);
902
903        // Step 6: Compute statistics. Group by aesthetic groups AND the facet
904        // variables, so a computed stat (density/histogram/…) is estimated per
905        // panel rather than on pooled data; the facet column is then re-attached
906        // to each group's output so faceting can split it back out.
907        // Panelwise stats (e.g. stat_compare_means) see the whole panel at once,
908        // so we group only by facet variables, not by aesthetic groups.
909        let mut group_cols = if stat.panelwise() {
910            Vec::new()
911        } else {
912            Self::detect_group_columns(&working_data)
913        };
914        for fv in facet_vars {
915            if working_data.has_column(fv) && !group_cols.contains(fv) {
916                group_cols.push(fv.clone());
917            }
918        }
919
920        working_data = if !group_cols.is_empty() {
921            let groups =
922                working_data.group_by(&group_cols.iter().map(|s| s.as_str()).collect::<Vec<_>>());
923            let mut result = DataFrame::new();
924            for group in groups {
925                let mut computed = stat.compute_group(&group, scale_set);
926                let n = computed.nrows();
927                if n > 0 {
928                    for fv in facet_vars {
929                        if !computed.has_column(fv) {
930                            if let Some(val) = group.column(fv).and_then(|c| c.first()).cloned() {
931                                computed.add_column(fv.clone(), vec![val; n]);
932                            }
933                        }
934                    }
935                }
936                result.vstack(&computed);
937            }
938            result
939        } else {
940            stat.compute_group(&working_data, scale_set)
941        };
942
943        // Step 6a: Apply after_stat() mappings (rename stat-computed columns)
944        apply_after_stat(&mut working_data, &merged_mapping, warnings);
945
946        // Stat output can contain NaN (e.g. a fit on degenerate input): drop
947        // those rows too, so nothing non-finite reaches a geom. `raw_unmapped`
948        // was computed pre-stat, so a passthrough stat (e.g. `StatIdentity`
949        // under `geom_line`/`geom_point`) still excludes the same raw,
950        // unmapped `lower`/`middle`/`upper` here as it did above; a stat
951        // that *produces* these fresh (`StatBoxplot`'s default, non-identity
952        // path) was never in that set, since they didn't exist pre-stat.
953        let removed = Self::drop_non_finite(
954            &mut working_data,
955            geom.allows_infinite(),
956            geom.keeps_na_as_break(),
957            &raw_unmapped,
958        );
959        if removed > 0 {
960            warnings.push(format!(
961                "{geom_label}: removed {removed} row{} containing missing values (stat_{} output)",
962                if removed == 1 { "" } else { "s" },
963                stat.name()
964            ));
965        }
966
967        // A layer with no data draws nothing — an empty input, or a stat that
968        // cannot estimate anything (a density of one value, loess on two
969        // points). It must not fail the whole plot. A stat's own required
970        // aesthetics are still validated when there *was* input.
971        if working_data.nrows() == 0 {
972            if input_rows > 0 {
973                for aes in &stat.required_aes() {
974                    let col_name = aes.col_name();
975                    if !pre_stat_columns.iter().any(|c| c == col_name) {
976                        return Err(GGError::ValidationError(format!(
977                            "stat_{} requires aesthetic '{}' but it was not provided",
978                            stat.name(),
979                            col_name
980                        )));
981                    }
982                }
983                warnings.push(format!(
984                    "{geom_label}: stat_{} produced no data from {input_rows} row{} \
985                     (too few or degenerate values); layer skipped",
986                    stat.name(),
987                    if input_rows == 1 { "" } else { "s" }
988                ));
989            }
990            return Ok(BuiltLayer {
991                data: DataFrame::new(),
992                geom,
993                show_legend,
994            });
995        }
996
997        // Step 6a-validate: A required aesthetic must have been supplied by the
998        // user (pre-stat) or synthesized by the stat (post-stat). This lets
999        // StatEcdf produce `y` for geom_step, while boxplot — which maps `y` then
1000        // consumes it into ymin/ymax — still validates. Empty input has the
1001        // column in neither place, so genuinely-missing aesthetics still error.
1002        for aes in &geom.required_aes() {
1003            let col_name = aes.col_name();
1004            let supplied = pre_stat_columns.iter().any(|c| c == col_name);
1005            if !supplied && !working_data.has_column(col_name) {
1006                return Err(GGError::ValidationError(format!(
1007                    "geom_{} requires aesthetic '{}' but it was not provided",
1008                    geom.name(),
1009                    col_name
1010                )));
1011            }
1012        }
1013
1014        // Step 6b: Ensure scales for stat-computed aesthetics (e.g. y from StatCount/StatBin)
1015        let stat_aes = [
1016            ("x", Aesthetic::X),
1017            ("y", Aesthetic::Y),
1018            ("xmin", Aesthetic::X),
1019            ("xmax", Aesthetic::X),
1020            ("ymin", Aesthetic::Y),
1021            ("ymax", Aesthetic::Y),
1022            // Boxplot stat="identity" hinges (B3-5): live on the y scale.
1023            ("lower", Aesthetic::Y),
1024            ("middle", Aesthetic::Y),
1025            ("upper", Aesthetic::Y),
1026            // Boxplot outlier extent (B3-5, allowed #6): `GeomBoxplot::
1027            // setup_data` adds these (under an internal-prefix name — see
1028            // review #158 finding 5 and `aes::BOXPLOT_YMIN_FINAL`'s doc,
1029            // so a raw column can never forge them) from the parsed
1030            // `outliers` column, so the y scale trains on them too (step
1031            // 8b below).
1032            (crate::aes::BOXPLOT_YMIN_FINAL, Aesthetic::Y),
1033            (crate::aes::BOXPLOT_YMAX_FINAL, Aesthetic::Y),
1034        ];
1035        // `raw_unmapped` (a raw, unmapped `lower`/`middle`/`upper` passthrough
1036        // column) never trains or gets a scale here — only a layer that
1037        // actually mapped (or whose stat computed) that name does (review
1038        // #158's final check).
1039        for (col, aes) in &stat_aes {
1040            if working_data.has_column(col) && !raw_unmapped.contains(col) {
1041                scale_set.ensure_scale(aes, &working_data);
1042            }
1043        }
1044
1045        // Step 6c: bars/histograms/area draw from a 0 baseline, so the Y scale
1046        // must include 0 — for stat-computed Y (count/bin) and for an explicitly
1047        // mapped Y alike (e.g. geom_col), matching ggplot2.
1048        let y_is_user_mapped = merged_mapping.get_mapping(&Aesthetic::Y).is_some();
1049        if (!y_is_user_mapped || geom.include_zero_baseline()) && working_data.has_column("y") {
1050            if let Some(y_scale) = scale_set.get_mut(&Aesthetic::Y) {
1051                y_scale.train(&[crate::data::Value::Float(0.0)]);
1052            }
1053        }
1054
1055        // Step 7: Position adjustment. `validate` runs once per layer (D2)
1056        // regardless of whether the position is per-panel.
1057        position.validate(warnings);
1058        let params = PositionParams::default();
1059        if position.per_panel() {
1060            Self::compute_position_per_panel(
1061                position.as_ref(),
1062                &mut working_data,
1063                &params,
1064                facet_vars,
1065            );
1066        } else {
1067            position.compute(&mut working_data, &params);
1068        }
1069
1070        // Step 7b: Geom-specific setup (e.g. tile/candlestick extents), then
1071        // make sure position scales exist for any extent columns it added.
1072        geom.setup_data(&mut working_data, warnings);
1073        for (col, aes) in &stat_aes {
1074            if working_data.has_column(col) && !raw_unmapped.contains(col) {
1075                scale_set.ensure_scale(aes, &working_data);
1076            }
1077        }
1078
1079        // Step 8: Train scales on this layer's data
1080        scale_set.train_layer(&working_data);
1081        for (col, aes) in &INTERCEPT_COLS {
1082            if let (Some(values), Some(scale)) = (working_data.column(col), scale_set.get_mut(aes))
1083            {
1084                train_intercepts(scale, values);
1085            }
1086        }
1087
1088        // Step 8b: Positional scales also need to see stat-computed extent columns
1089        // (e.g. boxplot/errorbar/pointrange emit ymin/ymax but no "y"). Without
1090        // this the Y (or X) scale would never train on the range and collapse.
1091        // Same `raw_unmapped` exclusion as Step 6b/7b above: an unmapped
1092        // raw `lower`/`middle`/`upper` must never stretch the y domain.
1093        for (col, aes) in &stat_aes {
1094            if raw_unmapped.contains(col) {
1095                continue;
1096            }
1097            if let Some(values) = working_data.column(col) {
1098                if let Some(scale) = scale_set.get_mut(aes) {
1099                    scale.train(values);
1100                }
1101            }
1102        }
1103
1104        // Step 9 (B2-5): render a `tooltip()` template against the built
1105        // (post-stat) data, into the same internal column `Aes::tooltip`
1106        // uses — so it replaces the geom's default `<title>` the same way,
1107        // with no further geom-level plumbing.
1108        if let Some(template) = &tooltip_template {
1109            // Review PR#141 finding 6 (LOW): a template on a geom that
1110            // never reads that internal column (`set_row_extras`) did
1111            // nothing, silently — e.g. `geom_area`/`geom_boxplot`/
1112            // `geom_ribbon`.
1113            if !geom.consumes_tooltips() {
1114                warnings.push(format!(
1115                    "{geom_label}: tooltip(\"{template}\") has no effect — this geom doesn't read tooltips, or the layer is decorative()"
1116                ));
1117            }
1118            let rendered: Vec<crate::data::Value> = (0..working_data.nrows())
1119                .map(|i| {
1120                    crate::data::Value::Str(render_tooltip_template(
1121                        template,
1122                        &working_data,
1123                        scale_set,
1124                        i,
1125                    ))
1126                })
1127                .collect();
1128            working_data.add_column(crate::aes::TOOLTIP_INTERNAL_NAME.to_string(), rendered);
1129        }
1130
1131        Ok(BuiltLayer {
1132            data: working_data,
1133            geom,
1134            show_legend,
1135        })
1136    }
1137
1138    /// Remove rows where x or y falls outside scale limits set via xlim/ylim.
1139    fn filter_oob_data(data: &mut DataFrame, scale_set: &ScaleSet) {
1140        let x_limits = scale_set.get(&Aesthetic::X).and_then(|s| s.filter_limits());
1141        let y_limits = scale_set.get(&Aesthetic::Y).and_then(|s| s.filter_limits());
1142
1143        if x_limits.is_none() && y_limits.is_none() {
1144            return;
1145        }
1146
1147        let nrows = data.nrows();
1148        let mut keep = vec![true; nrows];
1149
1150        if let Some((min, max)) = x_limits {
1151            if let Some(col) = data.column("x") {
1152                for (i, v) in col.iter().enumerate() {
1153                    if let Some(f) = v.as_f64() {
1154                        if f < min || f > max {
1155                            keep[i] = false;
1156                        }
1157                    }
1158                }
1159            }
1160        }
1161
1162        if let Some((min, max)) = y_limits {
1163            if let Some(col) = data.column("y") {
1164                for (i, v) in col.iter().enumerate() {
1165                    if let Some(f) = v.as_f64() {
1166                        if f < min || f > max {
1167                            keep[i] = false;
1168                        }
1169                    }
1170                }
1171            }
1172        }
1173
1174        // If nothing was filtered, skip the rebuild
1175        if keep.iter().all(|&k| k) {
1176            return;
1177        }
1178
1179        let indices: Vec<usize> = keep
1180            .iter()
1181            .enumerate()
1182            .filter(|(_, &k)| k)
1183            .map(|(i, _)| i)
1184            .collect();
1185
1186        let mut result = DataFrame::new();
1187        for col_name in data.column_names() {
1188            if let Some(src) = data.column(col_name) {
1189                let vals: Vec<_> = indices.iter().map(|&i| src[i].clone()).collect();
1190                result.add_column(col_name.to_string(), vals);
1191            }
1192        }
1193        *data = result;
1194    }
1195
1196    /// Compute per-panel scale sets for free facet scales.
1197    /// For each panel, clones the base scale set, resets freed axes, and retrains on panel data.
1198    fn compute_panel_scales(
1199        facet_scales: &FacetScales,
1200        panels_data: &[Vec<DataFrame>],
1201        base_scales: &ScaleSet,
1202    ) -> Vec<ScaleSet> {
1203        if matches!(facet_scales, FacetScales::Fixed) || panels_data.is_empty() {
1204            return vec![];
1205        }
1206
1207        let free_x = matches!(facet_scales, FacetScales::FreeX | FacetScales::Free);
1208        let free_y = matches!(facet_scales, FacetScales::FreeY | FacetScales::Free);
1209
1210        panels_data
1211            .iter()
1212            .map(|panel_layers| {
1213                let mut panel_set = base_scales.clone();
1214
1215                // Reset freed axis scales
1216                if free_x {
1217                    if let Some(s) = panel_set.get_mut(&Aesthetic::X) {
1218                        s.reset_training();
1219                    }
1220                }
1221                if free_y {
1222                    if let Some(s) = panel_set.get_mut(&Aesthetic::Y) {
1223                        s.reset_training();
1224                    }
1225                }
1226
1227                // Retrain on this panel's data, including extent columns
1228                // (bars/tiles/ranges), so free scales cover whole marks.
1229                for layer_data in panel_layers {
1230                    panel_set.train_layer(layer_data);
1231                    for (cols, aes) in [
1232                        (["xmin", "xmax", "xintercept"], Aesthetic::X),
1233                        (["ymin", "ymax", "yintercept"], Aesthetic::Y),
1234                    ] {
1235                        let freed = match aes {
1236                            Aesthetic::X => free_x,
1237                            _ => free_y,
1238                        };
1239                        if !freed {
1240                            continue;
1241                        }
1242                        for c in cols {
1243                            if let (Some(vals), Some(s)) =
1244                                (layer_data.column(c), panel_set.get_mut(&aes))
1245                            {
1246                                if c.ends_with("intercept") {
1247                                    train_intercepts(s, vals);
1248                                } else {
1249                                    s.train(vals);
1250                                }
1251                            }
1252                        }
1253                    }
1254                }
1255
1256                panel_set
1257            })
1258            .collect()
1259    }
1260
1261    /// Compute which aesthetics should be suppressed from the legend.
1262    /// An aesthetic is suppressed if every layer that has the corresponding column
1263    /// sets show_legend=Some(false), and no layer has it as None or Some(true).
1264    fn compute_suppressed_aes(built_layers: &[BuiltLayer]) -> std::collections::HashSet<Aesthetic> {
1265        use std::collections::HashSet;
1266        let legend_aes = [
1267            Aesthetic::Color,
1268            Aesthetic::Fill,
1269            Aesthetic::Shape,
1270            Aesthetic::Linetype,
1271            Aesthetic::Size,
1272            Aesthetic::Alpha,
1273            Aesthetic::Linewidth,
1274        ];
1275        let mut suppressed = HashSet::new();
1276        for aes in &legend_aes {
1277            let col_name = aes.col_name();
1278            let mut any_has = false;
1279            let mut all_hidden = true;
1280            for bl in built_layers {
1281                if bl.data.has_column(col_name) {
1282                    any_has = true;
1283                    match bl.show_legend {
1284                        Some(false) => {} // still hidden
1285                        _ => {
1286                            all_hidden = false;
1287                            break;
1288                        }
1289                    }
1290                }
1291            }
1292            if any_has && all_hidden {
1293                suppressed.insert(aes.clone());
1294            }
1295        }
1296        suppressed
1297    }
1298
1299    /// Run a per-panel [`Position`](crate::position::Position) (B3-3, D8):
1300    /// partition the rows by the facet variables' joined key, in
1301    /// first-seen order, run `compute` on each panel separately, then
1302    /// scatter the rows back into their original positions — NA-filling
1303    /// any column a panel's `compute` added that another panel's didn't
1304    /// (there currently are none in practice: `PositionStack`/
1305    /// `PositionFill` add the same `ymin` everywhere). Falls back to the
1306    /// plain pooled `compute` when there's no facet column, or only one
1307    /// distinct panel — both byte-identical to the pooled path, since
1308    /// there's nothing to partition.
1309    fn compute_position_per_panel(
1310        position: &dyn crate::position::Position,
1311        data: &mut DataFrame,
1312        params: &PositionParams,
1313        facet_vars: &[String],
1314    ) {
1315        let active_vars: Vec<&str> = facet_vars
1316            .iter()
1317            .map(|s| s.as_str())
1318            .filter(|v| data.has_column(v))
1319            .collect();
1320        if active_vars.is_empty() {
1321            position.compute(data, params);
1322            return;
1323        }
1324
1325        let n = data.nrows();
1326        let mut order: Vec<String> = Vec::new();
1327        let mut groups: indexmap::IndexMap<String, Vec<usize>> = indexmap::IndexMap::new();
1328        for i in 0..n {
1329            let key = active_vars
1330                .iter()
1331                .map(|v| data.column(v).unwrap()[i].key_str().into_owned())
1332                .collect::<Vec<_>>()
1333                .join("\u{1}");
1334            if !groups.contains_key(&key) {
1335                order.push(key.clone());
1336            }
1337            groups.entry(key).or_default().push(i);
1338        }
1339        if order.len() < 2 {
1340            position.compute(data, params);
1341            return;
1342        }
1343
1344        // Review #167 finding 2: a per-panel position's group *rank*
1345        // (e.g. `PositionDodge`) must come from the whole layer, computed
1346        // here against the still-pooled `data` — before it's split into
1347        // the panels below — so every panel ranks a given group the same
1348        // way regardless of which group its own rows happen to list
1349        // first (sipemu/ggplot-rs#153; matches 0.22.2 and ggplot2 4.0.3's
1350        // global `group` id). Positions that don't override `group_order`
1351        // (stack/fill/jitter) get `None` back, unchanged from before.
1352        let mut panel_params = params.clone();
1353        panel_params.group_order = position.group_order(data);
1354
1355        let col_names: Vec<String> = data.column_names().iter().map(|s| s.to_string()).collect();
1356        let mut panels: Vec<(Vec<usize>, DataFrame)> = Vec::with_capacity(order.len());
1357        for key in &order {
1358            let indices = &groups[key];
1359            let mut sub = DataFrame::new();
1360            for name in &col_names {
1361                let col = data.column(name).unwrap();
1362                let values: Vec<crate::data::Value> =
1363                    indices.iter().map(|&i| col[i].clone()).collect();
1364                sub.add_column(name.clone(), values);
1365            }
1366            position.compute(&mut sub, &panel_params);
1367            panels.push((indices.clone(), sub));
1368        }
1369
1370        // Union of every column present after `compute` (new columns like
1371        // `ymin` may have been added), so a panel that for some reason
1372        // didn't add one still gets NA there rather than a stale value.
1373        let mut all_cols = col_names.clone();
1374        for (_, sub) in &panels {
1375            for name in sub.column_names() {
1376                if !all_cols.iter().any(|c| c == name) {
1377                    all_cols.push(name.to_string());
1378                }
1379            }
1380        }
1381        for name in &all_cols {
1382            let mut full = vec![crate::data::Value::Na; n];
1383            for (indices, sub) in &panels {
1384                if let Some(col) = sub.column(name) {
1385                    for (j, &i) in indices.iter().enumerate() {
1386                        full[i] = col[j].clone();
1387                    }
1388                }
1389            }
1390            data.add_column(name.clone(), full);
1391        }
1392    }
1393
1394    /// Detect which columns to group by for statistics.
1395    /// Checks group/color/fill plus discrete x (like R's auto-grouping by discrete x).
1396    fn detect_group_columns(data: &DataFrame) -> Vec<String> {
1397        detect_group_columns(data)
1398    }
1399}
1400
1401/// The columns whose discrete values split a layer's rows into aesthetic
1402/// groups (`group`, `color`, `fill`, a discrete `x`). Also used by panelwise
1403/// stats that regroup inside a panel ([`crate::stat::align::StatAlign`]).
1404pub(crate) fn detect_group_columns(data: &DataFrame) -> Vec<String> {
1405    let candidates = ["group", "color", "fill", "x"];
1406    let mut group_cols = Vec::new();
1407    for &col in &candidates {
1408        if data.has_column(col) {
1409            if let Some(values) = data.column(col) {
1410                let is_discrete = values
1411                    .iter()
1412                    .any(|v| matches!(v, crate::data::Value::Str(_)));
1413                if is_discrete {
1414                    group_cols.push(col.to_string());
1415                }
1416            }
1417        }
1418    }
1419    group_cols
1420}