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