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