Skip to main content

ggplot_rs/
plot.rs

1#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2use plotters::prelude::IntoDrawingArea;
3
4use crate::aes::Aes;
5use crate::annotate::Annotation;
6use crate::build::PlotBuilder;
7use crate::coord::cartesian::CoordCartesian;
8use crate::coord::fixed::CoordFixed;
9use crate::coord::flip::CoordFlip;
10use crate::coord::polar::CoordPolar;
11use crate::coord::Coord;
12use crate::data::{DataFrame, GGData, Value};
13use crate::facet::{Facet, FacetLabeller, FacetScales, FacetSpace};
14use crate::geom::area::GeomArea;
15use crate::geom::bar::GeomBar;
16use crate::geom::bin2d::GeomBin2d;
17use crate::geom::blank::GeomBlank;
18use crate::geom::boxplot::GeomBoxplot;
19use crate::geom::col::GeomCol;
20use crate::geom::contour::GeomContour;
21use crate::geom::count::GeomCount;
22use crate::geom::crossbar::GeomCrossbar;
23use crate::geom::curve::GeomCurve;
24use crate::geom::density::GeomDensity;
25use crate::geom::density2d::GeomDensity2d;
26use crate::geom::density_ridges::GeomDensityRidges;
27use crate::geom::dotplot::GeomDotplot;
28use crate::geom::errorbar::GeomErrorbar;
29use crate::geom::freqpoly::GeomFreqpoly;
30use crate::geom::hex::GeomHex;
31use crate::geom::histogram::GeomHistogram;
32use crate::geom::jitter::GeomJitter;
33use crate::geom::line::GeomLine;
34use crate::geom::linerange::GeomLinerange;
35use crate::geom::path::GeomPath;
36use crate::geom::point::GeomPoint;
37use crate::geom::pointrange::GeomPointrange;
38use crate::geom::polygon::GeomPolygon;
39use crate::geom::qq::{GeomQQ, GeomQQLine};
40use crate::geom::rect::GeomRect;
41use crate::geom::refline::{GeomAbline, GeomHline, GeomVline};
42use crate::geom::ribbon::GeomRibbon;
43use crate::geom::rug::GeomRug;
44use crate::geom::segment::GeomSegment;
45use crate::geom::smooth::GeomSmooth;
46use crate::geom::spoke::GeomSpoke;
47use crate::geom::step::GeomStep;
48use crate::geom::text::{GeomLabel, GeomText};
49use crate::geom::tile::GeomTile;
50use crate::geom::violin::GeomViolin;
51use crate::geom::{Geom, GeomParams};
52use crate::position::Position;
53use crate::render::layout::PlotLayout;
54#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
55use crate::render::plotters_backend::PlottersAdapter;
56use crate::render::renderer::PlotRenderer;
57use crate::render::RenderError;
58use crate::scale::continuous::ScaleContinuous;
59use crate::scale::transform::ScaleTransform;
60use crate::scale::Scale;
61use crate::stat::Stat;
62use crate::theme::Theme;
63
64// Builder methods for the 0.17 statistical-graphics layers (QQ, step ribbons,
65// ECDF bands, Cook's contours, horizontal error bars).
66mod stat_layers;
67
68/// Labels for the plot.
69#[derive(Clone, Debug, Default)]
70pub struct Labels {
71    pub title: Option<String>,
72    pub subtitle: Option<String>,
73    pub x: Option<String>,
74    pub y: Option<String>,
75    pub caption: Option<String>,
76    /// Corner tag (R's `labs(tag = ...)`), e.g. "A" for figure panels.
77    pub tag: Option<String>,
78}
79
80/// A single layer in the plot.
81pub struct Layer {
82    pub data: Option<DataFrame>,
83    pub mapping: Aes,
84    pub geom: Box<dyn Geom>,
85    pub stat: Box<dyn Stat>,
86    pub position: Box<dyn Position>,
87    pub params: GeomParams,
88    pub show_legend: Option<bool>,
89    /// The geom was configured explicitly (`geom_*_with(...)`), so its colours
90    /// are deliberate and the theme's `primary_color` must not override them.
91    pub explicit_style: bool,
92    /// A `{column}` tooltip template ([`GGPlot::tooltip`]), rendered per row
93    /// from the *built* layer data (post-stat) once that's available.
94    pub tooltip_template: Option<String>,
95    /// Legend key override ([`GGPlot::key_glyph`]); `None` = the geom's.
96    pub key_glyph: Option<crate::guide::key::KeyGlyph>,
97    /// Per-aesthetic `show.legend` ([`GGPlot::show_legend_for`]).
98    pub show_legend_aes: Vec<(crate::aes::Aesthetic, bool)>,
99}
100
101/// The top-level plot specification — builder pattern.
102pub struct GGPlot {
103    pub(crate) data: DataFrame,
104    pub(crate) mapping: Aes,
105    pub(crate) layers: Vec<Layer>,
106    pub(crate) scales: Vec<Box<dyn Scale>>,
107    pub(crate) coord: Box<dyn Coord>,
108    pub(crate) theme: Theme,
109    pub(crate) labels: Labels,
110    pub(crate) facet: Facet,
111    /// Which facet panels get axes (#412).
112    pub(crate) facet_axes: crate::facet::FacetAxes,
113    pub(crate) annotations: Vec<Annotation>,
114    pub(crate) guide_legend: crate::guide::config::GuideLegend,
115    /// Warnings raised while specifying the plot (e.g. a clipped calendar
116    /// span); prepended to the build warnings.
117    pub(crate) warnings: Vec<String>,
118    /// [`GGPlot::legend_bottom_when_narrow`]'s share, if set (#287).
119    pub(crate) legend_bottom_share: Option<f64>,
120    /// Clip the data layers to the panel (ggplot2's `coord_*(clip = "on")`,
121    /// the default; #411).
122    pub(crate) clip: bool,
123    /// Tag axes, grid, legend, strips and titles with semantic CSS classes
124    /// in SVG output (#465).
125    pub(crate) svg_classes: bool,
126    /// [`GGPlot::direct_labels`] (#543).
127    pub(crate) direct_labels: bool,
128    /// [`GGPlot::legend_inside_auto`]'s settings, if set (#332).
129    pub(crate) legend_auto: Option<LegendAuto>,
130    /// Panel aspect ratio used when the theme sets none (helpers such as
131    /// `geom_calendar` need square cells; survives theme presets).
132    pub(crate) default_aspect_ratio: Option<f64>,
133    /// Hide axes and grid whatever theme is set (layout-only charts such as
134    /// `geom_sankey`, whose x/y carry no data meaning); survives presets.
135    pub(crate) hide_position_guides: bool,
136    /// Hide only the y guides whatever theme is set (`geom_timeline`).
137    pub(crate) hide_y_guides: bool,
138    /// Plot-wide default locale for axis / legend labels ([`GGPlot::locale`]).
139    pub(crate) locale: Option<crate::locale::Locale>,
140    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/…
141    /// ([`svg_root_data`](Self::svg_root_data)). Default `true`; a consumer
142    /// overlaying a fragment on its own basemap (`render_svg_native_at`)
143    /// turns it off so the fragment adds no root attributes of its own.
144    pub(crate) svg_root_data: bool,
145    /// Extra root `<svg>` attributes requested via [`svg_attr`](Self::svg_attr)/
146    /// [`svg_attrs`](Self::svg_attrs), validated and applied at render time.
147    pub(crate) root_attrs: Vec<(String, String)>,
148    /// Whether to emit a `data-warnings` JSON array of the build warnings
149    /// on the root `<svg>` ([`svg_warnings_attr`](Self::svg_warnings_attr)).
150    /// Default off; byte-identical output when off.
151    pub(crate) svg_warnings_attr: bool,
152    /// Whether to emit `data-fvalue`/`data-fx` on marks
153    /// ([`svg_formatted_values`](Self::svg_formatted_values)). Default off;
154    /// byte-identical output when off.
155    pub(crate) svg_formatted_values: bool,
156    /// #221: validated [`layer_svg_attr`](Self::layer_svg_attr)s as
157    /// `(layer index, name, value)`, applied by wrapping that layer's geom
158    /// at build time.
159    pub(crate) layer_svg_attrs: Vec<(usize, String, String)>,
160    /// #255: accessible name for the rendered root `<svg>`
161    /// ([`svg_title`](Self::svg_title)) — a `<title>` first child plus
162    /// `role="img"`/`aria-labelledby`. Default `None`; byte-identical
163    /// output when not set.
164    pub(crate) svg_title: Option<String>,
165    /// #255: accessible description for the rendered root `<svg>`
166    /// ([`svg_desc`](Self::svg_desc)) — a `<desc>` first child plus
167    /// `role="img"`/`aria-describedby`. Default `None`; byte-identical
168    /// output when not set.
169    pub(crate) svg_desc: Option<String>,
170}
171
172impl GGPlot {
173    /// Create a new plot with the given data source.
174    ///
175    /// Never panics on malformed input: e.g. column-oriented data whose columns
176    /// have different lengths is padded with `NA` and reported as a
177    /// [`GGError::ValidationError`] by [`try_build`](Self::try_build) and the
178    /// `render_*`/`save*` methods.
179    /// One-call quick plot (ggplot2's `qplot()` / `quickplot()`): points for
180    /// `x` + `y`; with only `x`, a histogram (numeric) or bar chart (text).
181    pub fn qplot(data: impl GGData, x: &str, y: Option<&str>) -> Self {
182        let plot = GGPlot::new(data);
183        match y {
184            Some(y) => plot.aes(Aes::new().x(x).y(y)).geom_point(),
185            None => {
186                let text = plot
187                    .data
188                    .column(x)
189                    .and_then(|c| c.iter().find(|v| !v.is_na()))
190                    .is_some_and(|v| matches!(v, Value::Str(_) | Value::Bool(_)));
191                let plot = plot.aes(Aes::new().x(x));
192                if text {
193                    plot.geom_bar()
194                } else {
195                    plot.geom_histogram()
196                }
197            }
198        }
199    }
200
201    pub fn new(data: impl GGData) -> Self {
202        GGPlot {
203            data: data.into_dataframe(),
204            mapping: Aes::default(),
205            layers: Vec::new(),
206            scales: Vec::new(),
207            coord: Box::new(CoordCartesian::new()),
208            theme: Theme::default(),
209            labels: Labels::default(),
210            facet: Facet::default(),
211            facet_axes: crate::facet::FacetAxes::default(),
212            annotations: Vec::new(),
213            guide_legend: crate::guide::config::GuideLegend::default(),
214            warnings: Vec::new(),
215            legend_bottom_share: None,
216            clip: true,
217            svg_classes: false,
218            direct_labels: false,
219            legend_auto: None,
220            default_aspect_ratio: None,
221            hide_position_guides: false,
222            hide_y_guides: false,
223            locale: None,
224            svg_root_data: true,
225            root_attrs: Vec::new(),
226            svg_warnings_attr: false,
227            svg_formatted_values: false,
228            layer_svg_attrs: Vec::new(),
229            svg_title: None,
230            svg_desc: None,
231        }
232    }
233
234    /// Set the plot-level aesthetic mapping.
235    pub fn aes(mut self, mapping: Aes) -> Self {
236        self.warnings.extend(mapping.warnings.iter().cloned());
237        self.mapping = mapping;
238        self
239    }
240
241    // ─── Geom shortcuts ──────────────────────────────────────────
242
243    pub fn geom_point(self) -> Self {
244        self.add_geom(GeomPoint::default())
245    }
246
247    pub fn geom_point_with(self, geom: GeomPoint) -> Self {
248        self.add_geom_with(geom)
249    }
250
251    pub fn geom_line(self) -> Self {
252        self.add_geom(GeomLine::default())
253    }
254
255    pub fn geom_line_with(self, geom: GeomLine) -> Self {
256        self.add_geom_with(geom)
257    }
258
259    pub fn geom_bar(self) -> Self {
260        self.add_geom(GeomBar::default())
261    }
262
263    pub fn geom_bar_with(self, geom: GeomBar) -> Self {
264        self.add_geom_with(geom)
265    }
266
267    pub fn geom_histogram(self) -> Self {
268        self.add_geom(GeomHistogram::default())
269    }
270
271    pub fn geom_histogram_with(self, geom: GeomHistogram) -> Self {
272        self.add_geom_with(geom)
273    }
274
275    pub fn geom_boxplot(self) -> Self {
276        self.add_geom(GeomBoxplot::default())
277    }
278
279    pub fn geom_boxplot_with(self, geom: GeomBoxplot) -> Self {
280        self.add_geom_with(geom)
281    }
282
283    pub fn geom_smooth(self) -> Self {
284        self.add_geom(GeomSmooth::default())
285    }
286
287    pub fn geom_smooth_with(self, geom: GeomSmooth) -> Self {
288        self.add_geom_with(geom)
289    }
290
291    pub fn geom_col(self) -> Self {
292        self.add_geom(GeomCol::default())
293    }
294
295    pub fn geom_col_with(self, geom: GeomCol) -> Self {
296        self.add_geom_with(geom)
297    }
298
299    /// Horizontal reference line at a constant `yintercept`. Like ggplot2 the
300    /// intercept trains the y scale (the line is always visible) and the line
301    /// appears in every facet panel.
302    pub fn geom_hline(self, yintercept: f64) -> Self {
303        self.add_refline(
304            GeomHline::new(yintercept),
305            false,
306            &[("yintercept", yintercept)],
307        )
308    }
309
310    /// Add a horizontal reference line with custom styling (color/linetype/width).
311    pub fn geom_hline_with(self, geom: GeomHline) -> Self {
312        let y = geom.yintercept;
313        self.add_refline(geom, true, &[("yintercept", y)])
314    }
315
316    /// Data-mapped horizontal lines (ggplot2's `geom_hline(aes(yintercept =
317    /// …))`): one line per row of the layer data (the plot data unless
318    /// [`layer_data`](Self::layer_data) follows), per facet panel, styled by
319    /// any `color`/`linetype`/`alpha` in `mapping`. The plot-level mapping is
320    /// not inherited.
321    ///
322    /// ```
323    /// # use ggplot_rs::prelude::*;
324    /// let thresholds: Vec<(String, Vec<Value>)> = vec![
325    ///     ("bound".into(), vec![Value::Float(-0.2), Value::Float(0.2)]),
326    /// ];
327    /// let svg = GGPlot::new(vec![
328    ///         ("lag".to_string(), vec![Value::Float(1.0), Value::Float(2.0)]),
329    ///         ("acf".to_string(), vec![Value::Float(0.5), Value::Float(0.1)]),
330    ///     ])
331    ///     .aes(Aes::new().x("lag").y("acf"))
332    ///     .geom_col()
333    ///     .geom_hline_aes(Aes::new().yintercept("bound"))
334    ///     .layer_data(thresholds)
335    ///     .render_svg_native()
336    ///     .unwrap();
337    /// assert!(svg.contains("data-value=\"0.2\""));
338    /// ```
339    pub fn geom_hline_aes(self, mapping: Aes) -> Self {
340        self.add_geom(GeomHline::mapped()).layer_aes(mapping)
341    }
342
343    /// [`geom_hline_aes`](Self::geom_hline_aes) with custom default styling.
344    pub fn geom_hline_aes_with(self, geom: GeomHline, mapping: Aes) -> Self {
345        self.add_geom_with(geom).layer_aes(mapping)
346    }
347
348    /// Vertical reference line at a constant `xintercept` (trains the x
349    /// scale, appears in every panel).
350    pub fn geom_vline(self, xintercept: f64) -> Self {
351        self.add_refline(
352            GeomVline::new(xintercept),
353            false,
354            &[("xintercept", xintercept)],
355        )
356    }
357
358    /// Add a vertical reference line with custom styling (color/linetype/width).
359    pub fn geom_vline_with(self, geom: GeomVline) -> Self {
360        let x = geom.xintercept;
361        self.add_refline(geom, true, &[("xintercept", x)])
362    }
363
364    /// Data-mapped vertical lines (`aes(xintercept = …)`), one per row; see
365    /// [`geom_hline_aes`](Self::geom_hline_aes).
366    pub fn geom_vline_aes(self, mapping: Aes) -> Self {
367        self.add_geom(GeomVline::mapped()).layer_aes(mapping)
368    }
369
370    /// [`geom_vline_aes`](Self::geom_vline_aes) with custom default styling.
371    pub fn geom_vline_aes_with(self, geom: GeomVline, mapping: Aes) -> Self {
372        self.add_geom_with(geom).layer_aes(mapping)
373    }
374
375    /// Line `y = intercept + slope · x` in data space, clipped to the panel.
376    /// It does not train any scale (as in ggplot2).
377    pub fn geom_abline(self, slope: f64, intercept: f64) -> Self {
378        self.add_refline(
379            GeomAbline::new(slope, intercept),
380            false,
381            &[("slope", slope), ("intercept", intercept)],
382        )
383    }
384
385    /// Add a slope/intercept reference line with custom styling.
386    pub fn geom_abline_with(self, geom: GeomAbline) -> Self {
387        let (b, a) = (geom.slope, geom.intercept);
388        self.add_refline(geom, true, &[("slope", b), ("intercept", a)])
389    }
390
391    /// Data-mapped ablines (`aes(slope = …, intercept = …)`), one per row; a
392    /// missing aesthetic defaults to slope 1 / intercept 0.
393    pub fn geom_abline_aes(self, mapping: Aes) -> Self {
394        self.add_geom(GeomAbline::mapped()).layer_aes(mapping)
395    }
396
397    /// [`geom_abline_aes`](Self::geom_abline_aes) with custom default styling.
398    pub fn geom_abline_aes_with(self, geom: GeomAbline, mapping: Aes) -> Self {
399        self.add_geom_with(geom).layer_aes(mapping)
400    }
401
402    /// A constant reference line as ggplot2 builds it: a one-row layer frame
403    /// holding the constants, mapped to their aesthetics.
404    fn add_refline(
405        self,
406        geom: impl Geom + 'static,
407        explicit: bool,
408        values: &[(&str, f64)],
409    ) -> Self {
410        let mut data = DataFrame::new();
411        let mut mapping = Aes::new();
412        for (col, v) in values {
413            data.add_column(col.to_string(), vec![Value::Float(*v)]);
414            mapping = match *col {
415                "xintercept" => mapping.xintercept(col),
416                "yintercept" => mapping.yintercept(col),
417                "slope" => mapping.slope(col),
418                _ => mapping.intercept(col),
419            };
420        }
421        let plot = if explicit {
422            self.add_geom_with(geom)
423        } else {
424            self.add_geom(geom)
425        };
426        plot.layer_aes(mapping).layer_data(data)
427    }
428
429    pub fn geom_text(self) -> Self {
430        self.add_geom(GeomText::default())
431    }
432
433    pub fn geom_text_with(self, geom: GeomText) -> Self {
434        self.add_geom_with(geom)
435    }
436
437    /// Annotate with a correlation coefficient + p-value (`ggpubr::stat_cor()`).
438    /// Adds a text layer whose statistic computes Pearson correlation via
439    /// anofox-statistics; use [`GGPlot::stat_cor_with`] to pick Spearman or set
440    /// the label position.
441    #[cfg(feature = "ggpubr")]
442    pub fn stat_cor(self) -> Self {
443        self.geom_text().stat(crate::stat::cor::StatCor::default())
444    }
445
446    /// [`GGPlot::stat_cor`] with an explicit [`StatCor`](crate::stat::cor::StatCor)
447    /// (method / label position).
448    #[cfg(feature = "ggpubr")]
449    pub fn stat_cor_with(self, stat: crate::stat::cor::StatCor) -> Self {
450        self.geom_text().stat(stat)
451    }
452
453    /// Annotate grouped data with a group-comparison p-value
454    /// (`ggpubr::stat_compare_means()`). Adds a text layer whose statistic
455    /// compares y across the discrete x groups (Wilcoxon for two groups,
456    /// Kruskal-Wallis for more) via anofox-statistics.
457    #[cfg(feature = "ggpubr")]
458    pub fn stat_compare_means(self) -> Self {
459        self.geom_text()
460            .stat(crate::stat::compare_means::StatCompareMeans::default())
461    }
462
463    /// [`GGPlot::stat_compare_means`] with an explicit
464    /// [`StatCompareMeans`](crate::stat::compare_means::StatCompareMeans).
465    #[cfg(feature = "ggpubr")]
466    pub fn stat_compare_means_with(
467        self,
468        stat: crate::stat::compare_means::StatCompareMeans,
469    ) -> Self {
470        self.geom_text().stat(stat)
471    }
472
473    /// Auto-draw pairwise significance brackets (`ggpubr::stat_compare_means`
474    /// with `comparisons`). For each `(group_a, group_b)` pair it runs a
475    /// two-sample test (Wilcoxon by default) on the plot's y-values, formats the
476    /// p-value, and stacks a labelled [`geom_bracket`](GGPlot::geom_bracket)
477    /// above the data. Uses the plot's x/y mapping and data.
478    #[cfg(feature = "ggpubr")]
479    pub fn stat_compare_means_pairwise(self, comparisons: &[(&str, &str)]) -> Self {
480        self.stat_compare_means_pairwise_with(
481            crate::stat::compare_means::CompareMethod::Auto,
482            comparisons,
483        )
484    }
485
486    /// [`stat_compare_means_pairwise`](GGPlot::stat_compare_means_pairwise) with
487    /// an explicit test method.
488    #[cfg(feature = "ggpubr")]
489    pub fn stat_compare_means_pairwise_with(
490        self,
491        method: crate::stat::compare_means::CompareMethod,
492        comparisons: &[(&str, &str)],
493    ) -> Self {
494        // Resolve the x/y source columns from the plot mapping + data.
495        let col_for = |a: crate::aes::Aesthetic| {
496            self.mapping
497                .mappings
498                .iter()
499                .find(|m| m.aesthetic == a)
500                .map(|m| m.column.clone())
501        };
502        let (xcol, ycol) = match (
503            col_for(crate::aes::Aesthetic::X),
504            col_for(crate::aes::Aesthetic::Y),
505        ) {
506            (Some(x), Some(y)) => (x, y),
507            _ => return self,
508        };
509        let (xc, yc) = match (self.data.column(&xcol), self.data.column(&ycol)) {
510            (Some(x), Some(y)) => (x, y),
511            _ => return self,
512        };
513
514        // Bucket y by x category (first-seen order) and find the data range.
515        let mut groups: Vec<(String, Vec<f64>)> = Vec::new();
516        let mut ymax = f64::NEG_INFINITY;
517        let mut ymin = f64::INFINITY;
518        for (xv, yv) in xc.iter().zip(yc.iter()) {
519            let y = match yv.as_f64() {
520                Some(y) if y.is_finite() => y,
521                _ => continue,
522            };
523            ymax = ymax.max(y);
524            ymin = ymin.min(y);
525            let key = xv.to_group_key();
526            if let Some(g) = groups.iter_mut().find(|(k, _)| *k == key) {
527                g.1.push(y);
528            } else {
529                groups.push((key, vec![y]));
530            }
531        }
532        if groups.len() < 2 {
533            return self;
534        }
535        let step = if ymax > ymin {
536            (ymax - ymin) * 0.12
537        } else {
538            1.0
539        };
540
541        // One stacked bracket per resolvable comparison.
542        let (mut xmin_v, mut xmax_v, mut y_v, mut label_v) =
543            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
544        let mut placed = 0usize;
545        for (a, b) in comparisons {
546            let ga = groups.iter().find(|(k, _)| k == a).map(|g| &g.1);
547            let gb = groups.iter().find(|(k, _)| k == b).map(|g| &g.1);
548            let (ga, gb) = match (ga, gb) {
549                (Some(x), Some(y)) if x.len() >= 2 && y.len() >= 2 => (x, y),
550                _ => continue,
551            };
552            let p = match crate::stat::compare_means::pairwise_p(method, ga, gb) {
553                Some(p) => p,
554                None => continue,
555            };
556            xmin_v.push(Value::Str((*a).to_string()));
557            xmax_v.push(Value::Str((*b).to_string()));
558            y_v.push(Value::Float(ymax + step * (placed as f64 + 1.0)));
559            label_v.push(Value::Str(crate::stat::cor::format_p_value(p)));
560            placed += 1;
561        }
562        if xmin_v.is_empty() {
563            return self;
564        }
565
566        let data = vec![
567            ("xmin".to_string(), xmin_v),
568            ("xmax".to_string(), xmax_v),
569            ("y".to_string(), y_v),
570            ("label".to_string(), label_v),
571        ];
572        self.add_geom(crate::geom::bracket::GeomBracket::default())
573            .layer_data(data)
574            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
575    }
576
577    /// Draw a significance bracket over the plot (`ggpubr::geom_bracket`): a bar
578    /// spanning the categorical positions `xmin`..`xmax` at height `y`, captioned
579    /// with `label` (e.g. a p-value or significance stars). Pairs with a boxplot
580    /// and [`stat_compare_means`](GGPlot::stat_compare_means).
581    pub fn geom_bracket(self, xmin: &str, xmax: &str, y: f64, label: &str) -> Self {
582        self.geom_bracket_many(
583            crate::geom::bracket::GeomBracket::default(),
584            &[(xmin, xmax, y, label)],
585        )
586    }
587
588    /// Draw several significance brackets at once with a configured
589    /// [`GeomBracket`](crate::geom::bracket::GeomBracket). Each tuple is
590    /// `(xmin, xmax, y, label)`.
591    pub fn geom_bracket_many(
592        self,
593        geom: crate::geom::bracket::GeomBracket,
594        brackets: &[(&str, &str, f64, &str)],
595    ) -> Self {
596        let xmin = brackets
597            .iter()
598            .map(|b| Value::Str(b.0.to_string()))
599            .collect::<Vec<_>>();
600        let xmax = brackets
601            .iter()
602            .map(|b| Value::Str(b.1.to_string()))
603            .collect::<Vec<_>>();
604        let y = brackets
605            .iter()
606            .map(|b| Value::Float(b.2))
607            .collect::<Vec<_>>();
608        let label = brackets
609            .iter()
610            .map(|b| Value::Str(b.3.to_string()))
611            .collect::<Vec<_>>();
612        let data = vec![
613            ("xmin".to_string(), xmin),
614            ("xmax".to_string(), xmax),
615            ("y".to_string(), y),
616            ("label".to_string(), label),
617        ];
618        self.add_geom(geom)
619            .layer_data(data)
620            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
621    }
622
623    /// Significance brackets from a precomputed test table (ggpubr's
624    /// `stat_pvalue_manual` / `geom_bracket(data = …)`) — e.g. the anofox
625    /// `test` contract output (`group1`, `group2`, `p_adj`/`p_value`, optional
626    /// `y_position`, `label`). No test is recomputed. See
627    /// [`BracketTable`](crate::geom::bracket::BracketTable) for the column
628    /// rules, label templates (`"p = {p_adj}"`, `"{p.signif}"`) and the
629    /// automatic stacking of rows without a `y_position`. Rows that cannot be
630    /// drawn are dropped with a build warning.
631    pub fn geom_bracket_table(
632        mut self,
633        table: impl GGData,
634        spec: crate::geom::bracket::BracketTable,
635    ) -> Self {
636        let table = table.into_dataframe();
637        let col_for = |a: crate::aes::Aesthetic| {
638            self.mapping
639                .mappings
640                .iter()
641                .find(|m| m.aesthetic == a)
642                .map(|m| m.column.clone())
643        };
644        // The plot's x categories (to reject unknown groups) and finite y
645        // range (to stack brackets above the data).
646        let x_levels: Vec<String> = col_for(crate::aes::Aesthetic::X)
647            .and_then(|c| self.data.column(&c))
648            .filter(|col| col.iter().any(|v| matches!(v, Value::Str(_))))
649            .map(|col| {
650                let mut seen = std::collections::HashSet::new();
651                col.iter()
652                    .filter(|v| !v.is_na())
653                    .map(|v| v.to_group_key())
654                    .filter(|k| seen.insert(k.clone()))
655                    .collect()
656            })
657            .unwrap_or_default();
658        let y_range = col_for(crate::aes::Aesthetic::Y)
659            .and_then(|c| self.data.column(&c))
660            .and_then(|col| {
661                let (lo, hi) = col
662                    .iter()
663                    .filter_map(|v| v.as_f64())
664                    .filter(|v| v.is_finite())
665                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
666                        (lo.min(v), hi.max(v))
667                    });
668                (lo <= hi).then_some((lo, hi))
669            });
670        let mut warnings = Vec::new();
671        let resolved = spec.resolve(&table, &x_levels, y_range, &mut warnings);
672        self.warnings.extend(warnings);
673        match resolved {
674            Some(data) => self
675                .add_geom(crate::geom::bracket::GeomBracket::from(spec.geom))
676                .layer_data(data)
677                .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label")),
678            None => self,
679        }
680    }
681
682    /// Text labels that repel each other and their points
683    /// (`ggrepel::geom_text_repel`) — deterministic (seeded) layout; see
684    /// [`GeomTextRepel`](crate::geom::repel::GeomTextRepel). Requires `x`,
685    /// `y` and `label`.
686    pub fn geom_text_repel(self) -> Self {
687        self.add_geom(crate::geom::repel::GeomTextRepel::default())
688    }
689
690    /// [`geom_text_repel`](Self::geom_text_repel) with a configured geom
691    /// (padding, nudge, `max_overlaps`, seed, …).
692    pub fn geom_text_repel_with(self, geom: crate::geom::repel::GeomTextRepel) -> Self {
693        self.add_geom_with(geom)
694    }
695
696    /// Boxed labels that repel each other and their points
697    /// (`ggrepel::geom_label_repel`).
698    pub fn geom_label_repel(self) -> Self {
699        self.add_geom(crate::geom::repel::GeomLabelRepel::default())
700    }
701
702    /// [`geom_label_repel`](Self::geom_label_repel) with a configured geom.
703    pub fn geom_label_repel_with(self, geom: crate::geom::repel::GeomLabelRepel) -> Self {
704        self.add_geom_with(geom)
705    }
706
707    pub fn geom_label(self) -> Self {
708        self.add_geom(GeomLabel::default())
709    }
710
711    pub fn geom_label_with(self, geom: GeomLabel) -> Self {
712        self.add_geom_with(geom)
713    }
714
715    pub fn geom_area(self) -> Self {
716        self.add_geom(GeomArea::default())
717    }
718
719    pub fn geom_area_with(self, geom: GeomArea) -> Self {
720        self.add_geom_with(geom)
721    }
722
723    pub fn geom_ribbon(self) -> Self {
724        self.add_geom(GeomRibbon::default())
725    }
726
727    pub fn geom_ribbon_with(self, geom: GeomRibbon) -> Self {
728        self.add_geom_with(geom)
729    }
730
731    pub fn geom_errorbar(self) -> Self {
732        self.add_geom(GeomErrorbar::default())
733    }
734
735    pub fn geom_errorbar_with(self, geom: GeomErrorbar) -> Self {
736        self.add_geom_with(geom)
737    }
738
739    pub fn geom_segment(self) -> Self {
740        self.add_geom(GeomSegment::default())
741    }
742
743    pub fn geom_segment_with(self, geom: GeomSegment) -> Self {
744        self.add_geom_with(geom)
745    }
746
747    pub fn geom_density(self) -> Self {
748        self.add_geom(GeomDensity::default())
749    }
750
751    pub fn geom_density_with(self, geom: GeomDensity) -> Self {
752        self.add_geom_with(geom)
753    }
754
755    pub fn geom_rug(self) -> Self {
756        self.add_geom(GeomRug::default())
757    }
758
759    pub fn geom_rug_with(self, geom: GeomRug) -> Self {
760        self.add_geom_with(geom)
761    }
762
763    pub fn geom_jitter(self) -> Self {
764        self.add_geom(GeomJitter::default())
765    }
766
767    pub fn geom_jitter_with(self, geom: GeomJitter) -> Self {
768        self.add_geom_with(geom)
769    }
770
771    pub fn geom_path(self) -> Self {
772        self.add_geom(GeomPath::default())
773    }
774
775    pub fn geom_path_with(self, geom: GeomPath) -> Self {
776        self.add_geom_with(geom)
777    }
778
779    /// Plot `fun(x)` as a line over the plot data's x range (ggplot2's
780    /// `geom_function()`); see [`geom_function_xlim`](Self::geom_function_xlim)
781    /// to plot without data.
782    pub fn geom_function(self, fun: impl Fn(f64) -> f64 + Send + Sync + 'static) -> Self {
783        self.geom_line()
784            .stat(crate::stat::function::StatFunction::new(fun))
785    }
786
787    /// Plot `fun(x)` over `[lo, hi]` without any data (`geom_function(xlim =)`).
788    pub fn geom_function_xlim(
789        self,
790        fun: impl Fn(f64) -> f64 + Send + Sync + 'static,
791        lo: f64,
792        hi: f64,
793    ) -> Self {
794        let range = vec![("x".to_string(), vec![Value::Float(lo), Value::Float(hi)])];
795        self.geom_line()
796            .layer_data(range)
797            .layer_aes(Aes::new().x("x"))
798            .stat(crate::stat::function::StatFunction::new(fun).with_xlim(lo, hi))
799    }
800
801    /// Join each group's points (in x order) with steps or straight lines
802    /// (ggplot2 4.0's `stat_connect(connection)`), drawn as a path.
803    pub fn stat_connect(self, connection: crate::stat::connect::Connection) -> Self {
804        self.geom_path()
805            .stat(crate::stat::connect::StatConnect::new(connection))
806    }
807
808    /// Points with duplicate rows dropped (`stat_unique()`); `.stat(StatUnique)`
809    /// applies it to any other layer.
810    pub fn stat_unique(self) -> Self {
811        self.geom_point().stat(crate::stat::unique::StatUnique)
812    }
813
814    /// Points from an arbitrary per-group transform (ggplot2 4.0's
815    /// `stat_manual(fun)`); `.stat(StatManual::new(f))` for other geoms.
816    pub fn stat_manual(
817        self,
818        fun: impl Fn(&crate::data::DataFrame) -> crate::data::DataFrame + Send + Sync + 'static,
819    ) -> Self {
820        self.geom_point()
821            .stat(crate::stat::manual::StatManual::new(fun))
822    }
823
824    /// Hexagons filled with a summary of the raw `z` column
825    /// (`stat_summary_hex(fun)`).
826    pub fn stat_summary_hex(self, fun: crate::stat::summary::SummaryFun) -> Self {
827        self.geom_hex()
828            .stat(crate::stat::binhex::StatSummaryHex::new(fun))
829    }
830
831    /// A point per WKT `geometry` (feature `sf`; `stat_sf_coordinates()`).
832    /// Use `.stat(StatSfCoordinates::default())` to put text, labels or any
833    /// other geom on a map.
834    #[cfg(feature = "sf")]
835    pub fn stat_sf_coordinates(self) -> Self {
836        self.geom_point()
837            .stat(crate::stat::sf_coordinates::StatSfCoordinates::default())
838    }
839
840    /// Add a confidence-ellipse layer (default 95%) as a path per group.
841    pub fn stat_ellipse(self) -> Self {
842        self.geom_path()
843            .stat(crate::stat::ellipse::StatEllipse::default())
844    }
845
846    /// Add a confidence-ellipse layer at the given level (0, 1).
847    pub fn stat_ellipse_level(self, level: f64) -> Self {
848        self.geom_path()
849            .stat(crate::stat::ellipse::StatEllipse::new(level))
850    }
851
852    /// Add a quantile-regression line for each `tau` as a separate path layer
853    /// (R's `stat_quantile`). Backed by anofox-regression (feature `regression`).
854    #[cfg(feature = "regression")]
855    pub fn stat_quantile(mut self, taus: &[f64]) -> Self {
856        for &tau in taus {
857            self = self
858                .geom_path()
859                .stat(crate::stat::quantile::StatQuantile::new(tau));
860        }
861        self
862    }
863
864    /// Quantile-regression lines at the quartiles (0.25, 0.5, 0.75).
865    #[cfg(feature = "regression")]
866    pub fn geom_quantile(self) -> Self {
867        self.stat_quantile(&[0.25, 0.5, 0.75])
868    }
869
870    pub fn geom_step(self) -> Self {
871        self.add_geom(GeomStep::default())
872    }
873
874    pub fn geom_step_with(self, geom: GeomStep) -> Self {
875        self.add_geom_with(geom)
876    }
877
878    pub fn geom_freqpoly(self) -> Self {
879        self.add_geom(GeomFreqpoly::default())
880    }
881
882    pub fn geom_freqpoly_with(self, geom: GeomFreqpoly) -> Self {
883        self.add_geom_with(geom)
884    }
885
886    pub fn geom_linerange(self) -> Self {
887        self.add_geom(GeomLinerange::default())
888    }
889
890    pub fn geom_linerange_with(self, geom: GeomLinerange) -> Self {
891        self.add_geom_with(geom)
892    }
893
894    pub fn geom_pointrange(self) -> Self {
895        self.add_geom(GeomPointrange::default())
896    }
897
898    pub fn geom_pointrange_with(self, geom: GeomPointrange) -> Self {
899        self.add_geom_with(geom)
900    }
901
902    pub fn geom_crossbar(self) -> Self {
903        self.add_geom(GeomCrossbar::default())
904    }
905
906    pub fn geom_crossbar_with(self, geom: GeomCrossbar) -> Self {
907        self.add_geom_with(geom)
908    }
909
910    pub fn geom_spoke(self) -> Self {
911        self.add_geom(GeomSpoke::default())
912    }
913
914    pub fn geom_spoke_with(self, geom: GeomSpoke) -> Self {
915        self.add_geom_with(geom)
916    }
917
918    pub fn geom_rect(self) -> Self {
919        self.add_geom(GeomRect::default())
920    }
921
922    pub fn geom_rect_with(self, geom: GeomRect) -> Self {
923        self.add_geom_with(geom)
924    }
925
926    pub fn geom_tile(self) -> Self {
927        self.add_geom(GeomTile::default())
928    }
929
930    pub fn geom_tile_with(self, geom: GeomTile) -> Self {
931        self.add_geom_with(geom)
932    }
933
934    /// Dense regular grid of filled cells (heatmap/raster) from x, y, fill.
935    pub fn geom_raster(self) -> Self {
936        self.add_geom(crate::geom::raster::GeomRaster::default())
937    }
938
939    pub fn geom_raster_with(self, geom: crate::geom::raster::GeomRaster) -> Self {
940        self.add_geom_with(geom)
941    }
942
943    pub fn geom_polygon(self) -> Self {
944        self.add_geom(GeomPolygon::default())
945    }
946
947    pub fn geom_polygon_with(self, geom: GeomPolygon) -> Self {
948        self.add_geom_with(geom)
949    }
950
951    /// Render simple-features geometry from a WKT `geometry` column (feature `sf`).
952    #[cfg(feature = "sf")]
953    pub fn geom_sf(self) -> Self {
954        self.add_geom(crate::geom::sf::GeomSf::default())
955    }
956
957    #[cfg(feature = "sf")]
958    pub fn geom_sf_with(self, geom: crate::geom::sf::GeomSf) -> Self {
959        self.add_geom_with(geom)
960    }
961
962    /// Labels placed inside `geom_sf` polygons (feature `sf`): `label`
963    /// aesthetic, `geometry` column — ggplot2's `geom_sf_text`.
964    #[cfg(feature = "sf")]
965    pub fn geom_sf_text(self) -> Self {
966        self.add_geom(crate::geom::sf_text::GeomSfText::default())
967    }
968
969    #[cfg(feature = "sf")]
970    pub fn geom_sf_text_with(self, geom: crate::geom::sf_text::GeomSfText) -> Self {
971        self.add_geom_with(geom)
972    }
973
974    /// Like [`geom_sf_text`](Self::geom_sf_text), on a background box —
975    /// ggplot2's `geom_sf_label`.
976    #[cfg(feature = "sf")]
977    pub fn geom_sf_label(self) -> Self {
978        self.add_geom(crate::geom::sf_text::GeomSfLabel::default())
979    }
980
981    #[cfg(feature = "sf")]
982    pub fn geom_sf_label_with(self, geom: crate::geom::sf_text::GeomSfLabel) -> Self {
983        self.add_geom_with(geom)
984    }
985
986    /// A metric scale bar in a panel corner (feature `sf`) — ggspatial's
987    /// `annotation_scale()`. Assumes the X/Y domain is in metres (any
988    /// `geom_sf` projection other than `SfProjection::PlateCarree`).
989    #[cfg(feature = "sf")]
990    pub fn annotation_scale(self) -> Self {
991        self.add_geom(crate::geom::annotation_scale::GeomAnnotationScale::default())
992    }
993
994    #[cfg(feature = "sf")]
995    pub fn annotation_scale_with(
996        self,
997        geom: crate::geom::annotation_scale::GeomAnnotationScale,
998    ) -> Self {
999        self.add_geom_with(geom)
1000    }
1001
1002    /// A north arrow in a panel corner (feature `sf`) — see
1003    /// [`GeomNorthArrow`](crate::geom::annotation_scale::GeomNorthArrow).
1004    #[cfg(feature = "sf")]
1005    pub fn annotation_north_arrow_with(
1006        self,
1007        geom: crate::geom::annotation_scale::GeomNorthArrow,
1008    ) -> Self {
1009        self.add_geom_with(geom)
1010    }
1011
1012    /// A small, muted attribution text in a panel corner (feature `sf`) —
1013    /// e.g. `"© Natural Earth"`.
1014    #[cfg(feature = "sf")]
1015    pub fn annotation_attribution(self, text: impl Into<String>) -> Self {
1016        self.add_geom(crate::geom::annotation_scale::GeomAttribution::new(text))
1017    }
1018
1019    /// A raster basemap from an XYZ tile provider (feature `tiles`, #325),
1020    /// drawn under every other layer: tiles fetched through `fetcher` for
1021    /// the plot's Web-Mercator view (project `geom_sf` layers with
1022    /// `SfProjection::Mercator`, add `coord_sf()`), at a zoom picked from
1023    /// the panel size, plus the source's attribution in a corner. E.g.
1024    /// `annotation_map_tile(TileSource::xyz("https://tile.openstreetmap.org/{z}/{x}/{y}.png")
1025    /// .attribution("© OpenStreetMap contributors"), my_http_fetcher)`.
1026    #[cfg(feature = "tiles")]
1027    pub fn annotation_map_tile(
1028        self,
1029        source: crate::geom::map_tile::TileSource,
1030        fetcher: impl crate::geom::map_tile::TileFetcher + 'static,
1031    ) -> Self {
1032        self.annotation_map_tile_with(crate::geom::map_tile::GeomMapTile::new(source, fetcher))
1033    }
1034
1035    /// [`annotation_map_tile`](Self::annotation_map_tile) with a configured
1036    /// layer (fixed zoom, detail, opacity).
1037    #[cfg(feature = "tiles")]
1038    pub fn annotation_map_tile_with(self, geom: crate::geom::map_tile::GeomMapTile) -> Self {
1039        let attribution = geom.source.attribution.clone();
1040        let mut plot = self.add_geom_with(geom);
1041        // Under every other layer (per-layer settings shift up by one).
1042        if let Some(layer) = plot.layers.pop() {
1043            plot.layers.insert(0, layer);
1044            for (idx, ..) in plot.layer_svg_attrs.iter_mut() {
1045                *idx += 1;
1046            }
1047        }
1048        if attribution.is_empty() {
1049            plot
1050        } else {
1051            plot.annotation_attribution(attribution)
1052        }
1053    }
1054
1055    #[cfg(feature = "sf")]
1056    pub fn annotation_attribution_with(
1057        self,
1058        geom: crate::geom::annotation_scale::GeomAttribution,
1059    ) -> Self {
1060        self.add_geom_with(geom)
1061    }
1062
1063    /// The square `n × m` guide for a
1064    /// [`ScaleFillBivariate`](crate::scale::bivariate::ScaleFillBivariate)
1065    /// fill scale (feature `sf`): two axis captions, biscale's own legend
1066    /// shape — drawn as a furniture layer, not through the ordinary
1067    /// per-aesthetic legend (set `.legend_position(LegendPosition::None)`
1068    /// to hide that one). [`GeomBivariateLegend::from_scale`] builds this
1069    /// from the same scale used for the fill, so the swatches match.
1070    #[cfg(feature = "sf")]
1071    pub fn bivariate_legend(
1072        self,
1073        geom: crate::geom::bivariate_legend::GeomBivariateLegend,
1074    ) -> Self {
1075        self.add_geom(geom)
1076    }
1077
1078    /// Like [`Self::bivariate_legend`], but with each cell's row count
1079    /// drawn centred in its swatch — build with
1080    /// [`GeomBivariateLegend::counts`](crate::geom::bivariate_legend::GeomBivariateLegend::counts)
1081    /// (#259).
1082    #[cfg(feature = "sf")]
1083    pub fn bivariate_legend_counts(
1084        self,
1085        geom: crate::geom::bivariate_legend::GeomBivariateLegendCounts,
1086    ) -> Self {
1087        self.add_geom(geom)
1088    }
1089
1090    pub fn geom_curve(self) -> Self {
1091        self.add_geom(GeomCurve::default())
1092    }
1093
1094    pub fn geom_curve_with(self, geom: GeomCurve) -> Self {
1095        self.add_geom_with(geom)
1096    }
1097
1098    pub fn geom_violin(self) -> Self {
1099        self.add_geom(GeomViolin::default())
1100    }
1101
1102    pub fn geom_violin_with(self, geom: GeomViolin) -> Self {
1103        self.add_geom_with(geom)
1104    }
1105
1106    /// A ridgeline plot: one density of `x` per level of a discrete `y`,
1107    /// drawn upward from the level's baseline and overlapping the row above
1108    /// ([`GeomDensityRidges::scale`]) — distributions over time or groups.
1109    pub fn geom_density_ridges(self) -> Self {
1110        self.add_geom(GeomDensityRidges::default())
1111    }
1112
1113    pub fn geom_density_ridges_with(self, geom: GeomDensityRidges) -> Self {
1114        self.add_geom_with(geom)
1115    }
1116
1117    pub fn geom_dotplot(self) -> Self {
1118        self.add_geom(GeomDotplot::default())
1119    }
1120
1121    pub fn geom_dotplot_with(self, geom: GeomDotplot) -> Self {
1122        self.add_geom_with(geom)
1123    }
1124
1125    pub fn geom_qq(self) -> Self {
1126        self.add_geom(GeomQQ::default())
1127    }
1128
1129    pub fn geom_qq_with(self, geom: GeomQQ) -> Self {
1130        self.add_geom_with(geom)
1131    }
1132
1133    pub fn geom_qq_line(self) -> Self {
1134        self.add_geom(GeomQQLine::default())
1135    }
1136
1137    pub fn geom_qq_line_with(self, geom: GeomQQLine) -> Self {
1138        self.add_geom_with(geom)
1139    }
1140
1141    pub fn geom_bin2d(self) -> Self {
1142        self.add_geom(GeomBin2d::default())
1143    }
1144
1145    pub fn geom_bin2d_with(self, geom: GeomBin2d) -> Self {
1146        self.add_geom_with(geom)
1147    }
1148
1149    pub fn geom_hex(self) -> Self {
1150        self.add_geom(GeomHex::default())
1151    }
1152
1153    pub fn geom_hex_with(self, geom: GeomHex) -> Self {
1154        self.add_geom_with(geom)
1155    }
1156
1157    pub fn geom_count(self) -> Self {
1158        self.add_geom(GeomCount::default())
1159    }
1160
1161    pub fn geom_count_with(self, geom: GeomCount) -> Self {
1162        self.add_geom_with(geom)
1163    }
1164
1165    pub fn geom_contour(self) -> Self {
1166        self.add_geom(GeomContour::default())
1167    }
1168
1169    pub fn geom_contour_with(self, geom: GeomContour) -> Self {
1170        self.add_geom_with(geom)
1171    }
1172
1173    /// Filled contour bands from gridded (x, y, z) data — draws polygons filled by
1174    /// band level. Pair with a continuous fill scale (e.g. `scale_fill_viridis_c`).
1175    pub fn geom_contour_filled(self) -> Self {
1176        self.add_geom(GeomPolygon {
1177            line_width: 0.0,
1178            alpha: 1.0,
1179            ..GeomPolygon::default()
1180        })
1181        .stat(crate::stat::contour_filled::StatContourFilled::default())
1182    }
1183
1184    pub fn geom_density2d(self) -> Self {
1185        self.add_geom(GeomDensity2d::default())
1186    }
1187
1188    pub fn geom_density2d_with(self, geom: GeomDensity2d) -> Self {
1189        self.add_geom_with(geom)
1190    }
1191
1192    /// Waterfall (bridge) chart: map `x` (steps, in data order) and `y` (each
1193    /// step's change). Bars float from the running total and are filled by
1194    /// direction (Increase / Decrease / Total, with a legend); dashed
1195    /// connectors join consecutive bars. See [`geom_waterfall_with`](Self::geom_waterfall_with)
1196    /// for subtotals and a closing total.
1197    pub fn geom_waterfall(self) -> Self {
1198        self.default_styled(|p| {
1199            p.geom_waterfall_with(crate::geom::waterfall::GeomWaterfall::default())
1200        })
1201    }
1202
1203    /// [`geom_waterfall`](Self::geom_waterfall) with explicit colours,
1204    /// `totals` (subtotal x levels) and `final_total`. Unless `fill` is
1205    /// already mapped at plot level, the layer maps `after_stat(fill =
1206    /// direction)`; unless a fill scale is already set, a manual fill scale
1207    /// with the geom's `up`/`down`/`total` colours is added (a later
1208    /// `scale_fill_*` call replaces it).
1209    pub fn geom_waterfall_with(self, geom: crate::geom::waterfall::GeomWaterfall) -> Self {
1210        use crate::scale::color::RGBAColor;
1211        use crate::stat::waterfall::{WATERFALL_DECREASE, WATERFALL_INCREASE, WATERFALL_TOTAL};
1212        let rgba = |(r, g, b): (u8, u8, u8)| RGBAColor::new(r, g, b);
1213        let mut values = vec![
1214            (WATERFALL_INCREASE, rgba(geom.up)),
1215            (WATERFALL_DECREASE, rgba(geom.down)),
1216        ];
1217        if geom.has_totals() {
1218            values.push((WATERFALL_TOTAL, rgba(geom.total)));
1219        }
1220        let fill_mapped = self
1221            .mapping
1222            .get_mapping(&crate::aes::Aesthetic::Fill)
1223            .is_some();
1224        let has_fill_scale = self
1225            .scales
1226            .iter()
1227            .any(|s| s.aesthetic() == crate::aes::Aesthetic::Fill);
1228        let mut plot = self.add_geom_with(geom);
1229        if !fill_mapped {
1230            plot = plot.layer_aes(Aes::new().after_stat_fill("direction"));
1231            if !has_fill_scale {
1232                plot = plot.scale_fill_manual(values);
1233            }
1234        }
1235        plot
1236    }
1237
1238    /// Pareto chart: map `x` (categories) and `y` (values, summed per
1239    /// category). Bars are sorted descending and a cumulative line with
1240    /// points rises to the grand total, read against a 0–100 % right axis.
1241    pub fn geom_pareto(self) -> Self {
1242        self.add_pareto(crate::geom::pareto::GeomPareto::default(), false)
1243    }
1244
1245    /// [`geom_pareto`](Self::geom_pareto) with explicit styling, sorting or a
1246    /// threshold line. Unless a y scale is already set, a continuous y scale
1247    /// with a [`SecAxis::percent_of_max`](crate::scale::sec_axis::SecAxis::percent_of_max)
1248    /// secondary axis ("Cumulative %") is added; a later `scale_y_continuous`
1249    /// replaces it.
1250    pub fn geom_pareto_with(self, geom: crate::geom::pareto::GeomPareto) -> Self {
1251        self.add_pareto(geom, true)
1252    }
1253
1254    fn add_pareto(self, geom: crate::geom::pareto::GeomPareto, explicit: bool) -> Self {
1255        let has_y_scale = self
1256            .scales
1257            .iter()
1258            .any(|s| s.aesthetic() == crate::aes::Aesthetic::Y);
1259        let plot = if explicit {
1260            self.add_geom_with(geom)
1261        } else {
1262            self.add_geom(geom)
1263        };
1264        if has_y_scale {
1265            plot
1266        } else {
1267            plot.scale_y_continuous(ScaleContinuous::new().with_sec_axis(
1268                crate::scale::sec_axis::SecAxis::percent_of_max().with_name("Cumulative %"),
1269            ))
1270        }
1271    }
1272
1273    /// Sankey diagram from an edge list: map `from`, `to` and optionally
1274    /// `weight` (`Aes::new().from("src").to("dst").weight("flow")`). Nodes
1275    /// are placed in columns by their depth, sized by their flow and
1276    /// coloured by name through the fill scale (no legend — nodes are
1277    /// labelled); links take their source's colour. Axes and grid are
1278    /// hidden, whatever the theme.
1279    pub fn geom_sankey(self) -> Self {
1280        self.add_sankey(crate::geom::sankey::GeomSankey::default(), false)
1281    }
1282
1283    /// [`geom_sankey`](Self::geom_sankey) with explicit layout and styling.
1284    pub fn geom_sankey_with(self, geom: crate::geom::sankey::GeomSankey) -> Self {
1285        self.add_sankey(geom, true)
1286    }
1287
1288    fn add_sankey(self, geom: crate::geom::sankey::GeomSankey, explicit: bool) -> Self {
1289        let mut plot = if explicit {
1290            self.add_geom_with(geom)
1291        } else {
1292            self.add_geom(geom)
1293        };
1294        plot.hide_position_guides = true;
1295        plot.layer_aes(Aes::new().after_stat_fill("node"))
1296            .show_legend(false)
1297    }
1298
1299    /// Chord diagram / dependency wheel from an edge list: map `from`, `to`
1300    /// and optionally `weight`. Each node is an arc sized by its total flow
1301    /// (in + out); each link a ribbon through the centre, coloured by its
1302    /// source. Nodes are coloured by name through the fill scale (no legend
1303    /// — they are labelled); axes and grid are hidden and the panel is kept
1304    /// square so the circle stays round.
1305    pub fn geom_chord(self) -> Self {
1306        self.add_chord(crate::geom::chord::GeomChord::default(), false)
1307    }
1308
1309    /// [`geom_chord`](Self::geom_chord) with explicit padding and styling.
1310    pub fn geom_chord_with(self, geom: crate::geom::chord::GeomChord) -> Self {
1311        self.add_chord(geom, true)
1312    }
1313
1314    fn add_chord(self, geom: crate::geom::chord::GeomChord, explicit: bool) -> Self {
1315        let (ex, ey) = geom.extents();
1316        let mut plot = if explicit {
1317            self.add_geom_with(geom)
1318        } else {
1319            self.add_geom(geom)
1320        };
1321        plot.hide_position_guides = true;
1322        plot.default_aspect_ratio = Some(ey / ex);
1323        plot.layer_aes(Aes::new().after_stat_fill("node"))
1324            .show_legend(false)
1325    }
1326
1327    /// Arc diagram from an edge list: map `from`, `to` and optionally
1328    /// `weight`. Nodes sit on a line (sized by total flow), links are arcs
1329    /// whose width is their weight. Coloured by node name through the fill
1330    /// scale (no legend — nodes are labelled); axes and grid are hidden.
1331    pub fn geom_arcdiagram(self) -> Self {
1332        self.add_arcdiagram(crate::geom::arcdiagram::GeomArcdiagram::default(), false)
1333    }
1334
1335    /// [`geom_arcdiagram`](Self::geom_arcdiagram) with explicit ordering,
1336    /// direction and styling.
1337    pub fn geom_arcdiagram_with(self, geom: crate::geom::arcdiagram::GeomArcdiagram) -> Self {
1338        self.add_arcdiagram(geom, true)
1339    }
1340
1341    fn add_arcdiagram(self, geom: crate::geom::arcdiagram::GeomArcdiagram, explicit: bool) -> Self {
1342        let mut plot = if explicit {
1343            self.add_geom_with(geom)
1344        } else {
1345            self.add_geom(geom)
1346        };
1347        plot.hide_position_guides = true;
1348        plot.layer_aes(Aes::new().after_stat_fill("node"))
1349            .show_legend(false)
1350    }
1351
1352    /// Squarified treemap: map `weight` (tile area) and optionally
1353    /// `subgroup` (tiles nest inside group rectangles), `fill` and `label`
1354    /// (`Aes::new().weight("sales").subgroup("region").label("country")`).
1355    /// When `subgroup` is mapped at plot level and `fill` is not, tiles are
1356    /// filled by subgroup. The panel aspect matches the layout so tiles come
1357    /// out square; the position scales get no expansion and the axes and
1358    /// grid are hidden.
1359    pub fn geom_treemap(self) -> Self {
1360        self.add_treemap(crate::geom::treemap::GeomTreemap::default(), false)
1361    }
1362
1363    /// [`geom_treemap`](Self::geom_treemap) with explicit layout and styling.
1364    pub fn geom_treemap_with(self, geom: crate::geom::treemap::GeomTreemap) -> Self {
1365        self.add_treemap(geom, true)
1366    }
1367
1368    fn add_treemap(self, geom: crate::geom::treemap::GeomTreemap, explicit: bool) -> Self {
1369        use crate::aes::Aesthetic;
1370        let aspect = geom.aspect;
1371        let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
1372        let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
1373        let fill_by = match (
1374            self.mapping.get_mapping(&Aesthetic::Fill),
1375            self.mapping.get_mapping(&Aesthetic::Subgroup),
1376        ) {
1377            (None, Some(sub)) => Some(sub.to_string()),
1378            _ => None,
1379        };
1380        let mut plot = if explicit {
1381            self.add_geom_with(geom)
1382        } else {
1383            self.add_geom(geom)
1384        };
1385        plot.hide_position_guides = true;
1386        plot.default_aspect_ratio = Some(1.0 / aspect.max(1e-6));
1387        if let Some(sub) = fill_by {
1388            plot = plot.layer_aes(Aes::new().fill(&sub));
1389        }
1390        if !has_x {
1391            plot = plot.scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1392        }
1393        if !has_y {
1394            plot = plot.scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1395        }
1396        plot
1397    }
1398
1399    /// Sunburst over the hierarchy columns `levels` (outermost first),
1400    /// sized by `weight` (1 per row when unmapped): concentric rings, one per
1401    /// level, each node's angle ∝ its value and nested in its parent's.
1402    /// Sets `coord_polar`, colours each branch by its top-level ancestor
1403    /// (lighter further out; no legend — sectors are labelled), drops scale
1404    /// expansion and hides the position guides.
1405    pub fn geom_sunburst<S: Into<String>>(self, levels: impl IntoIterator<Item = S>) -> Self {
1406        let geom = crate::geom::partition::GeomPartition::sunburst(levels);
1407        // The hole is `hole` level-widths of the `levels.len() + hole` radius.
1408        let depth = geom.levels.len().max(1) as f64;
1409        let inner = geom.hole / (geom.hole + depth);
1410        let mut plot = self.default_styled(|p| p.geom_partition_with(geom));
1411        plot.coord = Box::new(CoordPolar::new().inner_radius(inner));
1412        plot
1413    }
1414
1415    /// Icicle chart over `levels`: the partition of
1416    /// [`geom_sunburst`](Self::geom_sunburst) in Cartesian coordinates, root
1417    /// level on top.
1418    pub fn geom_icicle<S: Into<String>>(self, levels: impl IntoIterator<Item = S>) -> Self {
1419        self.default_styled(|p| {
1420            p.geom_partition_with(crate::geom::partition::GeomPartition::icicle(levels))
1421        })
1422    }
1423
1424    /// A partition layer with explicit settings (sunburst under
1425    /// `coord_polar`, icicle otherwise); same defaults as the shortcuts
1426    /// except the coordinate system, which is left as is.
1427    pub fn geom_partition_with(self, geom: crate::geom::partition::GeomPartition) -> Self {
1428        use crate::aes::Aesthetic;
1429        let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
1430        let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
1431        let fill_mapped = self.mapping.get_mapping(&Aesthetic::Fill).is_some();
1432        let mut plot = self.add_geom_with(geom);
1433        plot.hide_position_guides = true;
1434        if !fill_mapped {
1435            plot = plot
1436                .layer_aes(Aes::new().after_stat_fill("root"))
1437                .show_legend(false);
1438        }
1439        if !has_x {
1440            plot = plot.scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1441        }
1442        if !has_y {
1443            plot = plot.scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1444        }
1445        plot
1446    }
1447
1448    /// Funnel chart: map `x` (stage, in data order; repeats are summed) and
1449    /// `y` (value). Equal-height stages whose width is proportional to the
1450    /// value, each tapering to the next; labels show the value and the
1451    /// conversion from the first stage. Stages are filled by name (no
1452    /// legend); axes and grid are hidden. See
1453    /// [`GeomFunnel::silhouette`](crate::geom::funnel::GeomFunnel::silhouette)
1454    /// for the Highcharts-style fixed shape.
1455    pub fn geom_funnel(self) -> Self {
1456        self.default_styled(|p| p.geom_funnel_with(crate::geom::funnel::GeomFunnel::default()))
1457    }
1458
1459    /// Pyramid chart: apex on top, stage heights proportional to the values.
1460    pub fn geom_pyramid(self) -> Self {
1461        self.default_styled(|p| p.geom_funnel_with(crate::geom::funnel::GeomFunnel::pyramid()))
1462    }
1463
1464    /// [`geom_funnel`](Self::geom_funnel) with an explicit shape and styling.
1465    pub fn geom_funnel_with(self, geom: crate::geom::funnel::GeomFunnel) -> Self {
1466        let fill_mapped = self
1467            .mapping
1468            .get_mapping(&crate::aes::Aesthetic::Fill)
1469            .is_some();
1470        let mut plot = self.add_geom_with(geom);
1471        plot.hide_position_guides = true;
1472        if !fill_mapped {
1473            plot = plot
1474                .layer_aes(Aes::new().after_stat_fill("stage"))
1475                .show_legend(false);
1476        }
1477        plot
1478    }
1479
1480    /// Streamgraph: [`geom_area`](Self::geom_area) stacked around a
1481    /// wiggle-minimising baseline ([`StackOffset::Wiggle`](crate::position::stack::StackOffset::Wiggle)).
1482    /// Map `x`, `y` (non-negative) and `fill` (the series). For a
1483    /// symmetric ThemeRiver use
1484    /// `.geom_area().position(position_stack().with_offset(StackOffset::Silhouette))`.
1485    pub fn geom_stream(self) -> Self {
1486        self.geom_area().position(
1487            crate::position::stack::position_stack()
1488                .with_offset(crate::position::stack::StackOffset::Wiggle),
1489        )
1490    }
1491
1492    /// Lollipop chart: a stem from 0 to `y` capped with a dot, per `x`
1493    /// (`coord_flip` for horizontal lollipops).
1494    pub fn geom_lollipop(self) -> Self {
1495        self.add_geom(crate::geom::lollipop::GeomLollipop::default())
1496    }
1497
1498    pub fn geom_lollipop_with(self, geom: crate::geom::lollipop::GeomLollipop) -> Self {
1499        self.add_geom_with(geom)
1500    }
1501
1502    /// Dumbbell chart: a segment from `ymin` to `ymax` per `x`, with a dot at
1503    /// each end (low / high colours); `coord_flip` for the usual horizontal
1504    /// layout.
1505    pub fn geom_dumbbell(self) -> Self {
1506        self.add_geom(crate::geom::lollipop::GeomDumbbell::default())
1507    }
1508
1509    pub fn geom_dumbbell_with(self, geom: crate::geom::lollipop::GeomDumbbell) -> Self {
1510        self.add_geom_with(geom)
1511    }
1512
1513    /// Bullet chart (horizontal): map `x` (KPI) and `y` (actual); configure
1514    /// the target column and range bands on the geom, e.g.
1515    /// `GeomBullet::default().with_target("goal").with_ranges([60.0, 80.0, 100.0])`.
1516    /// Sets `coord_flip`; use [`geom_bullet_vertical`](Self::geom_bullet_vertical)
1517    /// for upright bullets.
1518    pub fn geom_bullet(self, geom: crate::geom::bullet::GeomBullet) -> Self {
1519        self.add_geom_with(geom).coord_flip()
1520    }
1521
1522    /// [`geom_bullet`](Self::geom_bullet) without the flip (vertical bars).
1523    pub fn geom_bullet_vertical(self, geom: crate::geom::bullet::GeomBullet) -> Self {
1524        self.add_geom_with(geom)
1525    }
1526
1527    /// Waffle chart: map `fill` (category) and `weight` (units per row);
1528    /// units fill a grid `rows` high, one contiguous block per category.
1529    /// Axes and grid are hidden; units stay square at any panel aspect.
1530    pub fn geom_waffle(self, rows: usize) -> Self {
1531        self.default_styled(|p| p.geom_waffle_with(crate::geom::waffle::GeomWaffle::waffle(rows)))
1532    }
1533
1534    /// Parliament (hemicycle) chart: map `fill` (party) and `weight`
1535    /// (seats); seats on concentric arcs, parties left to right in data
1536    /// order. `rows = 0` picks the number of arcs from the seat count.
1537    pub fn geom_parliament(self, rows: usize) -> Self {
1538        self.default_styled(|p| {
1539            p.geom_waffle_with(crate::geom::waffle::GeomWaffle::parliament(rows))
1540        })
1541    }
1542
1543    /// A waffle / parliament layer with explicit settings.
1544    pub fn geom_waffle_with(self, geom: crate::geom::waffle::GeomWaffle) -> Self {
1545        let mut plot = self.add_geom_with(geom);
1546        plot.hide_position_guides = true;
1547        plot
1548    }
1549
1550    /// Packed bubble chart: circles with area ∝ `weight`, packed without
1551    /// overlap; with `subgroup` they cluster per group (outlined). Fills by
1552    /// subgroup when `subgroup` is mapped at plot level and `fill` is not.
1553    /// The panel is square and the axes and grid are hidden.
1554    pub fn geom_packed_bubble(self) -> Self {
1555        self.default_styled(|p| {
1556            p.geom_packed_bubble_with(crate::geom::pack::GeomPackedBubble::default())
1557        })
1558    }
1559
1560    /// [`geom_packed_bubble`](Self::geom_packed_bubble) with explicit styling.
1561    pub fn geom_packed_bubble_with(self, geom: crate::geom::pack::GeomPackedBubble) -> Self {
1562        use crate::aes::Aesthetic;
1563        let fill_by = match (
1564            self.mapping.get_mapping(&Aesthetic::Fill),
1565            self.mapping.get_mapping(&Aesthetic::Subgroup),
1566        ) {
1567            (None, Some(sub)) => Some(sub.to_string()),
1568            _ => None,
1569        };
1570        let mut plot = self.add_geom_with(geom);
1571        plot.hide_position_guides = true;
1572        plot.default_aspect_ratio = Some(1.0);
1573        if let Some(sub) = fill_by {
1574            plot = plot.layer_aes(Aes::new().fill(&sub));
1575        }
1576        plot
1577    }
1578
1579    /// Network graph from an edge list: map `from`, `to` and optionally
1580    /// `weight`. Force-directed layout (seeded, deterministic), edges with
1581    /// width ∝ weight, nodes sized by degree and labelled. Square panel,
1582    /// axes and grid hidden. See [`GeomNetwork`](crate::geom::network::GeomNetwork)
1583    /// for directed edges, other layouts and colouring by component.
1584    pub fn geom_network(self) -> Self {
1585        self.add_network(crate::geom::network::GeomNetwork::default(), false)
1586    }
1587
1588    /// [`geom_network`](Self::geom_network) with explicit settings.
1589    pub fn geom_network_with(self, geom: crate::geom::network::GeomNetwork) -> Self {
1590        self.add_network(geom, true)
1591    }
1592
1593    fn add_network(self, geom: crate::geom::network::GeomNetwork, explicit: bool) -> Self {
1594        let by_component = geom.color_components;
1595        let mut plot = if explicit {
1596            self.add_geom_with(geom)
1597        } else {
1598            self.add_geom(geom)
1599        };
1600        plot.hide_position_guides = true;
1601        plot.default_aspect_ratio = Some(1.0);
1602        if by_component {
1603            plot = plot
1604                .layer_aes(Aes::new().after_stat_fill("component"))
1605                .show_legend(false);
1606        }
1607        plot
1608    }
1609
1610    /// Tree diagram from parent → child links: map `from` (parent) and `to`
1611    /// (child). Tidy layout (leaves evenly spaced, parents centred over
1612    /// their children), top-down with curved links. See
1613    /// [`GeomTree::org_chart`](crate::geom::tree::GeomTree::org_chart) and
1614    /// other orientations via [`geom_tree_with`](Self::geom_tree_with).
1615    /// Axes and grid are hidden.
1616    pub fn geom_tree(self) -> Self {
1617        self.default_styled(|p| p.geom_tree_with(crate::geom::tree::GeomTree::default()))
1618    }
1619
1620    /// Dendrogram from [`dendrogram_links`](crate::stat::tree::dendrogram_links)
1621    /// output (`from`, `to`, `height`): step links at the merge heights,
1622    /// leaves labelled.
1623    pub fn geom_dendrogram(self) -> Self {
1624        self.default_styled(|p| p.geom_tree_with(crate::geom::tree::GeomTree::dendrogram()))
1625    }
1626
1627    /// A tree layer with explicit layout and styling.
1628    pub fn geom_tree_with(self, geom: crate::geom::tree::GeomTree) -> Self {
1629        let radial = geom.orientation == crate::stat::tree::TreeOrientation::Radial;
1630        let mut plot = self.add_geom_with(geom);
1631        plot.hide_position_guides = true;
1632        if radial {
1633            plot.default_aspect_ratio = Some(1.0);
1634        }
1635        plot
1636    }
1637
1638    /// Area-proportional Venn / Euler diagram: map `sets` (`"A"`, `"B"`,
1639    /// `"A&B"`, … — venn.js-style inclusive sizes) and `weight` (size).
1640    /// Exact for two and three sets' pairwise overlaps, approximate beyond.
1641    /// Circles are filled by set name (no legend — regions are labelled);
1642    /// square panel, axes and grid hidden.
1643    pub fn geom_venn(self) -> Self {
1644        self.default_styled(|p| p.geom_venn_with(crate::geom::venn::GeomVenn::default()))
1645    }
1646
1647    /// [`geom_venn`](Self::geom_venn) with explicit styling.
1648    pub fn geom_venn_with(self, geom: crate::geom::venn::GeomVenn) -> Self {
1649        let mut plot = self.add_geom_with(geom);
1650        plot.hide_position_guides = true;
1651        plot.default_aspect_ratio = Some(1.0);
1652        plot.layer_aes(Aes::new().after_stat_fill("set"))
1653            .show_legend(false)
1654    }
1655
1656    /// Word cloud: map `label` (word) and `weight` (frequency); optionally
1657    /// `color`. Largest words placed first along a spiral from the centre,
1658    /// no overlaps, deterministic; words that don't fit are dropped. Axes
1659    /// and grid are hidden.
1660    pub fn geom_wordcloud(self) -> Self {
1661        self.default_styled(|p| {
1662            p.geom_wordcloud_with(crate::geom::wordcloud::GeomWordcloud::default())
1663        })
1664    }
1665
1666    /// [`geom_wordcloud`](Self::geom_wordcloud) with explicit sizes,
1667    /// rotation share, seed and palette.
1668    pub fn geom_wordcloud_with(self, geom: crate::geom::wordcloud::GeomWordcloud) -> Self {
1669        let mut plot = self.add_geom_with(geom);
1670        plot.hide_position_guides = true;
1671        plot
1672    }
1673
1674    /// Variwide chart: map `x` (category), `y` (height) and `weight` (bar
1675    /// width). Unless an x scale is set, the x axis is continuous over the
1676    /// column layout with each category named under its column (computed
1677    /// from the plot data, so map `x`/`weight` at plot level).
1678    pub fn geom_variwide(self) -> Self {
1679        self.default_styled(|p| {
1680            p.geom_marimekko_with(crate::geom::marimekko::GeomMarimekko::variwide())
1681        })
1682    }
1683
1684    /// Marimekko (mosaic) chart: map `x` (column), `fill` (segment) and
1685    /// `weight` (value). Column widths are their totals' shares, segments
1686    /// their share of the column (y axis 0–100 %).
1687    pub fn geom_marimekko(self) -> Self {
1688        self.default_styled(|p| {
1689            p.geom_marimekko_with(crate::geom::marimekko::GeomMarimekko::marimekko())
1690        })
1691    }
1692
1693    /// A variwide / Marimekko layer with explicit settings.
1694    pub fn geom_marimekko_with(self, geom: crate::geom::marimekko::GeomMarimekko) -> Self {
1695        use crate::aes::Aesthetic;
1696        let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
1697        let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
1698        // Column centres and names from the plot data (same layout as the stat).
1699        let axis = self.mapping.get_mapping(&Aesthetic::X).and_then(|xc| {
1700            let x = self.data.column(xc)?;
1701            let w = self
1702                .mapping
1703                .get_mapping(&Aesthetic::Weight)
1704                .and_then(|wc| self.data.column(wc));
1705            let totals = crate::stat::marimekko::column_totals(x, w);
1706            let widths: Vec<f64> = totals.iter().map(|t| t.1).collect();
1707            let spans = crate::stat::marimekko::column_spans(&widths, geom.gap);
1708            Some((
1709                spans
1710                    .iter()
1711                    .map(|s| (s.0 + s.1) / 2.0)
1712                    .collect::<Vec<f64>>(),
1713                totals.into_iter().map(|t| t.0).collect::<Vec<String>>(),
1714            ))
1715        });
1716        let mosaic = geom.mosaic;
1717        let mut plot = self.add_geom_with(geom);
1718        if !has_x {
1719            let mut sx = ScaleContinuous::new().with_expand(0.0, 0.0);
1720            if let Some((breaks, labels)) = axis {
1721                sx = sx.with_breaks(breaks).with_labels(labels);
1722            }
1723            plot = plot.scale_x_continuous(sx);
1724        }
1725        if mosaic && !has_y {
1726            plot = plot.scale_y_continuous(
1727                ScaleContinuous::new()
1728                    .with_expand(0.0, 0.0)
1729                    .with_label_formatter(|v| format!("{}%", (v * 100.0).round())),
1730            );
1731        }
1732        plot
1733    }
1734
1735    /// Timeline: map `x` (event time, e.g. a date), `label`, and optionally
1736    /// `xend` (span end) and `color`. Events sit on a central baseline with
1737    /// boxed labels stacked on alternating levels so they never overlap;
1738    /// the y axis and horizontal grid are hidden.
1739    pub fn geom_timeline(self) -> Self {
1740        let mut plot = self.add_geom(crate::geom::timeline::GeomTimeline::default());
1741        plot.hide_y_guides = true;
1742        plot
1743    }
1744
1745    /// [`geom_timeline`](Self::geom_timeline) with explicit styling.
1746    pub fn geom_timeline_with(self, geom: crate::geom::timeline::GeomTimeline) -> Self {
1747        let mut plot = self.add_geom_with(geom);
1748        plot.hide_y_guides = true;
1749        plot
1750    }
1751
1752    /// X-range / Gantt chart: map `y` (task), `xmin` (start) and `xmax`
1753    /// (end), optionally `fill`. Zero-length tasks are milestones
1754    /// (diamonds). Unless a y scale is set, tasks read top to bottom in data
1755    /// order (from the plot data). See
1756    /// [`GeomXrange`](crate::geom::xrange::GeomXrange) for progress and
1757    /// dependency arrows.
1758    pub fn geom_xrange(self) -> Self {
1759        self.add_xrange(crate::geom::xrange::GeomXrange::default(), false)
1760    }
1761
1762    /// [`geom_xrange`](Self::geom_xrange) with progress / dependency columns.
1763    pub fn geom_xrange_with(self, geom: crate::geom::xrange::GeomXrange) -> Self {
1764        self.add_xrange(geom, true)
1765    }
1766
1767    fn add_xrange(self, geom: crate::geom::xrange::GeomXrange, explicit: bool) -> Self {
1768        use crate::aes::Aesthetic;
1769        let has_y = self.scales.iter().any(|s| s.aesthetic() == Aesthetic::Y);
1770        // First task on top: reverse the data order for the discrete axis.
1771        let levels: Option<Vec<String>> = self
1772            .mapping
1773            .get_mapping(&Aesthetic::Y)
1774            .and_then(|c| self.data.column(c))
1775            .map(|col| {
1776                let mut seen: indexmap::IndexSet<String> = indexmap::IndexSet::new();
1777                for v in col.iter().filter(|v| !v.is_na()) {
1778                    seen.insert(v.key_str().into_owned());
1779                }
1780                seen.into_iter().rev().collect()
1781            });
1782        let mut plot = if explicit {
1783            self.add_geom_with(geom)
1784        } else {
1785            self.add_geom(geom)
1786        };
1787        if let (false, Some(levels)) = (has_y, levels) {
1788            let refs: Vec<&str> = levels.iter().map(String::as_str).collect();
1789            plot = plot
1790                .scale_y_discrete(crate::scale::discrete::ScaleDiscrete::new().with_limits(refs));
1791        }
1792        plot
1793    }
1794
1795    /// Tile-grid cartogram: map `x` (grid column), `y` (grid row, 0 at the
1796    /// top), `fill` and `label`; one equal tile per row (see
1797    /// [`us_state_grid`](crate::geom::tilemap::us_state_grid) for a ready
1798    /// US layout). Axes and grid are hidden.
1799    pub fn geom_tilemap(self, shape: crate::geom::tilemap::TileShape) -> Self {
1800        self.default_styled(|p| {
1801            p.geom_tilemap_with(crate::geom::tilemap::GeomTilemap {
1802                shape,
1803                ..Default::default()
1804            })
1805        })
1806    }
1807
1808    /// [`geom_tilemap`](Self::geom_tilemap) with explicit styling.
1809    pub fn geom_tilemap_with(self, geom: crate::geom::tilemap::GeomTilemap) -> Self {
1810        let mut plot = self.add_geom_with(geom);
1811        plot.hide_position_guides = true;
1812        plot
1813    }
1814
1815    /// Wind barbs: map `x` (and optionally `y`), and name the speed (knots,
1816    /// or m/s via `.meters_per_second()`) and direction (degrees the wind
1817    /// comes from) columns:
1818    /// `geom_windbarb(GeomWindbarb::new("speed", "dir"))`.
1819    pub fn geom_windbarb(self, geom: crate::geom::windbarb::GeomWindbarb) -> Self {
1820        self.add_geom(geom)
1821    }
1822
1823    /// Variable-radius pie (Highcharts `variablepie`): map `y` (wedge
1824    /// angle), `radius` (wedge length) and `fill` (category), optionally
1825    /// `label`. Square panel, axes and grid hidden.
1826    pub fn geom_variable_pie(self) -> Self {
1827        let mut plot = self.add_geom(crate::geom::variablepie::GeomVariablePie::default());
1828        plot.hide_position_guides = true;
1829        plot.default_aspect_ratio = Some(1.0);
1830        plot
1831    }
1832
1833    /// [`geom_variable_pie`](Self::geom_variable_pie) with explicit settings
1834    /// (e.g. a donut `inner`).
1835    pub fn geom_variable_pie_with(self, geom: crate::geom::variablepie::GeomVariablePie) -> Self {
1836        let mut plot = self.add_geom_with(geom);
1837        plot.hide_position_guides = true;
1838        plot.default_aspect_ratio = Some(1.0);
1839        plot
1840    }
1841
1842    /// HLC bars: a high–low bar with a close tick (no `open` needed); map
1843    /// `x` and `high`/`low`/`close`.
1844    pub fn geom_hlc(self) -> Self {
1845        self.add_geom(crate::geom::candlestick::GeomOhlc::hlc())
1846    }
1847
1848    /// Heikin-Ashi candles: [`geom_candlestick`](Self::geom_candlestick)
1849    /// over the Heikin-Ashi transform of the OHLC values
1850    /// ([`StatHeikinAshi`](crate::stat::heikin_ashi::StatHeikinAshi)).
1851    pub fn geom_heikin_ashi(self) -> Self {
1852        self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
1853            .stat(crate::stat::heikin_ashi::StatHeikinAshi)
1854    }
1855
1856    /// Renko chart: map `y` to the price (rows in time order); a brick of
1857    /// `box_size` per full move, reversals after two boxes. The x axis
1858    /// counts bricks.
1859    pub fn geom_renko(self, box_size: f64) -> Self {
1860        self.add_geom(crate::geom::renko::GeomRenko::renko(box_size))
1861            .xlab("Brick")
1862    }
1863
1864    /// Point-and-figure chart: map `y` to the price (rows in time order);
1865    /// X columns rise, O columns fall, a column reverses after `reversal`
1866    /// boxes of `box_size`. The x axis counts columns.
1867    pub fn geom_point_figure(self, box_size: f64, reversal: usize) -> Self {
1868        self.add_geom(crate::geom::renko::GeomRenko::point_figure(
1869            box_size, reversal,
1870        ))
1871        .xlab("Column")
1872    }
1873
1874    /// Event flags: map `x` and `label` (usually as a layer with its own
1875    /// `layer_data`); flags stand on the x axis, or on a series with
1876    /// [`GeomFlags::on_series`](crate::geom::flags::GeomFlags::on_series).
1877    /// Flags at the same x stack.
1878    pub fn geom_flags(self) -> Self {
1879        self.add_geom(crate::geom::flags::GeomFlags::default())
1880    }
1881
1882    pub fn geom_flags_with(self, geom: crate::geom::flags::GeomFlags) -> Self {
1883        self.add_geom_with(geom)
1884    }
1885
1886    /// Flow map (feature `sf`): map `x`/`y` (origin lon/lat), `xend`/`yend`
1887    /// (destination) and `weight`; curved bands with arrowheads, projected
1888    /// with the geom's projection (match your `geom_sf` layers), e.g.
1889    /// `geom_flow(GeomFlow::default().project(SfProjection::Mercator))`.
1890    #[cfg(feature = "sf")]
1891    pub fn geom_flow(self, geom: crate::geom::flow::GeomFlow) -> Self {
1892        self.add_geom(geom)
1893    }
1894
1895    /// Candlestick chart: map `x` and `open`/`high`/`low`/`close`
1896    /// (`Aes::new().x("date").open("o").high("h").low("l").close("c")`).
1897    pub fn geom_candlestick(self) -> Self {
1898        self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
1899    }
1900
1901    pub fn geom_candlestick_with(self, geom: crate::geom::candlestick::GeomCandlestick) -> Self {
1902        self.add_geom_with(geom)
1903    }
1904
1905    /// OHLC bar chart (high–low bar with open/close ticks); same aesthetics as
1906    /// [`geom_candlestick`](Self::geom_candlestick).
1907    pub fn geom_ohlc(self) -> Self {
1908        self.add_geom(crate::geom::candlestick::GeomOhlc::default())
1909    }
1910
1911    pub fn geom_ohlc_with(self, geom: crate::geom::candlestick::GeomOhlc) -> Self {
1912        self.add_geom_with(geom)
1913    }
1914
1915    /// Calendar heatmap (GitHub/ECharts style): the plot's `x` (a date —
1916    /// `DateTime`, epoch seconds or `"YYYY-MM-DD"`) is laid out as week
1917    /// columns × weekday rows (Sunday on top) via [`StatCalendar`], coloured
1918    /// by `fill`, with month labels along x, Mon/Wed/Fri along y, month
1919    /// boundary outlines and square cells. Spans over
1920    /// [`MAX_CALENDAR_YEARS`] are clipped to the most recent years (with a
1921    /// build warning). Uses the plot-level data and `x` mapping.
1922    ///
1923    /// [`StatCalendar`]: crate::stat::calendar::StatCalendar
1924    /// [`MAX_CALENDAR_YEARS`]: crate::stat::calendar::MAX_CALENDAR_YEARS
1925    pub fn geom_calendar(self) -> Self {
1926        self.geom_calendar_with(
1927            GeomTile {
1928                color: (255, 255, 255),
1929                line_width: 1.5,
1930                ..Default::default()
1931            },
1932            false,
1933        )
1934    }
1935
1936    /// [`geom_calendar`](Self::geom_calendar) with a custom cell style and
1937    /// optionally Monday-first weeks.
1938    pub fn geom_calendar_with(mut self, tile: GeomTile, monday_first: bool) -> Self {
1939        use crate::stat::calendar::{
1940            day_number, month_boundaries, month_breaks, month_breaks_localized, weekday_labels,
1941            CalendarGrid, StatCalendar, MAX_CALENDAR_YEARS,
1942        };
1943        let grid = self
1944            .mapping
1945            .get_mapping(&crate::aes::Aesthetic::X)
1946            .and_then(|c| self.data.column(c))
1947            .and_then(|col| {
1948                CalendarGrid::from_days(col.iter().filter_map(day_number), monday_first)
1949            });
1950        let Some((grid, clipped)) = grid else {
1951            // No dates: an empty calendar layer (renders an empty panel).
1952            return self.add_geom_with(tile).stat(StatCalendar {
1953                grid: None,
1954                monday_first,
1955            });
1956        };
1957        if clipped {
1958            self.warnings.push(format!(
1959                "geom_calendar: dates more than {MAX_CALENDAR_YEARS} years before the newest were dropped"
1960            ));
1961        }
1962        let (xb, _) = month_breaks(&grid);
1963        // Rows: y = 6 - weekday; label Mon/Wed/Fri.
1964        let yb = if monday_first {
1965            vec![6.0, 4.0, 2.0]
1966        } else {
1967            vec![5.0, 3.0, 1.0]
1968        };
1969        let segs = month_boundaries(&grid);
1970        let col = |f: fn(&(f64, f64, f64, f64)) -> f64| -> Vec<Value> {
1971            segs.iter().map(|s| Value::Float(f(s))).collect()
1972        };
1973        let boundaries = vec![
1974            ("x".to_string(), col(|s| s.0)),
1975            ("y".to_string(), col(|s| s.1)),
1976            ("xend".to_string(), col(|s| s.2)),
1977            ("yend".to_string(), col(|s| s.3)),
1978        ];
1979        self.default_aspect_ratio = Some(7.0 / grid.n_weeks().max(1) as f64);
1980        let plot = self
1981            .add_geom_with(tile)
1982            .stat(StatCalendar {
1983                grid: Some(grid),
1984                monday_first,
1985            })
1986            .scale_x_continuous(
1987                ScaleContinuous::new()
1988                    .with_breaks(xb)
1989                    // Month / weekday names follow the plot locale.
1990                    .with_localized_labels(move |l| month_breaks_localized(&grid, l).1)
1991                    .with_expand(0.0, 0.0),
1992            )
1993            .scale_y_continuous(
1994                ScaleContinuous::new()
1995                    .with_breaks(yb)
1996                    .with_localized_labels(weekday_labels)
1997                    .with_expand(0.0, 0.0),
1998            );
1999        if segs.is_empty() {
2000            return plot;
2001        }
2002        // Styled by the theme's `calendar_month_border` at draw time.
2003        plot.add_geom_with(crate::geom::segment::GeomCalendarBorder)
2004            .layer_data(boundaries)
2005            .layer_aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
2006            .show_legend(false)
2007    }
2008
2009    pub fn geom_blank(self) -> Self {
2010        self.add_geom(GeomBlank)
2011    }
2012
2013    /// Add a geom configured explicitly by the caller: its colours win over
2014    /// the theme's `primary_color`.
2015    /// Run a `geom_*_with` builder for a shortcut's *default* geom, then
2016    /// clear the `explicit_style` mark it put on the layer, so the defaults
2017    /// still take theme ink/paper and `primary_color` like `geom_line()`
2018    /// does (#362).
2019    fn default_styled(self, build: impl FnOnce(Self) -> Self) -> Self {
2020        let i = self.layers.len();
2021        let mut plot = build(self);
2022        if let Some(layer) = plot.layers.get_mut(i) {
2023            layer.explicit_style = false;
2024        }
2025        plot
2026    }
2027
2028    fn add_geom_with(self, geom: impl Geom + 'static) -> Self {
2029        let mut plot = self.add_geom(geom);
2030        if let Some(layer) = plot.layers.last_mut() {
2031            layer.explicit_style = true;
2032        }
2033        plot
2034    }
2035
2036    fn add_geom(mut self, geom: impl Geom + 'static) -> Self {
2037        let stat = geom.default_stat();
2038        let position = geom.default_position();
2039        let params = geom.default_params();
2040        self.layers.push(Layer {
2041            data: None,
2042            mapping: Aes::default(),
2043            geom: Box::new(geom),
2044            stat,
2045            position,
2046            params,
2047            show_legend: None,
2048            explicit_style: false,
2049            tooltip_template: None,
2050            key_glyph: None,
2051            show_legend_aes: Vec::new(),
2052        });
2053        self
2054    }
2055
2056    // ─── Layer-level overrides ──────────────────────────────────
2057
2058    /// Override the stat for the most recently added layer.
2059    pub fn stat(mut self, stat: impl Stat + 'static) -> Self {
2060        if let Some(layer) = self.layers.last_mut() {
2061            layer.stat = Box::new(stat);
2062        }
2063        self
2064    }
2065
2066    /// Override the position for the most recently added layer.
2067    pub fn position(mut self, pos: impl Position + 'static) -> Self {
2068        if let Some(layer) = self.layers.last_mut() {
2069            layer.position = Box::new(pos);
2070        }
2071        self
2072    }
2073
2074    /// Override the data for the most recently added layer.
2075    pub fn layer_data(mut self, data: impl GGData) -> Self {
2076        if let Some(layer) = self.layers.last_mut() {
2077            layer.data = Some(data.into_dataframe());
2078        }
2079        self
2080    }
2081
2082    /// Override the aesthetic mapping for the most recently added layer.
2083    pub fn layer_aes(mut self, mapping: Aes) -> Self {
2084        self.warnings.extend(mapping.warnings.iter().cloned());
2085        if let Some(layer) = self.layers.last_mut() {
2086            layer.mapping = mapping;
2087        }
2088        self
2089    }
2090
2091    /// A `{column}` tooltip template for the most recently added layer
2092    /// (B2-5), replacing its default `<title>`. Each placeholder is filled
2093    /// from the *built* layer data (so it can reference a stat-computed
2094    /// column, e.g. a hex's `count`) at that row, formatted through the
2095    /// column's scale when it has one
2096    /// ([`Scale::format_value`](crate::scale::Scale::format_value)) — the same
2097    /// `data-fvalue` logic, but written into the tooltip text. A column
2098    /// that doesn't exist on this layer renders as empty, not literally
2099    /// `{column}`. `{{`/`}}` are literal braces. The result is escaped the
2100    /// same way any other tooltip is — this is plain text, not markup.
2101    pub fn tooltip(mut self, template: &str) -> Self {
2102        if let Some(layer) = self.layers.last_mut() {
2103            layer.tooltip_template = Some(template.to_string());
2104        }
2105        self
2106    }
2107
2108    /// Control whether the most recently added layer contributes to the legend.
2109    /// `true` = always show, `false` = always hide, default (None) = auto.
2110    pub fn show_legend(mut self, show: bool) -> Self {
2111        if let Some(layer) = self.layers.last_mut() {
2112            layer.show_legend = Some(show);
2113        }
2114        self
2115    }
2116
2117    /// Drop one aesthetic's legend (ggplot2's `guides(fill = "none")`, #409).
2118    pub fn guide_none(mut self, aes: crate::aes::Aesthetic) -> Self {
2119        if !self.guide_legend.hidden.contains(&aes) {
2120            self.guide_legend.hidden.push(aes);
2121        }
2122        self
2123    }
2124
2125    /// Title one aesthetic's legend (`guides(colour = guide_legend(title =
2126    /// "…"))` / `labs(colour = "…")`, #409).
2127    pub fn guide_title(mut self, aes: crate::aes::Aesthetic, title: &str) -> Self {
2128        self.guide_legend.titles.retain(|(a, _)| *a != aes);
2129        self.guide_legend.titles.push((aes, title.to_string()));
2130        self
2131    }
2132
2133    /// Options for a continuous colour / fill legend (ggplot2's
2134    /// `guides(fill = guide_colourbar(barwidth =, nbin =, display =, frame
2135    /// =, ticks =))`, or `guide_coloursteps()` with [`GuideColourbar::steps`];
2136    /// #409).
2137    ///
2138    /// [`GuideColourbar::steps`]: crate::guide::config::GuideColourbar::steps
2139    pub fn guide_colourbar(
2140        mut self,
2141        aes: crate::aes::Aesthetic,
2142        bar: crate::guide::config::GuideColourbar,
2143    ) -> Self {
2144        self.guide_legend.colourbars.retain(|(a, _)| *a != aes);
2145        self.guide_legend.colourbars.push((aes, bar));
2146        self
2147    }
2148
2149    /// Options for a binned scale's legend (ggplot2's `guides(size =
2150    /// guide_bins(show.limits =, axis =))`, #409 / #408). `guide_bins()` is
2151    /// already the default guide of the `scale_*_binned()` scales; this
2152    /// sets its options.
2153    pub fn guide_bins(
2154        mut self,
2155        aes: crate::aes::Aesthetic,
2156        bins: crate::guide::config::GuideBins,
2157    ) -> Self {
2158        self.guide_legend.plain_keys.retain(|a| *a != aes);
2159        self.guide_legend.bins.retain(|(a, _)| *a != aes);
2160        self.guide_legend.bins.push((aes, bins));
2161        self
2162    }
2163
2164    /// Draw one aesthetic's legend at its own side (ggplot2 3.5's
2165    /// `guides(colour = guide_legend(position = "bottom"))`, #409); the
2166    /// others stay at the theme's `legend_position`.
2167    pub fn guide_position(
2168        mut self,
2169        aes: crate::aes::Aesthetic,
2170        position: crate::theme::LegendPosition,
2171    ) -> Self {
2172        self.guide_legend.positions.retain(|(a, _)| *a != aes);
2173        self.guide_legend.positions.push((aes, position));
2174        self
2175    }
2176
2177    /// Add a legend entry drawn by your own code — ggplot2's
2178    /// `guide_custom()` (#409): see [`GuideCustom`](crate::guide::config::GuideCustom).
2179    pub fn guide_custom(mut self, guide: crate::guide::config::GuideCustom) -> Self {
2180        self.guide_legend.custom.push(guide);
2181        self
2182    }
2183
2184    /// Draw a binned scale's legend as plain keys, one labelled `lo–hi`
2185    /// per bin (`guides(size = "legend")`), instead of `guide_bins()`.
2186    pub fn guide_legend_keys(mut self, aes: crate::aes::Aesthetic) -> Self {
2187        self.guide_legend.bins.retain(|(a, _)| *a != aes);
2188        if !self.guide_legend.plain_keys.contains(&aes) {
2189            self.guide_legend.plain_keys.push(aes);
2190        }
2191        self
2192    }
2193
2194    /// ggplot2's `guide_coloursteps()` for `aes`: the colourbar drawn as one
2195    /// solid block per interval between breaks, evenly sized (#409).
2196    pub fn guide_coloursteps(self, aes: crate::aes::Aesthetic) -> Self {
2197        self.guide_colourbar(aes, crate::guide::config::GuideColourbar::steps())
2198    }
2199
2200    /// Reverse one aesthetic's legend keys (`guides(colour =
2201    /// guide_legend(reverse = TRUE))`, #409).
2202    pub fn guide_reverse(mut self, aes: crate::aes::Aesthetic, reverse: bool) -> Self {
2203        self.guide_legend.reversed.retain(|a| *a != aes);
2204        if reverse {
2205            self.guide_legend.reversed.push(aes);
2206        }
2207        self
2208    }
2209
2210    /// Draw one legend's keys with fixed values (ggplot2's `guides(colour =
2211    /// guide_legend(override.aes = list(size = 4, alpha = 1)))`, #409).
2212    pub fn guide_override(
2213        mut self,
2214        aes: crate::aes::Aesthetic,
2215        keys: crate::guide::config::KeyOverride,
2216    ) -> Self {
2217        self.guide_legend.overrides.retain(|(a, _)| *a != aes);
2218        self.guide_legend.overrides.push((aes, keys));
2219        self
2220    }
2221
2222    /// ggplot2's `guides(x = guide_axis_logticks())` (#409): log10 minor
2223    /// ticks on that axis (long at decades, mid at 5s, short otherwise).
2224    /// Call after `scale_x_log10()` / `scale_y_log10()`.
2225    pub fn guide_axis_logticks(mut self, aes: crate::aes::Aesthetic) -> Self {
2226        for s in self.scales.iter_mut().filter(|s| s.aesthetic() == aes) {
2227            s.set_log_ticks(true);
2228        }
2229        self
2230    }
2231
2232    /// Show or hide the most recent layer in one aesthetic's legend only
2233    /// (ggplot2's `show.legend = c(colour = TRUE, fill = FALSE)`; #410).
2234    pub fn show_legend_for(mut self, aes: crate::aes::Aesthetic, show: bool) -> Self {
2235        if let Some(layer) = self.layers.last_mut() {
2236            layer.show_legend_aes.retain(|(a, _)| *a != aes);
2237            layer.show_legend_aes.push((aes, show));
2238        }
2239        self
2240    }
2241
2242    /// Draw the most recent layer's legend keys as `glyph` (ggplot2's
2243    /// `key_glyph =`, e.g. `KeyGlyph::Timeseries` for a line; #410).
2244    pub fn key_glyph(mut self, glyph: crate::guide::key::KeyGlyph) -> Self {
2245        if let Some(layer) = self.layers.last_mut() {
2246            layer.key_glyph = Some(glyph);
2247        }
2248        self
2249    }
2250
2251    /// Mark the most recently added layer as purely decorative (#161): its
2252    /// drawn marks keep their own visual style but carry **no** per-mark
2253    /// metadata — no `<title>`, no `data-x`/`data-series`/`data-value`/
2254    /// `data-fvalue`, and no [`data_attr`](crate::aes::Aes::data_attr)
2255    /// attributes — so an SVG consumer that treats "has a non-empty
2256    /// `<title>`" as "is a selectable data point" doesn't pick it up. Meant
2257    /// for a layer that annotates another layer's mark rather than drawing
2258    /// data in its own right (e.g. a boxplot's own mean dot, drawn by a
2259    /// separate `geom_point` layer purely to mark the spot the box's own
2260    /// tooltip already names). Each mark also carries
2261    /// `data-part="decorative"` and `aria-hidden="true"` (`data-geom`
2262    /// still names the real geom), so a consumer can select decorative
2263    /// marks positively rather than only infer them from what they lack.
2264    /// Their class is `gg-mark gg-decorative`, not the geom's own
2265    /// (`gg-point`, `gg-line`, …).
2266    ///
2267    /// A `.tooltip(...)` template on a decorative layer has no visible
2268    /// effect — the geom's marks carry no tooltip regardless — and warns,
2269    /// like the existing has-no-effect warning for a geom that doesn't
2270    /// read tooltips at all.
2271    ///
2272    /// A decorative layer also defaults to hidden in the legend (it's
2273    /// annotating, not its own series), unless
2274    /// [`show_legend`](Self::show_legend)`(true)` is called — before or
2275    /// after `decorative()` — to opt back in; an explicit
2276    /// `show_legend(false)` is left untouched either way.
2277    pub fn decorative(mut self) -> Self {
2278        if let Some(layer) = self.layers.last_mut() {
2279            let geom = std::mem::replace(&mut layer.geom, Box::new(GeomBlank));
2280            layer.geom = Box::new(crate::geom::decorative::Decorative(geom));
2281            if layer.show_legend.is_none() {
2282                layer.show_legend = Some(false);
2283            }
2284        }
2285        self
2286    }
2287
2288    /// Add one SVG attribute to **every mark** of the most recently added
2289    /// layer (#221) — e.g. to make a label layer drawn over node boxes inert,
2290    /// so hover/click and screen readers pass through to the box below:
2291    ///
2292    /// ```
2293    /// # use ggplot_rs::{aes::Aes, data::Value, GGPlot};
2294    /// # let data = vec![("x".to_string(), vec![Value::Float(1.0)]),
2295    /// #   ("y".to_string(), vec![Value::Float(1.0)]),
2296    /// #   ("l".to_string(), vec![Value::Str("a".into())])];
2297    /// let svg = GGPlot::new(data)
2298    ///     .aes(Aes::new().x("x").y("y").label("l"))
2299    ///     .geom_text()
2300    ///     .layer_svg_attr("aria-hidden", "true")
2301    ///     .layer_svg_attr("pointer-events", "none")
2302    ///     .layer_svg_attr("class", "node-label")
2303    ///     .render_svg_native_with_size(200, 200)
2304    ///     .unwrap();
2305    /// assert!(svg.contains(r#"aria-hidden="true" pointer-events="none""#));
2306    /// ```
2307    ///
2308    /// The allow-list is deliberately small: `class` (space-separated
2309    /// tokens, each `[A-Za-z][A-Za-z0-9_-]*`, appended to the mark's own
2310    /// `gg-mark gg-<kind>` class; invalid tokens are dropped), `aria-hidden`
2311    /// (`"true"`/`"false"`), `pointer-events` (an SVG keyword such as
2312    /// `"none"`), and `data-*` (`Aes::data_attr`'s name rules; a row's own
2313    /// `data_attr` of the same name wins). Anything else — in particular
2314    /// `style` and `on*` handlers, so a strict CSP without `unsafe-inline`
2315    /// still holds — is ignored with a build warning, as is a bad value or a
2316    /// call before any layer. A later call with the same name replaces the
2317    /// earlier value. Values are escaped on output. For a per-row class use
2318    /// [`Aes::class`](crate::aes::Aes::class); to wrap several layers' marks
2319    /// per key in one `<g>`, [`Aes::group_wrap`](crate::aes::Aes::group_wrap).
2320    /// SVG backend only.
2321    pub fn layer_svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
2322        let (name, value) = (name.into(), value.into());
2323        let Some(idx) = self.layers.len().checked_sub(1) else {
2324            self.warnings.push(format!(
2325                "layer_svg_attr(\"{name}\") called before any layer was added — ignored"
2326            ));
2327            return self;
2328        };
2329        if let Some((n, v)) =
2330            crate::render::svg_backend::validate_layer_svg_attr(&name, &value, &mut self.warnings)
2331        {
2332            self.layer_svg_attrs
2333                .retain(|(i, k, _)| !(*i == idx && *k == n));
2334            self.layer_svg_attrs.push((idx, n, v));
2335        }
2336        self
2337    }
2338
2339    /// [`layer_svg_attr`](Self::layer_svg_attr) for several attributes at once.
2340    pub fn layer_svg_attrs<N: Into<String>, V: Into<String>>(
2341        self,
2342        attrs: impl IntoIterator<Item = (N, V)>,
2343    ) -> Self {
2344        attrs
2345            .into_iter()
2346            .fold(self, |p, (n, v)| p.layer_svg_attr(n, v))
2347    }
2348
2349    // ─── Scales ──────────────────────────────────────────────────
2350
2351    pub fn scale_x_continuous(mut self, s: ScaleContinuous) -> Self {
2352        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
2353        self.scales.push(Box::new(s));
2354        self
2355    }
2356
2357    pub fn scale_y_continuous(mut self, s: ScaleContinuous) -> Self {
2358        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
2359        self.scales.push(Box::new(s));
2360        self
2361    }
2362
2363    pub fn scale_x_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
2364        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
2365        self.scales.push(Box::new(s));
2366        self
2367    }
2368
2369    pub fn scale_y_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
2370        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
2371        self.scales.push(Box::new(s));
2372        self
2373    }
2374
2375    pub fn scale_color(mut self, s: impl Scale + 'static) -> Self {
2376        self.scales.push(Box::new(s));
2377        self
2378    }
2379
2380    pub fn scale_fill(mut self, s: impl Scale + 'static) -> Self {
2381        self.scales.push(Box::new(s));
2382        self
2383    }
2384
2385    pub fn scale_color_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
2386        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Color, values);
2387        self.scale_color(s)
2388    }
2389
2390    pub fn scale_fill_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
2391        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Fill, values);
2392        self.scale_fill(s)
2393    }
2394
2395    /// The `colour`/`color` column already holds `#RRGGBB`/`#RGB` hex
2396    /// strings, used as-is — no legend (R's `scale_colour_identity`).
2397    pub fn scale_colour_identity(self) -> Self {
2398        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Color);
2399        self.scale_color(s)
2400    }
2401
2402    /// American-spelling alias for [`scale_colour_identity`](Self::scale_colour_identity).
2403    pub fn scale_color_identity(self) -> Self {
2404        self.scale_colour_identity()
2405    }
2406
2407    /// The `fill` column already holds `#RRGGBB`/`#RGB` hex strings, used
2408    /// as-is — no legend (R's `scale_fill_identity`).
2409    pub fn scale_fill_identity(self) -> Self {
2410        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Fill);
2411        self.scale_fill(s)
2412    }
2413
2414    pub fn scale_color_viridis(self) -> Self {
2415        use crate::scale::color::ScaleColorDiscrete;
2416        use crate::scale::palettes::PaletteName;
2417        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
2418            .with_named_palette(&PaletteName::Viridis);
2419        self.scale_color(s)
2420    }
2421
2422    pub fn scale_color_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
2423        use crate::scale::color::ScaleColorDiscrete;
2424        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).with_named_palette(&name);
2425        self.scale_color(s)
2426    }
2427
2428    pub fn scale_color_gradient(
2429        self,
2430        low: crate::scale::color::RGBAColor,
2431        high: crate::scale::color::RGBAColor,
2432    ) -> Self {
2433        use crate::scale::color::ScaleColorContinuous;
2434        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Color).with_colors(low, high);
2435        self.scale_color(s)
2436    }
2437
2438    pub fn scale_fill_gradient(
2439        self,
2440        low: crate::scale::color::RGBAColor,
2441        high: crate::scale::color::RGBAColor,
2442    ) -> Self {
2443        use crate::scale::color::ScaleColorContinuous;
2444        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Fill).with_colors(low, high);
2445        self.scale_fill(s)
2446    }
2447
2448    pub fn scale_color_gradient2(
2449        self,
2450        low: crate::scale::color::RGBAColor,
2451        mid: crate::scale::color::RGBAColor,
2452        high: crate::scale::color::RGBAColor,
2453    ) -> Self {
2454        use crate::scale::gradient::ScaleColorGradient2;
2455        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Color).with_colors(low, mid, high);
2456        self.scale_color(s)
2457    }
2458
2459    pub fn scale_fill_gradient2(
2460        self,
2461        low: crate::scale::color::RGBAColor,
2462        mid: crate::scale::color::RGBAColor,
2463        high: crate::scale::color::RGBAColor,
2464    ) -> Self {
2465        use crate::scale::gradient::ScaleColorGradient2;
2466        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Fill).with_colors(low, mid, high);
2467        self.scale_fill(s)
2468    }
2469
2470    pub fn scale_fill_viridis(self) -> Self {
2471        use crate::scale::color::ScaleColorDiscrete;
2472        use crate::scale::palettes::PaletteName;
2473        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
2474            .with_named_palette(&PaletteName::Viridis);
2475        self.scale_fill(s)
2476    }
2477
2478    /// Continuous viridis color scale (for numeric data).
2479    pub fn scale_color_viridis_c(self) -> Self {
2480        use crate::scale::gradient_n::ScaleColorGradientN;
2481        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Color);
2482        self.scale_color(s)
2483    }
2484
2485    /// Continuous viridis fill scale (for numeric data).
2486    pub fn scale_fill_viridis_c(self) -> Self {
2487        use crate::scale::gradient_n::ScaleColorGradientN;
2488        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Fill);
2489        self.scale_fill(s)
2490    }
2491
2492    /// N-stop continuous color gradient.
2493    pub fn scale_color_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
2494        use crate::scale::gradient_n::ScaleColorGradientN;
2495        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Color, stops);
2496        self.scale_color(s)
2497    }
2498
2499    /// N-stop continuous fill gradient.
2500    pub fn scale_fill_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
2501        use crate::scale::gradient_n::ScaleColorGradientN;
2502        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Fill, stops);
2503        self.scale_fill(s)
2504    }
2505
2506    /// Binned (stepped) two-colour continuous colour scale — buckets the mapped
2507    /// variable into `n_bins` bins, each a discrete colour, with a stepped legend.
2508    pub fn scale_color_steps(
2509        self,
2510        low: crate::scale::color::RGBAColor,
2511        high: crate::scale::color::RGBAColor,
2512        n_bins: usize,
2513    ) -> Self {
2514        let s = crate::scale::steps::ScaleColorSteps::two(
2515            crate::aes::Aesthetic::Color,
2516            (low.r, low.g, low.b),
2517            (high.r, high.g, high.b),
2518            n_bins,
2519        );
2520        self.scale_color(s)
2521    }
2522
2523    /// Binned N-stop continuous colour scale.
2524    pub fn scale_color_stepsn(
2525        self,
2526        stops: Vec<crate::scale::color::RGBAColor>,
2527        n_bins: usize,
2528    ) -> Self {
2529        let s = crate::scale::steps::ScaleColorSteps::new(
2530            crate::aes::Aesthetic::Color,
2531            stops.iter().map(|c| (c.r, c.g, c.b)).collect(),
2532            n_bins,
2533        );
2534        self.scale_color(s)
2535    }
2536
2537    /// Binned ColorBrewer colour scale (R's `scale_color_fermenter`).
2538    pub fn scale_color_fermenter(
2539        self,
2540        name: crate::scale::palettes::PaletteName,
2541        n_bins: usize,
2542    ) -> Self {
2543        let stops = crate::scale::palettes::palette(&name)
2544            .iter()
2545            .map(|c| (c.r, c.g, c.b))
2546            .collect();
2547        let s =
2548            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Color, stops, n_bins);
2549        self.scale_color(s)
2550    }
2551
2552    /// Binned (stepped) two-colour continuous fill scale.
2553    /// `scale_colour_steps2(low, mid, high, midpoint)`: diverging binned
2554    /// colour scale (#408).
2555    pub fn scale_color_steps2(
2556        self,
2557        low: crate::scale::color::RGBAColor,
2558        mid: crate::scale::color::RGBAColor,
2559        high: crate::scale::color::RGBAColor,
2560        midpoint: f64,
2561        n_bins: usize,
2562    ) -> Self {
2563        self.scale_color(crate::scale::steps::ScaleColorSteps::diverging(
2564            crate::aes::Aesthetic::Color,
2565            (low.r, low.g, low.b),
2566            (mid.r, mid.g, mid.b),
2567            (high.r, high.g, high.b),
2568            midpoint,
2569            n_bins,
2570        ))
2571    }
2572
2573    /// `scale_fill_steps2(low, mid, high, midpoint)` — see
2574    /// [`scale_color_steps2`](Self::scale_color_steps2).
2575    pub fn scale_fill_steps2(
2576        self,
2577        low: crate::scale::color::RGBAColor,
2578        mid: crate::scale::color::RGBAColor,
2579        high: crate::scale::color::RGBAColor,
2580        midpoint: f64,
2581        n_bins: usize,
2582    ) -> Self {
2583        self.scale_fill(crate::scale::steps::ScaleColorSteps::diverging(
2584            crate::aes::Aesthetic::Fill,
2585            (low.r, low.g, low.b),
2586            (mid.r, mid.g, mid.b),
2587            (high.r, high.g, high.b),
2588            midpoint,
2589            n_bins,
2590        ))
2591    }
2592
2593    /// `scale_colour_viridis_b(option)`: binned viridis, `option` 'A'–'H'
2594    /// (#408).
2595    pub fn scale_color_viridis_b(self, option: char, n_bins: usize) -> Self {
2596        self.scale_color(crate::scale::steps::ScaleColorSteps::viridis(
2597            crate::aes::Aesthetic::Color,
2598            option,
2599            n_bins,
2600        ))
2601    }
2602
2603    /// `scale_fill_viridis_b(option)` — see
2604    /// [`scale_color_viridis_b`](Self::scale_color_viridis_b).
2605    pub fn scale_fill_viridis_b(self, option: char, n_bins: usize) -> Self {
2606        self.scale_fill(crate::scale::steps::ScaleColorSteps::viridis(
2607            crate::aes::Aesthetic::Fill,
2608            option,
2609            n_bins,
2610        ))
2611    }
2612
2613    pub fn scale_fill_steps(
2614        self,
2615        low: crate::scale::color::RGBAColor,
2616        high: crate::scale::color::RGBAColor,
2617        n_bins: usize,
2618    ) -> Self {
2619        let s = crate::scale::steps::ScaleColorSteps::two(
2620            crate::aes::Aesthetic::Fill,
2621            (low.r, low.g, low.b),
2622            (high.r, high.g, high.b),
2623            n_bins,
2624        );
2625        self.scale_fill(s)
2626    }
2627
2628    /// Binned fill scale with *explicit* class breaks (`n + 1` increasing
2629    /// edges, `n` colours interpolated `low`→`high`) — R's
2630    /// `scale_fill_steps(breaks = ...)`, backing a `::CLASSES` choropleth
2631    /// (sipemu/ggplot-rs#180). The legend shows each class's trained count
2632    /// (`"10–50 (12)"`) and, when any value is `Value::Na`, a "no data" key
2633    /// in `na_color` (default grey50) — see
2634    /// [`ScaleFillBinned`](crate::scale::binned::ScaleFillBinned) for the
2635    /// `.na_color(..)`/`.na_label(..)` builders. The break maths itself
2636    /// (quantile/Jenks/equal-width/custom edges) is the caller's job; this
2637    /// only bins against the edges it's given.
2638    pub fn scale_fill_binned(
2639        self,
2640        breaks: Vec<f64>,
2641        low: crate::scale::color::RGBAColor,
2642        high: crate::scale::color::RGBAColor,
2643    ) -> Self {
2644        let s = crate::scale::binned::ScaleFillBinned::two(
2645            crate::aes::Aesthetic::Fill,
2646            breaks,
2647            (low.r, low.g, low.b),
2648            (high.r, high.g, high.b),
2649        );
2650        self.scale_fill(s)
2651    }
2652
2653    /// Like [`scale_fill_binned`](Self::scale_fill_binned), with an
2654    /// explicit colour per bin (`colors.len()` should be
2655    /// `breaks.len() - 1`) instead of a two-colour interpolation.
2656    pub fn scale_fill_binned_with(
2657        self,
2658        breaks: Vec<f64>,
2659        colors: Vec<crate::scale::color::RGBAColor>,
2660    ) -> Self {
2661        let s = crate::scale::binned::ScaleFillBinned::new(
2662            crate::aes::Aesthetic::Fill,
2663            breaks,
2664            colors.iter().map(|c| (c.r, c.g, c.b)).collect(),
2665        );
2666        self.scale_fill(s)
2667    }
2668
2669    /// Binned ColorBrewer fill scale.
2670    pub fn scale_fill_fermenter(
2671        self,
2672        name: crate::scale::palettes::PaletteName,
2673        n_bins: usize,
2674    ) -> Self {
2675        let stops = crate::scale::palettes::palette(&name)
2676            .iter()
2677            .map(|c| (c.r, c.g, c.b))
2678            .collect();
2679        let s =
2680            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Fill, stops, n_bins);
2681        self.scale_fill(s)
2682    }
2683
2684    /// Default discrete fill palette with levels in sorted order, so a level
2685    /// keeps its colour across charts regardless of data order. For a custom
2686    /// palette: `scale_fill(ScaleColorDiscrete::new(Aesthetic::Fill)
2687    /// .with_palette(p).sorted())`.
2688    pub fn scale_fill_discrete_sorted(self) -> Self {
2689        use crate::scale::color::ScaleColorDiscrete;
2690        self.scale_fill(ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).sorted())
2691    }
2692
2693    /// Default discrete colour palette with levels in sorted order (see
2694    /// [`scale_fill_discrete_sorted`](Self::scale_fill_discrete_sorted)).
2695    pub fn scale_color_discrete_sorted(self) -> Self {
2696        use crate::scale::color::ScaleColorDiscrete;
2697        self.scale_color(ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).sorted())
2698    }
2699
2700    /// ggplot2's `scale_colour_hue(h, c, l, h.start, direction)`: hues evenly
2701    /// spaced for the number of levels — `HuePalette::default()` gives
2702    /// exactly ggplot2's default colours for any number of groups (#408).
2703    pub fn scale_color_hue(self, p: crate::scale::color::HuePalette) -> Self {
2704        self.scale_color(
2705            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
2706                .with_generated(crate::scale::color::GeneratedPalette::Hue(p)),
2707        )
2708    }
2709
2710    /// `scale_fill_hue(...)` — see [`scale_color_hue`](Self::scale_color_hue).
2711    pub fn scale_fill_hue(self, p: crate::scale::color::HuePalette) -> Self {
2712        self.scale_fill(
2713            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
2714                .with_generated(crate::scale::color::GeneratedPalette::Hue(p)),
2715        )
2716    }
2717
2718    /// `scale_colour_viridis_d(option, begin, end, direction)` for a
2719    /// categorical mapping: `option` 'A' magma … 'D' viridis … 'H' turbo.
2720    pub fn scale_color_viridis_d(self, option: char, begin: f64, end: f64, direction: i32) -> Self {
2721        self.scale_color(
2722            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
2723                .with_generated(crate::scale::color::GeneratedPalette::Viridis {
2724                    option,
2725                    begin,
2726                    end,
2727                    direction,
2728                }),
2729        )
2730    }
2731
2732    /// `scale_fill_viridis_d(...)` — see [`scale_color_viridis_d`](Self::scale_color_viridis_d).
2733    pub fn scale_fill_viridis_d(self, option: char, begin: f64, end: f64, direction: i32) -> Self {
2734        self.scale_fill(
2735            crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
2736                .with_generated(crate::scale::color::GeneratedPalette::Viridis {
2737                    option,
2738                    begin,
2739                    end,
2740                    direction,
2741                }),
2742        )
2743    }
2744
2745    /// `scale_colour_distiller(palette, direction)`: a Brewer palette
2746    /// interpolated as a continuous gradient (ggplot2's default `direction
2747    /// = -1` puts the darkest colour at the low end — pass `-1` for that).
2748    pub fn scale_color_distiller(
2749        self,
2750        palette: crate::scale::palettes::PaletteName,
2751        direction: i32,
2752    ) -> Self {
2753        self.scale_color(distiller(crate::aes::Aesthetic::Color, &palette, direction))
2754    }
2755
2756    /// `scale_fill_distiller(...)` — see [`scale_color_distiller`](Self::scale_color_distiller).
2757    pub fn scale_fill_distiller(
2758        self,
2759        palette: crate::scale::palettes::PaletteName,
2760        direction: i32,
2761    ) -> Self {
2762        self.scale_fill(distiller(crate::aes::Aesthetic::Fill, &palette, direction))
2763    }
2764
2765    /// Force values into the x / y scales' ranges (ggplot2's
2766    /// `expand_limits(x = …, y = …)`), e.g. `expand_limits(&[0.0], &[])` to
2767    /// include 0. Adds an invisible `geom_blank` layer.
2768    pub fn expand_limits(self, x: &[f64], y: &[f64]) -> Self {
2769        let n = x.len().max(y.len());
2770        if n == 0 {
2771            return self;
2772        }
2773        let col =
2774            |v: &[f64]| -> Vec<Value> { (0..n).map(|i| Value::Float(v[i % v.len()])).collect() };
2775        let mut data = Vec::new();
2776        let mut aes = Aes::new();
2777        if !x.is_empty() {
2778            data.push(("x".to_string(), col(x)));
2779            aes = aes.x("x");
2780        }
2781        if !y.is_empty() {
2782            data.push(("y".to_string(), col(y)));
2783            aes = aes.y("y");
2784        }
2785        self.geom_blank().layer_data(data).layer_aes(aes)
2786    }
2787
2788    pub fn scale_fill_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
2789        use crate::scale::color::ScaleColorDiscrete;
2790        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).with_named_palette(&name);
2791        self.scale_fill(s)
2792    }
2793
2794    pub fn scale_linetype_manual(
2795        self,
2796        values: Vec<(&str, crate::render::backend::Linetype)>,
2797    ) -> Self {
2798        let s = crate::scale::linetype_manual::ScaleLinetypeManual::new(values);
2799        self.scale_color(s)
2800    }
2801
2802    pub fn scale_shape_manual(
2803        self,
2804        values: Vec<(&str, crate::render::backend::PointShape)>,
2805    ) -> Self {
2806        let s = crate::scale::shape_manual::ScaleShapeManual::new(values);
2807        self.scale_color(s)
2808    }
2809
2810    pub fn scale_color_grey(self) -> Self {
2811        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Color);
2812        self.scale_color(s)
2813    }
2814
2815    pub fn scale_fill_grey(self) -> Self {
2816        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Fill);
2817        self.scale_fill(s)
2818    }
2819
2820    pub fn scale_color_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
2821        self.scale_color(s)
2822    }
2823
2824    pub fn scale_fill_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
2825        self.scale_fill(s)
2826    }
2827
2828    pub fn scale_x_reverse(self) -> Self {
2829        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
2830    }
2831
2832    pub fn scale_y_reverse(self) -> Self {
2833        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
2834    }
2835
2836    pub fn scale_x_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
2837        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
2838        self.scales.push(Box::new(s));
2839        self
2840    }
2841
2842    pub fn scale_y_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
2843        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
2844        self.scales.push(Box::new(s));
2845        self
2846    }
2847
2848    pub fn scale_size(mut self, s: crate::scale::size::ScaleSizeContinuous) -> Self {
2849        self.scales.push(Box::new(s));
2850        self
2851    }
2852
2853    /// `scale_size_area(max_size)` (ggplot2, B3-6): size scale where
2854    /// *area*, not radius, is proportional to the value, and 0 maps to 0.
2855    /// See [`ScaleSizeContinuous::area`](crate::scale::size::ScaleSizeContinuous::area).
2856    pub fn scale_size_area(mut self, max_size: f64) -> Self {
2857        self.scales.push(Box::new(
2858            crate::scale::size::ScaleSizeContinuous::new().area(max_size),
2859        ));
2860        self
2861    }
2862
2863    /// `scale_radius(range)` (ggplot2): point *radius*, not area,
2864    /// proportional to the value — ggplot-rs's default size mapping (#408).
2865    pub fn scale_radius(self, min: f64, max: f64) -> Self {
2866        self.scale_size(crate::scale::size::ScaleSizeContinuous::new().with_range(min, max))
2867    }
2868
2869    /// ggplot2's `scale_size_binned(n.breaks = n)` (#408): sizes by bin.
2870    pub fn scale_size_binned(self, n: usize) -> Self {
2871        self.scale_color(crate::scale::values::ScaleValueBinned::new(
2872            crate::aes::Aesthetic::Size,
2873            n,
2874        ))
2875    }
2876
2877    /// ggplot2's `scale_alpha_binned()` (#408).
2878    pub fn scale_alpha_binned(self, n: usize) -> Self {
2879        self.scale_color(crate::scale::values::ScaleValueBinned::new(
2880            crate::aes::Aesthetic::Alpha,
2881            n,
2882        ))
2883    }
2884
2885    /// ggplot2's `scale_linewidth_binned()` (#408).
2886    pub fn scale_linewidth_binned(self, n: usize) -> Self {
2887        self.scale_color(crate::scale::values::ScaleValueBinned::new(
2888            crate::aes::Aesthetic::Linewidth,
2889            n,
2890        ))
2891    }
2892
2893    /// ggplot2's `scale_shape_binned()` (#408): one shape per bin.
2894    pub fn scale_shape_binned(self, n: usize) -> Self {
2895        self.scale_color(crate::scale::values::ScaleValueBinned::new(
2896            crate::aes::Aesthetic::Shape,
2897            n,
2898        ))
2899    }
2900
2901    /// ggplot2's `scale_linetype_binned()` (#408): one linetype per bin.
2902    pub fn scale_linetype_binned(self, n: usize) -> Self {
2903        self.scale_color(crate::scale::values::ScaleValueBinned::new(
2904            crate::aes::Aesthetic::Linetype,
2905            n,
2906        ))
2907    }
2908
2909    /// `scale_size_manual(values)`: named levels → point sizes (#408).
2910    pub fn scale_size_manual(self, values: Vec<(&str, f64)>) -> Self {
2911        self.scale_color(crate::scale::values::ScaleValueManual::new(
2912            crate::aes::Aesthetic::Size,
2913            values,
2914        ))
2915    }
2916
2917    /// `scale_alpha_manual(values)`: named levels → opacities (#408).
2918    pub fn scale_alpha_manual(self, values: Vec<(&str, f64)>) -> Self {
2919        self.scale_color(crate::scale::values::ScaleValueManual::new(
2920            crate::aes::Aesthetic::Alpha,
2921            values,
2922        ))
2923    }
2924
2925    /// `scale_linewidth_manual(values)`: named levels → line widths (#408).
2926    pub fn scale_linewidth_manual(self, values: Vec<(&str, f64)>) -> Self {
2927        self.scale_color(crate::scale::values::ScaleValueManual::new(
2928            crate::aes::Aesthetic::Linewidth,
2929            values,
2930        ))
2931    }
2932
2933    /// `scale_size_identity()`: the column already holds point sizes (#408).
2934    pub fn scale_size_identity(self) -> Self {
2935        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2936            crate::aes::Aesthetic::Size,
2937        ))
2938    }
2939
2940    /// `scale_alpha_identity()`: the column already holds opacities (#408).
2941    pub fn scale_alpha_identity(self) -> Self {
2942        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2943            crate::aes::Aesthetic::Alpha,
2944        ))
2945    }
2946
2947    /// `scale_linewidth_identity()`: the column already holds line widths
2948    /// (#408).
2949    pub fn scale_linewidth_identity(self) -> Self {
2950        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2951            crate::aes::Aesthetic::Linewidth,
2952        ))
2953    }
2954
2955    /// `scale_shape_identity()`: the column holds ggplot2 `pch` codes or
2956    /// shape names (`"triangle"`), drawn as the nearest shape (#408).
2957    pub fn scale_shape_identity(self) -> Self {
2958        self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2959            crate::aes::Aesthetic::Shape,
2960        ))
2961    }
2962
2963    pub fn scale_alpha(mut self, s: crate::scale::alpha::ScaleAlphaContinuous) -> Self {
2964        self.scales.push(Box::new(s));
2965        self
2966    }
2967
2968    /// Continuous linewidth scale for the `linewidth` aesthetic (segment,
2969    /// curve, path, line) — see
2970    /// [`ScaleLinewidthContinuous`](crate::scale::linewidth::ScaleLinewidthContinuous).
2971    pub fn scale_linewidth(mut self, s: crate::scale::linewidth::ScaleLinewidthContinuous) -> Self {
2972        self.scales.push(Box::new(s));
2973        self
2974    }
2975
2976    pub fn xlim(self, min: f64, max: f64) -> Self {
2977        self.scale_x_continuous(ScaleContinuous::new().with_limits(min, max))
2978    }
2979
2980    pub fn ylim(self, min: f64, max: f64) -> Self {
2981        self.scale_y_continuous(ScaleContinuous::new().with_limits(min, max))
2982    }
2983
2984    pub fn scale_x_log10(self) -> Self {
2985        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
2986    }
2987
2988    pub fn scale_y_log10(self) -> Self {
2989        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
2990    }
2991
2992    pub fn scale_x_sqrt(self) -> Self {
2993        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
2994    }
2995
2996    pub fn scale_y_sqrt(self) -> Self {
2997        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
2998    }
2999
3000    pub fn scale_x_log2(self) -> Self {
3001        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
3002    }
3003
3004    pub fn scale_y_log2(self) -> Self {
3005        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
3006    }
3007
3008    pub fn scale_x_ln(self) -> Self {
3009        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
3010    }
3011
3012    pub fn scale_y_ln(self) -> Self {
3013        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
3014    }
3015
3016    /// Logit-transformed x axis (for proportions in (0, 1)).
3017    pub fn scale_x_logit(self) -> Self {
3018        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
3019    }
3020
3021    pub fn scale_y_logit(self) -> Self {
3022        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
3023    }
3024
3025    /// Probit-transformed x axis (inverse normal CDF, for proportions in (0, 1)).
3026    pub fn scale_x_probit(self) -> Self {
3027        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
3028    }
3029
3030    pub fn scale_y_probit(self) -> Self {
3031        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
3032    }
3033
3034    /// Sign-preserving pseudo-log x axis (handles zero and negative values).
3035    pub fn scale_x_pseudo_log(self) -> Self {
3036        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
3037    }
3038
3039    pub fn scale_y_pseudo_log(self) -> Self {
3040        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
3041    }
3042
3043    /// Reciprocal (1/x) x axis.
3044    pub fn scale_x_reciprocal(self) -> Self {
3045        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
3046    }
3047
3048    pub fn scale_y_reciprocal(self) -> Self {
3049        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
3050    }
3051
3052    /// Exponential x axis (labels spaced logarithmically).
3053    pub fn scale_x_exp(self) -> Self {
3054        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
3055    }
3056
3057    pub fn scale_y_exp(self) -> Self {
3058        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
3059    }
3060
3061    /// Box–Cox x axis with the given lambda (x > 0).
3062    /// ggplot2's `scale_x_time()`: seconds of day on x, `HH:MM:SS` labels at
3063    /// round time steps (#408).
3064    pub fn scale_x_time(self) -> Self {
3065        self.scale_x_continuous(ScaleContinuous::time())
3066    }
3067
3068    /// ggplot2's `scale_y_time()` — see [`scale_x_time`](Self::scale_x_time).
3069    pub fn scale_y_time(self) -> Self {
3070        self.scale_y_continuous(ScaleContinuous::time())
3071    }
3072
3073    /// ggplot2's `scale_x_binned(n.breaks = n)` (#408): x cut into round
3074    /// bins between about `n` breaks, each value at its bin's midpoint before the stat —
3075    /// `geom_bar()` then draws a histogram, the axis breaks are the edges.
3076    pub fn scale_x_binned(self, n: usize) -> Self {
3077        self.scale_x_continuous(ScaleContinuous::binned(n))
3078    }
3079
3080    /// ggplot2's `scale_y_binned()` — see [`scale_x_binned`](Self::scale_x_binned).
3081    pub fn scale_y_binned(self, n: usize) -> Self {
3082        self.scale_y_continuous(ScaleContinuous::binned(n))
3083    }
3084
3085    pub fn scale_x_boxcox(self, lambda: f64) -> Self {
3086        self.scale_x_continuous(
3087            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
3088        )
3089    }
3090
3091    pub fn scale_y_boxcox(self, lambda: f64) -> Self {
3092        self.scale_y_continuous(
3093            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
3094        )
3095    }
3096
3097    // ─── Faceting ─────────────────────────────────────────────────
3098
3099    pub fn facet_wrap(mut self, var: &str, ncol: Option<usize>) -> Self {
3100        self.facet = Facet::Wrap {
3101            var: var.to_string(),
3102            ncol,
3103            scales: FacetScales::Fixed,
3104            labeller: FacetLabeller::default(),
3105            levels: None,
3106            vertical: false,
3107            as_table: true,
3108            strip_position: crate::facet::StripPosition::Top,
3109            space: FacetSpace::Fixed,
3110        };
3111        self
3112    }
3113
3114    pub fn facet_wrap_free(mut self, var: &str, ncol: Option<usize>, scales: FacetScales) -> Self {
3115        self.facet = Facet::Wrap {
3116            var: var.to_string(),
3117            ncol,
3118            scales,
3119            labeller: FacetLabeller::default(),
3120            levels: None,
3121            vertical: false,
3122            as_table: true,
3123            strip_position: crate::facet::StripPosition::Top,
3124            space: FacetSpace::Fixed,
3125        };
3126        self
3127    }
3128
3129    pub fn facet_wrap_labeller(
3130        mut self,
3131        var: &str,
3132        ncol: Option<usize>,
3133        labeller: FacetLabeller,
3134    ) -> Self {
3135        self.facet = Facet::Wrap {
3136            var: var.to_string(),
3137            ncol,
3138            scales: FacetScales::Fixed,
3139            labeller,
3140            levels: None,
3141            vertical: false,
3142            as_table: true,
3143            strip_position: crate::facet::StripPosition::Top,
3144            space: FacetSpace::Fixed,
3145        };
3146        self
3147    }
3148
3149    /// Fill `facet_wrap` panels column by column (`vertical`, ggplot2's
3150    /// `dir = "v"`) and / or bottom-up (`as_table = false`, ggplot2's
3151    /// `as.table = FALSE`). Call after `facet_wrap*` (#412).
3152    pub fn facet_wrap_dir(mut self, vertical: bool, as_table: bool) -> Self {
3153        if let Facet::Wrap {
3154            vertical: v,
3155            as_table: a,
3156            ..
3157        } = &mut self.facet
3158        {
3159            *v = vertical;
3160            *a = as_table;
3161        }
3162        self
3163    }
3164
3165    /// Draw axes on every facet panel, not just the outer ones (ggplot2's
3166    /// `facet_*(axes = "all" | "all_x" | "all_y", axis.labels = …)`; #412).
3167    pub fn facet_axes(mut self, axes: crate::facet::FacetAxes) -> Self {
3168        self.facet_axes = axes;
3169        self
3170    }
3171
3172    /// Set the strip labeller of the current `facet_wrap` / `facet_grid`
3173    /// (ggplot2's `labeller =`, #412), e.g. `FacetLabeller::Template("n =
3174    /// {value}".into())` or `FacetLabeller::per_var(..)`.
3175    pub fn facet_labeller(mut self, l: FacetLabeller) -> Self {
3176        match &mut self.facet {
3177            Facet::Wrap { labeller, .. } | Facet::Grid { labeller, .. } => *labeller = l,
3178            Facet::None => {}
3179        }
3180        self
3181    }
3182
3183    /// ggplot2 3.5's `facet_wrap(space = "free_x" | "free_y")` (#412):
3184    /// panel widths follow their x range in a single-row wrap (heights their
3185    /// y range in a single column); pair with free scales.
3186    pub fn facet_wrap_space(mut self, space: FacetSpace) -> Self {
3187        if let Facet::Wrap { space: s, .. } = &mut self.facet {
3188            *s = space;
3189        }
3190        self
3191    }
3192
3193    /// Put each `facet_wrap` panel's strip on another side (ggplot2's
3194    /// `strip.position = "bottom" | "left" | "right"`). Call after
3195    /// `facet_wrap*` (#412).
3196    pub fn facet_strip_position(mut self, position: crate::facet::StripPosition) -> Self {
3197        if let Facet::Wrap { strip_position, .. } = &mut self.facet {
3198            *strip_position = position;
3199        }
3200        self
3201    }
3202
3203    /// Fix a `facet_grid`'s row / column order and keep empty ones
3204    /// (ggplot2's factor levels with `drop = FALSE`, #412): `None` keeps the
3205    /// data's own levels for that direction. Call after `facet_grid*`.
3206    pub fn facet_grid_levels<S: AsRef<str>>(
3207        mut self,
3208        rows: Option<&[S]>,
3209        cols: Option<&[S]>,
3210    ) -> Self {
3211        let dedup = |l: &[S]| {
3212            let mut seen = Vec::<String>::new();
3213            for s in l {
3214                if !seen.iter().any(|x| x == s.as_ref()) {
3215                    seen.push(s.as_ref().to_string());
3216                }
3217            }
3218            seen
3219        };
3220        if let Facet::Grid {
3221            row_levels,
3222            col_levels,
3223            ..
3224        } = &mut self.facet
3225        {
3226            *row_levels = rows.map(dedup);
3227            *col_levels = cols.map(dedup);
3228        }
3229        self
3230    }
3231
3232    /// Add an "(all)" row and column pooling the others (ggplot2's
3233    /// `facet_grid(margins = TRUE)`, #412). Stats are computed on the pooled
3234    /// data. Call after `facet_grid*`.
3235    pub fn facet_margins(mut self, on: bool) -> Self {
3236        if let Facet::Grid { margins, .. } = &mut self.facet {
3237            *margins = on;
3238        }
3239        self
3240    }
3241
3242    /// Move `facet_grid` strips to the opposite side (ggplot2's `switch =
3243    /// "x" | "y" | "both"`): column strips below the grid, row strips on its
3244    /// left. Call after `facet_grid*` (#412).
3245    pub fn facet_switch(mut self, switch: crate::facet::FacetSwitch) -> Self {
3246        if let Facet::Grid { switch: s, .. } = &mut self.facet {
3247            *s = switch;
3248        }
3249        self
3250    }
3251
3252    /// Fix a [`facet_wrap`](Self::facet_wrap)'s panel order and keep empty
3253    /// panels (ggplot2's factor levels with `drop = FALSE`, #329): one panel
3254    /// per entry of `levels`, in that order, whether or not any layer has
3255    /// rows for it; rows whose facet value isn't listed are dropped. A value
3256    /// matches a level by its displayed form (`1` for the integer 1). Call
3257    /// after `facet_wrap*`; no effect on other facets.
3258    pub fn facet_levels<S: AsRef<str>>(mut self, levels: &[S]) -> Self {
3259        if let Facet::Wrap { levels: l, .. } = &mut self.facet {
3260            let mut seen = Vec::<String>::new();
3261            for s in levels {
3262                if !seen.iter().any(|x| x == s.as_ref()) {
3263                    seen.push(s.as_ref().to_string());
3264                }
3265            }
3266            *l = Some(seen);
3267        }
3268        self
3269    }
3270
3271    pub fn facet_grid(mut self, row: Option<&str>, col: Option<&str>) -> Self {
3272        self.facet = Facet::Grid {
3273            row_var: row.map(String::from),
3274            col_var: col.map(String::from),
3275            scales: FacetScales::Fixed,
3276            labeller: FacetLabeller::default(),
3277            space: FacetSpace::Fixed,
3278            switch: crate::facet::FacetSwitch::None,
3279            row_levels: None,
3280            col_levels: None,
3281            margins: false,
3282        };
3283        self
3284    }
3285
3286    pub fn facet_grid_free(
3287        mut self,
3288        row: Option<&str>,
3289        col: Option<&str>,
3290        scales: FacetScales,
3291    ) -> Self {
3292        self.facet = Facet::Grid {
3293            row_var: row.map(String::from),
3294            col_var: col.map(String::from),
3295            scales,
3296            labeller: FacetLabeller::default(),
3297            space: FacetSpace::Fixed,
3298            switch: crate::facet::FacetSwitch::None,
3299            row_levels: None,
3300            col_levels: None,
3301            margins: false,
3302        };
3303        self
3304    }
3305
3306    /// `facet_grid` over **multiple** column variables (R's `rows ~ b + c`):
3307    /// the columns become the combination of the given variables' values.
3308    /// Also accepts free scales + proportional `space` for full parity.
3309    pub fn facet_grid_multi(
3310        mut self,
3311        row: Option<&str>,
3312        cols: &[&str],
3313        scales: FacetScales,
3314        space: FacetSpace,
3315    ) -> Self {
3316        let col_var = if cols.len() > 1 {
3317            // Build a synthetic column that is the interaction of the col vars.
3318            let n = self.data.nrows();
3319            let mut combined = Vec::with_capacity(n);
3320            for i in 0..n {
3321                let parts: Vec<String> = cols
3322                    .iter()
3323                    .map(|c| {
3324                        self.data
3325                            .column(c)
3326                            .and_then(|col| col.get(i))
3327                            .map(|v| v.to_group_key())
3328                            .unwrap_or_default()
3329                    })
3330                    .collect();
3331                combined.push(crate::data::Value::Str(parts.join(" . ")));
3332            }
3333            let name = "__facet_cols__".to_string();
3334            self.data.add_column(name.clone(), combined);
3335            Some(name)
3336        } else {
3337            cols.first().map(|s| s.to_string())
3338        };
3339        self.facet = Facet::Grid {
3340            row_var: row.map(String::from),
3341            col_var,
3342            scales,
3343            labeller: FacetLabeller::default(),
3344            space,
3345            switch: crate::facet::FacetSwitch::None,
3346            row_levels: None,
3347            col_levels: None,
3348            margins: false,
3349        };
3350        self
3351    }
3352
3353    /// `facet_grid` with proportional panel sizing (R's `space =`): panels are
3354    /// sized to their data range. Typically paired with free scales.
3355    pub fn facet_grid_space(
3356        mut self,
3357        row: Option<&str>,
3358        col: Option<&str>,
3359        scales: FacetScales,
3360        space: FacetSpace,
3361    ) -> Self {
3362        self.facet = Facet::Grid {
3363            row_var: row.map(String::from),
3364            col_var: col.map(String::from),
3365            scales,
3366            labeller: FacetLabeller::default(),
3367            space,
3368            switch: crate::facet::FacetSwitch::None,
3369            row_levels: None,
3370            col_levels: None,
3371            margins: false,
3372        };
3373        self
3374    }
3375
3376    pub fn facet_grid_labeller(
3377        mut self,
3378        row: Option<&str>,
3379        col: Option<&str>,
3380        labeller: FacetLabeller,
3381    ) -> Self {
3382        self.facet = Facet::Grid {
3383            row_var: row.map(String::from),
3384            col_var: col.map(String::from),
3385            scales: FacetScales::Fixed,
3386            labeller,
3387            space: FacetSpace::Fixed,
3388            switch: crate::facet::FacetSwitch::None,
3389            row_levels: None,
3390            col_levels: None,
3391            margins: false,
3392        };
3393        self
3394    }
3395
3396    // ─── Coordinates ─────────────────────────────────────────────
3397
3398    pub fn coord_flip(mut self) -> Self {
3399        self.coord = Box::new(CoordFlip);
3400        self
3401    }
3402
3403    pub fn coord_fixed(mut self, ratio: f64) -> Self {
3404        self.coord = Box::new(CoordFixed::new(ratio));
3405        self
3406    }
3407
3408    /// Spatial coordinate system (feature `sf`): equal aspect derived from the
3409    /// data extent, so projected geometry keeps its shape. Pair with a `geom_sf`
3410    /// projection (e.g. Mercator) for a conformal map.
3411    #[cfg(feature = "sf")]
3412    pub fn coord_sf(mut self) -> Self {
3413        self.coord = Box::new(crate::coord::sf::CoordSf::new());
3414        self
3415    }
3416
3417    /// Spatial coordinate system with explicit settings (`xlim`/`ylim`/
3418    /// `expand`) — see [`CoordSf`](crate::coord::sf::CoordSf). Used by
3419    /// consumers overlaying a fragment on their own projected basemap: a
3420    /// fixed pixel window via `xlim`/`ylim` and `expand(false)`.
3421    #[cfg(feature = "sf")]
3422    pub fn coord_sf_with(mut self, coord: crate::coord::sf::CoordSf) -> Self {
3423        self.coord = Box::new(coord);
3424        self
3425    }
3426
3427    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/
3428    /// `data-xdomain`/… (see [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
3429    /// Default `true`. A consumer that overlays a rendered fragment
3430    /// (`render_svg_native_at`) on its own basemap — which already has its
3431    /// own root attributes and window — turns this off so the fragment adds
3432    /// none of its own.
3433    pub fn svg_root_data(mut self, on: bool) -> Self {
3434        self.svg_root_data = on;
3435        self
3436    }
3437
3438    /// Add one extra attribute to the root `<svg>` element — a host
3439    /// identifier, an ARIA label, a CSS hook, and so on. Allowed names:
3440    /// `data-*`, `aria-*`, `role`, `id`, `class`, `lang`; anything else, or
3441    /// a name ggplot-rs already writes to the root (`data-plot`,
3442    /// `data-domain`, …, or `data-warnings` when
3443    /// [`svg_warnings_attr`](Self::svg_warnings_attr) is also on), is
3444    /// ignored with a build warning instead of being silently dropped or
3445    /// duplicated. Values are escaped on output. PlotGrid has the same API
3446    /// ([`PlotGrid::svg_attr`](crate::compose::PlotGrid::svg_attr)).
3447    pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
3448        self.root_attrs.push((name.into(), value.into()));
3449        self
3450    }
3451
3452    /// [`svg_attr`](Self::svg_attr) for several attributes at once.
3453    pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
3454        self.root_attrs.extend(attrs);
3455        self
3456    }
3457
3458    /// Emit a `data-warnings` attribute on the root `<svg>` — a JSON array
3459    /// of the build warnings (rows dropped for non-finite positions, an
3460    /// `svg_attr` name rejected, …), `[]` when there are none. Default off,
3461    /// and omitted entirely when off (byte-identical to not calling this).
3462    pub fn svg_warnings_attr(mut self, on: bool) -> Self {
3463        self.svg_warnings_attr = on;
3464        self
3465    }
3466
3467    /// Emit `data-fvalue`/`data-fx` on marks: the value aesthetic's raw
3468    /// data value (y for most geoms, fill for hex/tile) and the x value,
3469    /// each formatted through its scale (currency/locale numbers, ISO or
3470    /// locale dates — [`Scale::format_value`](crate::scale::Scale::format_value))
3471    /// rather than the plain display string `data-value`/`data-x` already
3472    /// carry. `data-fx` is omitted when it would just duplicate `data-x`.
3473    /// Default off, and omitted entirely when off (byte-identical to not
3474    /// calling this).
3475    /// Tag the SVG's non-data elements with stable semantic CSS classes
3476    /// (#465), so a page stylesheet can restyle them: `gg-plot-background`,
3477    /// `gg-panel-background`, `gg-panel-border`, `gg-grid` (+ `gg-grid-major`
3478    /// / `gg-grid-minor`), `gg-axis` (+ `gg-axis-x` / `gg-axis-y` and
3479    /// `gg-axis-line` / `gg-axis-tick` / `gg-axis-text`), `gg-axis-title`
3480    /// (+ `-x` / `-y`), `gg-legend` (+ `gg-legend-title` / `gg-legend-key`
3481    /// / `gg-legend-text` / `gg-legend-background`), `gg-strip` (+
3482    /// `gg-strip-background` / `gg-strip-text`), `gg-title`, `gg-subtitle`,
3483    /// `gg-caption`, `gg-tag`. Data marks always carry `gg-mark gg-<kind>`.
3484    /// Off by default (output unchanged).
3485    pub fn svg_semantic_classes(mut self, on: bool) -> Self {
3486        self.svg_classes = on;
3487        self
3488    }
3489
3490    pub fn svg_formatted_values(mut self, on: bool) -> Self {
3491        self.svg_formatted_values = on;
3492        self
3493    }
3494
3495    /// Give the rendered root `<svg>` an accessible name: a `<title>`
3496    /// written (escaped) as its first child, plus `role="img"` and
3497    /// `aria-labelledby` pointing at that `<title>`'s id — the SVG
3498    /// accessibility practice of naming an image via `role="img"` +
3499    /// `aria-labelledby`/`-describedby` rather than a bare `<title>`,
3500    /// which some screen readers treat as a tooltip instead of a name.
3501    /// Pairs with [`svg_desc`](Self::svg_desc) for a longer description;
3502    /// either may be set alone. Default off (`None`), so output stays
3503    /// byte-identical when this is never called.
3504    pub fn svg_title(mut self, title: impl Into<String>) -> Self {
3505        self.svg_title = Some(title.into());
3506        self
3507    }
3508
3509    /// Give the rendered root `<svg>` an accessible description: a
3510    /// `<desc>` written (escaped) as a first child (after `<title>`, if
3511    /// [`svg_title`](Self::svg_title) is also set), plus `role="img"` and
3512    /// `aria-describedby` pointing at that `<desc>`'s id — e.g. a data
3513    /// summary like "4 regions; highest Bavaria (5.2); 1 without data".
3514    /// Default off (`None`), so output stays byte-identical when this is
3515    /// never called.
3516    pub fn svg_desc(mut self, desc: impl Into<String>) -> Self {
3517        self.svg_desc = Some(desc.into());
3518        self
3519    }
3520
3521    /// Transform the coordinate space at draw time (R's `coord_trans`) — stats are
3522    /// computed on raw data but drawn on non-linear axes. Pass a per-axis
3523    /// [`ScaleTransform`] (e.g. `Some(ScaleTransform::Log10)`), `None` to leave an
3524    /// axis linear.
3525    pub fn coord_trans(mut self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
3526        self.coord = Box::new(crate::coord::trans::CoordTrans::new(x, y));
3527        self
3528    }
3529
3530    /// ggplot2 4.0's name for [`coord_trans`](Self::coord_trans).
3531    pub fn coord_transform(self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
3532        self.coord_trans(x, y)
3533    }
3534
3535    /// Plain longitude (`x`) / latitude (`y`) data with the aspect ratio of
3536    /// the middle latitude (ggplot2's `coord_quickmap()`).
3537    pub fn coord_quickmap(mut self) -> Self {
3538        self.coord = Box::new(crate::coord::map::CoordMap::new(
3539            crate::coord::map::MapProjection::Quick,
3540        ));
3541        self
3542    }
3543
3544    /// Plain longitude / latitude data on a Mercator map (ggplot2's
3545    /// `coord_map("mercator")`); use `geom_sf` + `coord_sf` for other
3546    /// projections.
3547    pub fn coord_map(mut self) -> Self {
3548        self.coord = Box::new(crate::coord::map::CoordMap::new(
3549            crate::coord::map::MapProjection::Mercator,
3550        ));
3551        self
3552    }
3553
3554    /// Use a configured [`CoordCartesian`] (zoom + reverse).
3555    pub fn coord_cartesian_with(mut self, coord: CoordCartesian) -> Self {
3556        self.coord = Box::new(coord);
3557        self
3558    }
3559
3560    /// Name each line at its end instead of drawing a colour legend (#543,
3561    /// R's `directlabels`): every colour group of a line / path / step layer
3562    /// gets its label right of the panel, at the height of its last point,
3563    /// in its colour — pushed apart so labels never overlap, with a short
3564    /// leader when one had to move. Uses the band a right legend would take;
3565    /// a plot with nothing to label this way draws its legend as usual.
3566    pub fn direct_labels(mut self) -> Self {
3567        self.direct_labels = true;
3568        self
3569    }
3570
3571    /// Whether the data layers are clipped to the panel — ggplot2's
3572    /// `coord_*(clip = "on")` (the default) or `clip = "off"` (`false`),
3573    /// which lets marks and labels at the edge draw past it (#411).
3574    pub fn coord_clip(mut self, on: bool) -> Self {
3575        self.clip = on;
3576        self
3577    }
3578
3579    /// Mirror the panel in x and / or y (`coord_cartesian(reverse = …)`).
3580    pub fn coord_reverse(mut self, x: bool, y: bool) -> Self {
3581        self.coord = Box::new(CoordCartesian::new().reverse(x, y));
3582        self
3583    }
3584
3585    /// ggplot2's `coord_radial(start, end, inner.radius)`: a polar coord
3586    /// whose theta runs from `start` to `end` radians (clockwise from 12
3587    /// o'clock) with a hole of `inner_radius` (0–1) — partial circles and
3588    /// donuts.
3589    pub fn coord_radial(mut self, start: f64, end: f64, inner_radius: f64) -> Self {
3590        let mut c = CoordPolar::new();
3591        c.start = start;
3592        c.span = end - start;
3593        c.inner_radius = inner_radius.clamp(0.0, 0.99);
3594        self.coord = Box::new(c);
3595        self
3596    }
3597
3598    /// `coord_trans` on the y-axis only.
3599    pub fn coord_trans_y(self, y: ScaleTransform) -> Self {
3600        self.coord_trans(None, Some(y))
3601    }
3602
3603    /// `coord_trans` on the x-axis only.
3604    pub fn coord_trans_x(self, x: ScaleTransform) -> Self {
3605        self.coord_trans(Some(x), None)
3606    }
3607
3608    /// Zoom into a region without filtering data (unlike xlim/ylim which filter).
3609    pub fn coord_cartesian_zoom(
3610        mut self,
3611        xlim: Option<(f64, f64)>,
3612        ylim: Option<(f64, f64)>,
3613    ) -> Self {
3614        let mut c = CoordCartesian::new();
3615        if let Some((min, max)) = xlim {
3616            c = c.xlim(min, max);
3617        }
3618        if let Some((min, max)) = ylim {
3619            c = c.ylim(min, max);
3620        }
3621        self.coord = Box::new(c);
3622        self
3623    }
3624
3625    pub fn coord_polar(mut self) -> Self {
3626        self.coord = Box::new(CoordPolar::new());
3627        self
3628    }
3629
3630    /// Radar / spider chart coordinates: discrete `x` → spokes, `y` → distance
3631    /// from the centre, straight segments, ring/spoke guides. Pair with
3632    /// `geom_polygon` (closed series) and `geom_point`.
3633    pub fn coord_radar(mut self) -> Self {
3634        self.coord = Box::new(crate::coord::radar::CoordRadar::new());
3635        self
3636    }
3637
3638    pub fn coord_radar_with(mut self, coord: crate::coord::radar::CoordRadar) -> Self {
3639        self.coord = Box::new(coord);
3640        self
3641    }
3642
3643    pub fn coord_polar_with(mut self, coord: CoordPolar) -> Self {
3644        self.coord = Box::new(coord);
3645        self
3646    }
3647
3648    // ─── Theme ───────────────────────────────────────────────────
3649
3650    /// Replace the theme. A `primary_color` set earlier is kept unless the new
3651    /// theme sets its own, so preset/`primary_color` call order doesn't matter.
3652    pub fn theme(mut self, theme: Theme) -> Self {
3653        self.apply_preset(theme);
3654        self
3655    }
3656
3657    fn apply_preset(&mut self, theme: Theme) {
3658        let primary = self.theme.primary;
3659        self.theme = theme;
3660        if self.theme.primary.is_none() {
3661            self.theme.primary = primary;
3662        }
3663    }
3664
3665    /// Rotate the x-axis tick labels by `degrees` (R's
3666    /// `guides(x = guide_axis(angle = ...))` / `axis.text.x = element_text(angle)`).
3667    /// Useful for long category labels. Call after any `theme_*()` preset.
3668    pub fn axis_text_x_angle(mut self, degrees: f64) -> Self {
3669        self.theme.axis_text_x.angle = degrees;
3670        self
3671    }
3672
3673    /// Rotate the y-axis tick labels by `degrees`.
3674    pub fn axis_text_y_angle(mut self, degrees: f64) -> Self {
3675        self.theme.axis_text_y.angle = degrees;
3676        self
3677    }
3678
3679    /// Stagger x-axis tick labels across `n` rows to avoid overlap (R's
3680    /// `guides(x = guide_axis(n.dodge = n))`). `1` = no dodging.
3681    pub fn axis_text_x_dodge(mut self, n: usize) -> Self {
3682        self.theme.axis_text_x_dodge = n.max(1);
3683        self
3684    }
3685
3686    /// Fix the panel's height:width ratio (R's `aspect.ratio`). Call after any
3687    /// `theme_*()` preset.
3688    pub fn aspect_ratio(mut self, ratio: f64) -> Self {
3689        self.theme.aspect_ratio = Some(ratio);
3690        self
3691    }
3692
3693    /// Draw gridlines on top of the data layers (R's `panel.ontop`).
3694    pub fn panel_ontop(mut self) -> Self {
3695        self.theme.panel_ontop = true;
3696        self
3697    }
3698
3699    /// Draw minor tick marks between major ticks (R's `axis.minor.ticks`).
3700    pub fn axis_minor_ticks(mut self) -> Self {
3701        self.theme.axis_minor_ticks = true;
3702        self
3703    }
3704
3705    /// How an outer x-axis label that would cross the SVG edge is handled
3706    /// (B3-1, D6): [`AxisLabelFit::Reserve`](crate::theme::AxisLabelFit::Reserve) (default), `Shift`, or `Clip`
3707    /// (the 0.21 behaviour). Use `Shift` for panels that must stay
3708    /// pixel-aligned with other elements (e.g. a host's own aligned strip).
3709    pub fn axis_text_x_fit(mut self, fit: crate::theme::AxisLabelFit) -> Self {
3710        self.theme.axis_text_x_fit = fit;
3711        self
3712    }
3713
3714    /// Thin crowded x-axis labels in ggplot2's `check.overlap` priority
3715    /// order (B3-1, D5). Off by default.
3716    pub fn axis_text_x_check_overlap(mut self, on: bool) -> Self {
3717        self.theme.axis_text_x_check_overlap = on;
3718        self
3719    }
3720
3721    /// Align title/subtitle/caption to the panel or the whole plot width
3722    /// (R's `plot.title.position`).
3723    pub fn title_position(mut self, pos: crate::theme::TitlePosition) -> Self {
3724        self.theme.title_position = pos;
3725        self
3726    }
3727
3728    /// Corner for the `tag()` label (R's `plot.tag.position`).
3729    pub fn tag_position(mut self, pos: crate::theme::TagPosition) -> Self {
3730        self.theme.tag_position = pos;
3731        self
3732    }
3733
3734    /// Force the legend key layout direction (R's `legend.direction`).
3735    pub fn legend_direction(mut self, dir: crate::theme::LegendDirection) -> Self {
3736        self.theme.legend_direction = Some(dir);
3737        self
3738    }
3739
3740    /// Set the brand/primary color used as the default for single-series geoms
3741    /// that have no color/fill aesthetic mapped. Composes with any theme — one
3742    /// render process can serve different tenants' brands at render time.
3743    /// Place the legend inside the panel at panel-relative coordinates
3744    /// (0..1, 0..1) — `(0,0)` bottom-left, `(1,1)` top-right (R's
3745    /// `legend.position = c(x, y)`).
3746    pub fn legend_position_inside(mut self, x: f64, y: f64) -> Self {
3747        self.theme.legend_position = crate::theme::LegendPosition::Inside(x, y);
3748        self
3749    }
3750
3751    /// Set the legend position (R's `legend.position`, e.g. `Top`/`Bottom`).
3752    pub fn legend_position(mut self, pos: crate::theme::LegendPosition) -> Self {
3753        self.theme.legend_position = pos;
3754        self
3755    }
3756
3757    /// Move a [`Right`](crate::theme::LegendPosition::Right) legend to
3758    /// `Bottom` (drawn horizontally) when it would take more than `share`
3759    /// (0..1) of the panel's width — the width the panel has with no legend
3760    /// at all (#287). The band is roughly fixed in size, so on a narrow
3761    /// render it can take most of the panel; a render wide enough keeps
3762    /// `Right`, unchanged. Off by default; no effect on any other position.
3763    pub fn legend_bottom_when_narrow(mut self, share: f64) -> Self {
3764        self.legend_bottom_share = Some(share);
3765        self
3766    }
3767
3768    /// Put the legend inside the panel, in an empty corner (#332): after
3769    /// layout, each corner's real legend box is tested against the drawn
3770    /// marks (polygons, lines, points, labels, corner furniture such as a
3771    /// scale bar), and the first corner it overlaps nothing in wins, in the
3772    /// order bottom-right, bottom-left, top-right, top-left. If every
3773    /// corner is taken the legend goes outside, `Top` or `Right`, whichever
3774    /// leaves the data area (e.g. a `coord_sf` map) larger. The choice is
3775    /// written as the root `data-legend-at` attribute (`inside-top-left`,
3776    /// `top`, …). Single-panel plots only; a faceted plot keeps its legend
3777    /// position. See [`legend_inside_auto_with`](Self::legend_inside_auto_with).
3778    pub fn legend_inside_auto(self) -> Self {
3779        self.legend_inside_auto_with(&crate::theme::LegendCorner::ALL, None)
3780    }
3781
3782    /// [`legend_inside_auto`](Self::legend_inside_auto) with the candidate
3783    /// `corners` (in preference order) and an outside `fallback`
3784    /// (`Top`/`Right`/`Bottom`/`Left`; `None` = the larger of `Top` and
3785    /// `Right`).
3786    pub fn legend_inside_auto_with(
3787        mut self,
3788        corners: &[crate::theme::LegendCorner],
3789        fallback: Option<crate::theme::LegendPosition>,
3790    ) -> Self {
3791        use crate::theme::LegendPosition as P;
3792        let mut c = [None; 4];
3793        for (slot, corner) in c.iter_mut().zip(corners) {
3794            *slot = Some(*corner);
3795        }
3796        let fallback = match fallback {
3797            Some(P::Top) => Some(LegendSide::Top),
3798            Some(P::Right) => Some(LegendSide::Right),
3799            Some(P::Bottom) => Some(LegendSide::Bottom),
3800            Some(P::Left) => Some(LegendSide::Left),
3801            _ => None,
3802        };
3803        self.legend_auto = Some(LegendAuto {
3804            corners: c,
3805            fallback,
3806        });
3807        self
3808    }
3809
3810    pub fn primary_color(mut self, color: (u8, u8, u8)) -> Self {
3811        self.theme.primary = Some(color);
3812        self
3813    }
3814
3815    pub fn theme_minimal(mut self) -> Self {
3816        self.apply_preset(crate::theme::presets::theme_minimal());
3817        self
3818    }
3819
3820    /// ggplot2's `theme_test()`: `theme_bw` without gridlines (#413).
3821    pub fn theme_test(mut self) -> Self {
3822        self.apply_preset(crate::theme::presets::theme_test());
3823        self
3824    }
3825
3826    pub fn theme_bw(mut self) -> Self {
3827        self.apply_preset(crate::theme::presets::theme_bw());
3828        self
3829    }
3830
3831    pub fn theme_gray(mut self) -> Self {
3832        self.apply_preset(crate::theme::presets::theme_gray());
3833        self
3834    }
3835
3836    pub fn theme_classic(mut self) -> Self {
3837        self.apply_preset(crate::theme::presets::theme_classic());
3838        self
3839    }
3840
3841    /// Apply the publication-ready `theme_pubr()` (ggpubr style).
3842    pub fn theme_pubr(mut self) -> Self {
3843        self.apply_preset(crate::theme::presets::theme_pubr());
3844        self
3845    }
3846
3847    pub fn theme_linedraw(mut self) -> Self {
3848        self.apply_preset(crate::theme::presets::theme_linedraw());
3849        self
3850    }
3851
3852    pub fn theme_light(mut self) -> Self {
3853        self.apply_preset(crate::theme::presets::theme_light());
3854        self
3855    }
3856
3857    pub fn theme_dark(mut self) -> Self {
3858        self.apply_preset(crate::theme::presets::theme_dark());
3859        self
3860    }
3861
3862    pub fn theme_void(mut self) -> Self {
3863        self.apply_preset(crate::theme::presets::theme_void());
3864        self
3865    }
3866
3867    /// Apply incremental theme modifications on top of the current theme.
3868    /// Like R's `+ theme(axis.text.x = element_text(...))`.
3869    pub fn theme_update(mut self, update: crate::theme::ThemeUpdate) -> Self {
3870        self.theme = self.theme.update(update);
3871        self
3872    }
3873
3874    /// ggplot2's `%+replace%`: the elements `update` sets replace the
3875    /// current ones whole (#413) — the same as [`theme_update`](Self::theme_update),
3876    /// named for parity. For ggplot2's merging `+ theme(..)` (only the given
3877    /// properties change) use [`theme_with`](Self::theme_with).
3878    pub fn theme_replace(self, update: crate::theme::ThemeUpdate) -> Self {
3879        self.theme_update(update)
3880    }
3881
3882    /// Change single theme properties in place (ggplot2's merging `+ theme(
3883    /// axis.text.x = element_text(size = 14))`, #413), e.g.
3884    /// `.theme_with(|t| t.axis_text_x.size = 14.0)`.
3885    pub fn theme_with(mut self, f: impl FnOnce(&mut Theme)) -> Self {
3886        f(&mut self.theme);
3887        self
3888    }
3889
3890    // ─── Guides ──────────────────────────────────────────────────
3891
3892    /// Configure legend guide (title, ncol, reverse).
3893    pub fn guides(mut self, mut guide: crate::guide::config::GuideLegend) -> Self {
3894        // Keep per-aesthetic settings made earlier (`guide_none` /
3895        // `guide_title` / `guide_reverse` / `guide_colourbar`) unless the
3896        // new guide sets its own.
3897        if guide.hidden.is_empty() {
3898            guide.hidden = std::mem::take(&mut self.guide_legend.hidden);
3899        }
3900        if guide.titles.is_empty() {
3901            guide.titles = std::mem::take(&mut self.guide_legend.titles);
3902        }
3903        if guide.reversed.is_empty() {
3904            guide.reversed = std::mem::take(&mut self.guide_legend.reversed);
3905        }
3906        if guide.colourbars.is_empty() {
3907            guide.colourbars = std::mem::take(&mut self.guide_legend.colourbars);
3908        }
3909        if guide.overrides.is_empty() {
3910            guide.overrides = std::mem::take(&mut self.guide_legend.overrides);
3911        }
3912        if guide.bins.is_empty() {
3913            guide.bins = std::mem::take(&mut self.guide_legend.bins);
3914        }
3915        if guide.plain_keys.is_empty() {
3916            guide.plain_keys = std::mem::take(&mut self.guide_legend.plain_keys);
3917        }
3918        if guide.custom.is_empty() {
3919            guide.custom = std::mem::take(&mut self.guide_legend.custom);
3920        }
3921        if guide.positions.is_empty() {
3922            guide.positions = std::mem::take(&mut self.guide_legend.positions);
3923        }
3924        self.guide_legend = guide;
3925        self
3926    }
3927
3928    // ─── Labels ──────────────────────────────────────────────────
3929
3930    pub fn labs(mut self, labels: Labels) -> Self {
3931        if labels.title.is_some() {
3932            self.labels.title = labels.title;
3933        }
3934        if labels.subtitle.is_some() {
3935            self.labels.subtitle = labels.subtitle;
3936        }
3937        if labels.x.is_some() {
3938            self.labels.x = labels.x;
3939        }
3940        if labels.y.is_some() {
3941            self.labels.y = labels.y;
3942        }
3943        if labels.caption.is_some() {
3944            self.labels.caption = labels.caption;
3945        }
3946        if labels.tag.is_some() {
3947            self.labels.tag = labels.tag;
3948        }
3949        self
3950    }
3951
3952    pub fn title(mut self, title: &str) -> Self {
3953        self.labels.title = Some(title.to_string());
3954        self
3955    }
3956
3957    /// Corner tag label (R's `labs(tag = ...)`), drawn at the top-left — handy
3958    /// for labelling figure panels ("A", "B", …).
3959    pub fn tag(mut self, tag: &str) -> Self {
3960        self.labels.tag = Some(tag.to_string());
3961        self
3962    }
3963
3964    pub fn subtitle(mut self, subtitle: &str) -> Self {
3965        self.labels.subtitle = Some(subtitle.to_string());
3966        self
3967    }
3968
3969    pub fn xlab(mut self, label: &str) -> Self {
3970        self.labels.x = Some(label.to_string());
3971        self
3972    }
3973
3974    pub fn ylab(mut self, label: &str) -> Self {
3975        self.labels.y = Some(label.to_string());
3976        self
3977    }
3978
3979    pub fn caption(mut self, caption: &str) -> Self {
3980        self.labels.caption = Some(caption.to_string());
3981        self
3982    }
3983
3984    // ─── Annotations ──────────────────────────────────────────────
3985
3986    /// Add an annotation to the plot.
3987    pub fn annotate(mut self, annotation: Annotation) -> Self {
3988        self.annotations.push(annotation);
3989        self
3990    }
3991
3992    /// Add a text annotation at data coordinates.
3993    pub fn annotate_text(self, label: &str, x: f64, y: f64) -> Self {
3994        self.annotate(Annotation::text(label, x, y))
3995    }
3996
3997    /// Add a rectangle annotation at data coordinates.
3998    pub fn annotate_rect(self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
3999        self.annotate(Annotation::rect(xmin, xmax, ymin, ymax))
4000    }
4001
4002    /// Add a segment annotation between data coordinates.
4003    pub fn annotate_segment(self, x: f64, y: f64, xend: f64, yend: f64) -> Self {
4004        self.annotate(Annotation::segment(x, y, xend, yend))
4005    }
4006
4007    /// Log-10 tick marks on the panel `sides` (`"bl"`, `"trbl"`, …) —
4008    /// ggplot2's `annotation_logticks()`; pair with `scale_x_log10()` etc.
4009    pub fn annotation_logticks(self, sides: &str) -> Self {
4010        self.annotate(Annotation::logticks(sides))
4011    }
4012
4013    /// An encoded PNG / JPEG image over a data rectangle (`annotation_raster`);
4014    /// `f64::INFINITY` / `NEG_INFINITY` bounds mean the panel edges.
4015    pub fn annotation_raster(
4016        self,
4017        image: Vec<u8>,
4018        xmin: f64,
4019        xmax: f64,
4020        ymin: f64,
4021        ymax: f64,
4022    ) -> Self {
4023        self.annotate(Annotation::raster(image, xmin, xmax, ymin, ymax))
4024    }
4025
4026    /// An RGBA pixel buffer (`width × height × 4`, row-major) over a data
4027    /// rectangle (`annotation_raster` with a colour matrix; feature `png`).
4028    #[cfg(feature = "png")]
4029    pub fn annotation_raster_rgba(
4030        self,
4031        (width, height): (u32, u32),
4032        rgba: &[u8],
4033        (xmin, xmax, ymin, ymax): (f64, f64, f64, f64),
4034    ) -> Self {
4035        use image::ImageEncoder;
4036        let mut png = Vec::new();
4037        let ok = image::codecs::png::PngEncoder::new(&mut png)
4038            .write_image(rgba, width, height, image::ColorType::Rgba8)
4039            .is_ok();
4040        if !ok {
4041            return self;
4042        }
4043        self.annotation_raster(png, xmin, xmax, ymin, ymax)
4044    }
4045
4046    /// Draw another plot as an inset into a data rectangle — ggplot2's
4047    /// `annotation_custom(ggplotGrob(p), xmin, xmax, ymin, ymax)`.
4048    /// `f64::INFINITY` / `NEG_INFINITY` bounds mean the panel edges.
4049    pub fn annotation_custom(
4050        self,
4051        inset: GGPlot,
4052        xmin: f64,
4053        xmax: f64,
4054        ymin: f64,
4055        ymax: f64,
4056    ) -> Self {
4057        self.annotate(Annotation::inset(inset, xmin, xmax, ymin, ymax))
4058    }
4059
4060    /// Default [`Locale`](crate::locale::Locale) for the plot's axis and
4061    /// legend labels: every continuous position / colour / size / alpha scale
4062    /// labels its default breaks with the locale's decimal and thousands marks
4063    /// (`1.000`, `2,5` in de-DE), and date/datetime scales use its month names
4064    /// and date formats (`Okt. 2026`, `15. Okt. 2026`). A scale's own
4065    /// `with_locale` and custom `label_*` formatters take precedence.
4066    /// Without this call labels are unchanged (`.` decimal mark, no grouping,
4067    /// ISO dates).
4068    ///
4069    /// ```
4070    /// use ggplot_rs::prelude::*;
4071    /// let svg = GGPlot::new(vec![
4072    ///         ("x".to_string(), vec![Value::Float(0.0), Value::Float(3000.0)]),
4073    ///         ("y".to_string(), vec![Value::Float(0.5), Value::Float(2.5)]),
4074    ///     ])
4075    ///     .aes(Aes::new().x("x").y("y"))
4076    ///     .geom_point()
4077    ///     .locale(Locale::from_tag("de-DE"))
4078    ///     .render_svg_native()
4079    ///     .unwrap();
4080    /// assert!(svg.contains(">1.000<") && svg.contains(">1,5<"));
4081    /// ```
4082    pub fn locale(mut self, locale: crate::locale::Locale) -> Self {
4083        self.locale = Some(locale);
4084        self
4085    }
4086
4087    // ─── Build and Render ────────────────────────────────────────
4088
4089    /// Build the plot without rendering, returning errors on validation failure.
4090    pub fn try_build(self) -> Result<crate::build::BuiltPlot, GGError> {
4091        PlotBuilder::build(self)
4092    }
4093
4094    /// Build the plot without rendering (analogous to R's ggplot_build()).
4095    /// Returns the fully computed BuiltPlot with layer data ready for inspection.
4096    /// Panics on validation errors — use `try_build()` for error handling.
4097    pub fn build(self) -> crate::build::BuiltPlot {
4098        self.try_build().expect("plot build failed")
4099    }
4100
4101    /// Build and save the plot to a file. Format determined by extension.
4102    /// (Requires the `plotters` feature, on by default; native only — wasm has
4103    /// no filesystem/plotters backend.)
4104    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4105    pub fn save(self, path: &str) -> Result<(), GGError> {
4106        self.save_with_size(path, 800, 600)
4107    }
4108
4109    /// Build and save with custom dimensions. (Feature `plotters`; native only.)
4110    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4111    pub fn save_with_size(self, path: &str, w: u32, h: u32) -> Result<(), GGError> {
4112        // Determine backend from file extension
4113        let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
4114        #[cfg(feature = "pdf")]
4115        if ext == "pdf" {
4116            let bytes = self.render_pdf_with_size(w, h)?;
4117            return std::fs::write(path, bytes).map_err(|e| GGError::Render(e.into()));
4118        }
4119        let (built, layout) = self.prepare(w, h)?;
4120
4121        match ext.as_str() {
4122            "svg" => {
4123                let backend = plotters::prelude::SVGBackend::new(path, (w, h));
4124                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4125            }
4126            "png" | "bmp" | "gif" | "jpeg" | "jpg" | "tiff" => {
4127                let backend = plotters::prelude::BitMapBackend::new(path, (w, h));
4128                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4129            }
4130            _ => {
4131                return Err(GGError::UnsupportedFormat(ext));
4132            }
4133        }
4134
4135        Ok(())
4136    }
4137
4138    /// Render the plot to an in-memory SVG document (default 800x600).
4139    ///
4140    /// Unlike [`save`](Self::save), this writes nothing to disk — handy for
4141    /// serving charts from a web/MCP service. Requires the `plotters` feature
4142    /// (on by default); without it use [`render_svg_native`](Self::render_svg_native).
4143    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4144    pub fn render_svg(self) -> Result<String, GGError> {
4145        self.render_svg_with_size(800, 600)
4146    }
4147
4148    /// Render the plot to an in-memory SVG document with custom dimensions.
4149    /// (Feature `plotters`; native only — on wasm or without `plotters` use
4150    /// [`render_svg_native_with_size`](Self::render_svg_native_with_size).)
4151    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4152    pub fn render_svg_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
4153        let (built, layout) = self.prepare(w, h)?;
4154        let mut buf = String::new();
4155        {
4156            let backend = plotters::prelude::SVGBackend::with_string(&mut buf, (w, h));
4157            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4158        }
4159        Ok(buf)
4160    }
4161
4162    /// Render to SVG through the self-contained [`SvgBackend`](crate::render::svg_backend::SvgBackend)
4163    /// — a plotters-free path that drives the same `PlotRenderer`, proving the
4164    /// `DrawBackend` abstraction (and needing no glyph rasterization).
4165    pub fn render_svg_native(self) -> Result<String, GGError> {
4166        self.render_svg_native_with_size(800, 600)
4167    }
4168
4169    /// [`render_svg_native`](Self::render_svg_native) with an explicit size.
4170    ///
4171    /// The root `<svg>` carries `data-plot="x y w h"` (the panel rect) and the
4172    /// trained position domains (`data-domain`, `data-xdomain`, `data-ydomain`,
4173    /// `data-xlevels`, `data-ylevels` — see
4174    /// [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
4175    /// Hoverable marks carry `data-x`, `data-series` and `data-value`.
4176    pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
4177        Ok(self.render_native(w, h)?.0.finish())
4178    }
4179
4180    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
4181    /// but also returns the build warnings (rows dropped for non-finite
4182    /// positions, layers whose stat produced no data, …) — see
4183    /// [`BuiltPlot::warnings`](crate::build::BuiltPlot::warnings).
4184    pub fn render_svg_native_with_warnings(
4185        self,
4186        w: u32,
4187        h: u32,
4188    ) -> Result<(String, Vec<String>), GGError> {
4189        let (backend, warnings, _) = self.render_native(w, h)?;
4190        Ok((backend.finish(), warnings))
4191    }
4192
4193    /// Render a `w`×`h` chart as a *nested* `<svg x=.. y=.. width=.. height=..
4194    /// viewBox="0 0 w h">` fragment for composition into a larger SVG (a
4195    /// dashboard): no `xmlns` (inherited from the parent), positioned at
4196    /// `(x, y)` in the parent's user space. No string surgery needed:
4197    ///
4198    /// ```ignore
4199    /// let mut page = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="900" height="400">"#);
4200    /// page += &plot_a.render_svg_native_at(0.0, 0.0, 450, 400)?;
4201    /// page += &plot_b.render_svg_native_at(450.0, 0.0, 450, 400)?;
4202    /// page += "</svg>";
4203    /// ```
4204    pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
4205        Ok(self.render_native(w, h)?.0.finish_fragment(x, y))
4206    }
4207
4208    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
4209    /// but also returns the panel rect in pixels `[x, y, w, h]` — enough to
4210    /// overlay a WebGL/canvas layer that draws marks in data coordinates.
4211    pub fn render_svg_area_with_size(self, w: u32, h: u32) -> Result<(String, [f64; 4]), GGError> {
4212        let (backend, _, pa) = self.render_native(w, h)?;
4213        Ok((backend.finish(), [pa.x, pa.y, pa.width, pa.height]))
4214    }
4215
4216    /// Shared native-SVG pipeline: build, lay out, render into an
4217    /// [`SvgBackend`](crate::render::svg_backend::SvgBackend) (not yet
4218    /// finished), returning it with the build warnings and the panel rect.
4219    fn render_native(
4220        self,
4221        w: u32,
4222        h: u32,
4223    ) -> Result<
4224        (
4225            crate::render::svg_backend::SvgBackend,
4226            Vec<String>,
4227            crate::render::Rect,
4228        ),
4229        GGError,
4230    > {
4231        let svg_root_data = self.svg_root_data;
4232        let root_attrs = self.root_attrs.clone();
4233        let svg_warnings_attr = self.svg_warnings_attr;
4234        let svg_formatted_values = self.svg_formatted_values;
4235        let svg_title = self.svg_title.clone();
4236        let svg_desc = self.svg_desc.clone();
4237        let (built, layout) = self.prepare(w, h)?;
4238        let pa = layout.plot_area.clone();
4239        let mut backend = crate::render::svg_backend::SvgBackend::new(w, h, pa.clone());
4240        backend.set_formatted_values(svg_formatted_values);
4241        backend.set_svg_title(svg_title.clone());
4242        backend.set_svg_desc(svg_desc.clone());
4243        let existing_root_attrs = if svg_root_data {
4244            let attrs = crate::render::svg_backend::root_data_attrs(&built);
4245            backend.set_root_attrs(attrs.clone());
4246            // `data-plot` itself is a literal in `root_open`, not part of
4247            // `root_data_attrs`'s output, but it is written whenever
4248            // `svg_root_data` is on — reserve it too.
4249            let mut reserved = attrs;
4250            // `data-viewport`/`data-panels` likewise come from the backend
4251            // (a letterboxing coord / fixed-aspect facets).
4252            for name in ["data-plot", "data-viewport", "data-panels"] {
4253                reserved.push((name.to_string(), String::new()));
4254            }
4255            reserved
4256        } else {
4257            backend.without_plot_attr();
4258            Vec::new()
4259        };
4260        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4261        let mut warnings = built.warnings;
4262        warnings.extend(backend.take_warnings());
4263
4264        let mut reserved = existing_root_attrs;
4265        if svg_warnings_attr {
4266            reserved.push(("data-warnings".to_string(), String::new()));
4267        }
4268        // #255: `role`/`aria-labelledby`/`aria-describedby` are written
4269        // directly by `SvgBackend::root_open` when a title/desc was set —
4270        // reserve them so a colliding `svg_attr` call is dropped with a
4271        // warning instead of duplicating the attribute.
4272        if svg_title.is_some() || svg_desc.is_some() {
4273            reserved.push(("role".to_string(), String::new()));
4274        }
4275        if svg_title.is_some() {
4276            reserved.push(("aria-labelledby".to_string(), String::new()));
4277        }
4278        if svg_desc.is_some() {
4279            reserved.push(("aria-describedby".to_string(), String::new()));
4280        }
4281        let extra = crate::render::svg_backend::validate_root_attrs(
4282            &root_attrs,
4283            &reserved,
4284            "plot",
4285            &mut warnings,
4286        );
4287        backend.extend_root_attrs(extra);
4288        if svg_warnings_attr {
4289            backend.extend_root_attrs(vec![(
4290                "data-warnings".to_string(),
4291                crate::render::svg_backend::warnings_json(&warnings),
4292            )]);
4293        }
4294        Ok((backend, warnings, pa))
4295    }
4296
4297    /// Render to a raw RGBA pixel buffer via the self-contained raster
4298    /// [`PixelBackend`](crate::render::pixel_backend::PixelBackend) (feature
4299    /// `canvas`) — fast for large-N and wasm-compatible. Returns `(w, h, rgba)`,
4300    /// ready for a `<canvas>` `putImageData`.
4301    #[cfg(feature = "canvas")]
4302    pub fn render_rgba_with_size(self, w: u32, h: u32) -> Result<(u32, u32, Vec<u8>), GGError> {
4303        let (built, layout) = self.prepare(w, h)?;
4304        let mut backend =
4305            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
4306        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4307        let (ow, oh) = backend.dimensions();
4308        Ok((ow, oh, backend.into_rgba()))
4309    }
4310
4311    /// Render to a vector PDF (feature `pdf`, #467): one page of `w` × `h`
4312    /// points (1 px = 1 pt), real selectable text in the bundled DejaVu
4313    /// fonts (embedded as subsets).
4314    #[cfg(feature = "pdf")]
4315    pub fn render_pdf_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
4316        let (built, layout) = self.prepare(w, h)?;
4317        let mut backend =
4318            crate::render::pdf_backend::PdfBackend::new(w, h, layout.plot_area.clone());
4319        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4320        backend.finish().map_err(GGError::Render)
4321    }
4322
4323    /// [`render_pdf_with_size`](Self::render_pdf_with_size) at 800 × 600.
4324    #[cfg(feature = "pdf")]
4325    pub fn render_pdf(self) -> Result<Vec<u8>, GGError> {
4326        self.render_pdf_with_size(800, 600)
4327    }
4328
4329    /// Like [`render_rgba_with_size`](Self::render_rgba_with_size), but also
4330    /// returns the panel rect in pixels `[x, y, w, h]` — enough to map a canvas
4331    /// pixel back to data coordinates for interactive hover.
4332    #[cfg(feature = "canvas")]
4333    pub fn render_rgba_area_with_size(
4334        self,
4335        w: u32,
4336        h: u32,
4337    ) -> Result<(Vec<u8>, [f64; 4]), GGError> {
4338        let (built, layout) = self.prepare(w, h)?;
4339        let pa = layout.plot_area.clone();
4340        let mut backend = crate::render::pixel_backend::PixelBackend::new(w, h, pa.clone());
4341        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4342        Ok((backend.into_rgba(), [pa.x, pa.y, pa.width, pa.height]))
4343    }
4344
4345    /// Render to PNG bytes via the raster [`PixelBackend`](crate::render::pixel_backend::PixelBackend)
4346    /// (feature `canvas`). Unlike [`render_png`](Self::render_png) this needs no
4347    /// plotters bitmap backend, so it also works on wasm.
4348    #[cfg(feature = "canvas")]
4349    pub fn render_png_raster_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
4350        let (built, layout) = self.prepare(w, h)?;
4351        let mut backend =
4352            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
4353        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4354        backend.into_png().map_err(GGError::Render)
4355    }
4356
4357    /// Render the plot to in-memory PNG bytes (default 800x600).
4358    ///
4359    /// Returns a fully-encoded PNG, ready to write to an HTTP response or
4360    /// embed as a data URI — no temp files involved. Requires the `plotters`
4361    /// feature (on by default); see also `render_png_raster_with_size`
4362    /// (feature `canvas`).
4363    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4364    pub fn render_png(self) -> Result<Vec<u8>, GGError> {
4365        self.render_png_with_size(800, 600)
4366    }
4367
4368    /// Render the plot to in-memory PNG bytes with custom dimensions. (Feature
4369    /// `plotters`; native only — PNG needs the plotters bitmap backend.)
4370    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4371    pub fn render_png_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
4372        let (built, layout) = self.prepare(w, h)?;
4373
4374        // plotters' BitMapBackend draws into a raw RGB buffer; we then encode
4375        // that buffer to PNG via the `image` crate.
4376        let mut rgb = vec![0u8; (w as usize) * (h as usize) * 3];
4377        {
4378            let backend = plotters::prelude::BitMapBackend::with_buffer(&mut rgb, (w, h));
4379            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4380        }
4381
4382        let img = image::RgbImage::from_raw(w, h, rgb).ok_or_else(|| {
4383            GGError::Render(RenderError::BackendError(
4384                "PNG buffer size mismatch".to_string(),
4385            ))
4386        })?;
4387        let mut out = std::io::Cursor::new(Vec::new());
4388        img.write_to(&mut out, image::ImageOutputFormat::Png)
4389            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
4390        Ok(out.into_inner())
4391    }
4392
4393    /// Shared pipeline: build the plot, apply label overrides, compute layout.
4394    pub(crate) fn prepare(
4395        self,
4396        w: u32,
4397        h: u32,
4398    ) -> Result<(crate::build::BuiltPlot, PlotLayout), GGError> {
4399        let (mut built, meta) = self.build_for_render()?;
4400        let layout = Self::layout_built(&mut built, &meta, w, h);
4401        Ok((built, layout))
4402    }
4403
4404    /// The size-independent half of [`prepare`](Self::prepare): build the plot,
4405    /// resolve theme inheritance and apply axis-label overrides.
4406    pub(crate) fn build_for_render(self) -> Result<(crate::build::BuiltPlot, RenderMeta), GGError> {
4407        let plot = self;
4408
4409        let has_title = plot.labels.title.is_some();
4410        let has_subtitle = plot.labels.subtitle.is_some();
4411        let has_caption = plot.labels.caption.is_some();
4412        let has_legend = plot.has_legend_mapping();
4413        let legend_bottom_share = plot.legend_bottom_share;
4414        let legend_auto = plot.legend_auto;
4415        let x_label = plot.labels.x.clone();
4416        let y_label = plot.labels.y.clone();
4417        let guide_titles = plot.guide_legend.titles.clone();
4418
4419        let mut built = PlotBuilder::build(plot)?;
4420
4421        // #409: per-aesthetic legend titles name their scales.
4422        for (aes, title) in &guide_titles {
4423            if let Some(s) = built.scales.get_mut(aes) {
4424                s.set_name(title);
4425            }
4426        }
4427
4428        // Resolve R-style theme inheritance (root `text` → child text elements).
4429        built.theme.resolve_inheritance();
4430
4431        // #411: a fixed-aspect coord (coord_fixed / coord_sf / coord_map /
4432        // coord_quickmap) shrinks the single panel to its aspect — the
4433        // background, grid and axes hug the data, as in ggplot2 — instead
4434        // of letterboxing the data inside a full-size panel.
4435        if built.facet.is_none() && built.theme.aspect_ratio.is_none() {
4436            if let Some(a) = built
4437                .coord
4438                .fixed_aspect()
4439                .filter(|a| a.is_finite() && *a > 0.0)
4440            {
4441                built.theme.aspect_ratio = Some(a);
4442            }
4443        }
4444
4445        // Apply user label overrides to scales
4446        if let Some(ref label) = x_label {
4447            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::X) {
4448                s.set_name(label);
4449            }
4450        }
4451        if let Some(ref label) = y_label {
4452            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::Y) {
4453                s.set_name(label);
4454            }
4455        }
4456
4457        Ok((
4458            built,
4459            RenderMeta {
4460                has_title,
4461                has_subtitle,
4462                has_caption,
4463                has_legend,
4464                legend_bottom_share,
4465                legend_auto,
4466            },
4467        ))
4468    }
4469
4470    /// The size-dependent half of [`prepare`](Self::prepare): auto-tune axis
4471    /// labels for `w`×`h` and compute the layout.
4472    pub(crate) fn layout_built(
4473        built: &mut crate::build::BuiltPlot,
4474        meta: &RenderMeta,
4475        w: u32,
4476        h: u32,
4477    ) -> PlotLayout {
4478        match meta.legend_auto {
4479            Some(auto) if meta.has_legend && built.panels.is_empty() => {
4480                Self::layout_legend_auto(built, meta, auto, w, h)
4481            }
4482            _ => Self::layout_built_inner(built, meta, w, h),
4483        }
4484    }
4485
4486    /// #332: try each candidate corner for an inside legend against the
4487    /// marks a dry render draws; fall back outside when none is free.
4488    fn layout_legend_auto(
4489        built: &mut crate::build::BuiltPlot,
4490        meta: &RenderMeta,
4491        auto: LegendAuto,
4492        w: u32,
4493        h: u32,
4494    ) -> PlotLayout {
4495        use crate::render::probe::Probe;
4496        use crate::theme::LegendPosition as P;
4497        let total = crate::render::Rect {
4498            x: 0.0,
4499            y: 0.0,
4500            width: w as f64,
4501            height: h as f64,
4502        };
4503        // `layout_built_inner` may rotate axis labels and push warnings:
4504        // every trial starts from the same state.
4505        let (theme0, n_warnings) = (built.theme.clone(), built.warnings.len());
4506        let reset = |built: &mut crate::build::BuiltPlot, pos: P| {
4507            built.theme = theme0.clone();
4508            built.theme.legend_position = pos;
4509            built.warnings.truncate(n_warnings);
4510        };
4511
4512        reset(built, P::Inside(1.0, 0.0));
4513        let layout = Self::layout_built_inner(built, meta, w, h);
4514        let pa = layout.plot_area.clone();
4515        let mut marks = Probe::new(pa.clone(), total.clone());
4516        for layer in built.layers.iter().filter(|l| l.data.nrows() > 0) {
4517            let _ = layer.geom.draw(
4518                &layer.data,
4519                built.coord.as_ref(),
4520                &built.scales,
4521                &built.theme,
4522                &mut marks,
4523            );
4524        }
4525        for corner in auto.corners.iter().flatten() {
4526            built.theme.legend_position = corner.inside();
4527            let mut legend = Probe::new(pa.clone(), total.clone());
4528            let drawn = crate::guide::legend::draw_legend_planned(
4529                &built.scales,
4530                &built.theme,
4531                &pa,
4532                pa.width,
4533                &mut legend,
4534                &built.guide_legend,
4535                &built.suppressed_aes,
4536                &built.legend_plans,
4537            );
4538            let Some((x0, y0, x1, y1)) = legend.extent().filter(|_| drawn.is_ok()) else {
4539                continue;
4540            };
4541            const PAD: f64 = 2.0;
4542            if !marks.hits((x0 - PAD, y0 - PAD, x1 + PAD, y1 + PAD)) {
4543                built.legend_at = Some(format!("inside-{}", corner.name()));
4544                return layout;
4545            }
4546        }
4547
4548        // Outside: the given side, else whichever of Top/Right leaves the
4549        // data area (a fixed-aspect map's letterboxed rect) larger.
4550        let sides = match auto.fallback {
4551            Some(side) => vec![side],
4552            None => vec![LegendSide::Top, LegendSide::Right],
4553        };
4554        let data_area = |built: &crate::build::BuiltPlot, layout: &PlotLayout| {
4555            let r = built
4556                .coord
4557                .data_rect(&layout.plot_area)
4558                .unwrap_or_else(|| layout.plot_area.clone());
4559            r.width.max(0.0) * r.height.max(0.0)
4560        };
4561        let mut best = (sides[0], f64::MIN);
4562        for &side in &sides {
4563            reset(built, side.position());
4564            let trial = Self::layout_built_inner(built, meta, w, h);
4565            let area = data_area(built, &trial);
4566            if area > best.1 {
4567                best = (side, area);
4568            }
4569        }
4570        reset(built, best.0.position());
4571        let layout = Self::layout_built_inner(built, meta, w, h);
4572        built.legend_at = Some(
4573            match built.theme.legend_position {
4574                P::Top => "top",
4575                P::Right => "right",
4576                P::Bottom => "bottom",
4577                _ => "left",
4578            }
4579            .to_string(),
4580        );
4581        layout
4582    }
4583
4584    fn layout_built_inner(
4585        built: &mut crate::build::BuiltPlot,
4586        meta: &RenderMeta,
4587        w: u32,
4588        h: u32,
4589    ) -> PlotLayout {
4590        let RenderMeta {
4591            has_title,
4592            has_subtitle,
4593            has_caption,
4594            has_legend,
4595            legend_bottom_share,
4596            legend_auto: _,
4597        } = *meta;
4598        let x_axis_top = built
4599            .scales
4600            .get(&crate::aes::Aesthetic::X)
4601            .map(|s| s.axis_position_opposite())
4602            .unwrap_or(false);
4603
4604        // #287: decided first, so every legend pass below plans for the
4605        // position actually drawn, on this render's own layout.
4606        if let Some(share) = legend_bottom_share {
4607            if has_legend
4608                && matches!(
4609                    built.theme.legend_position,
4610                    crate::theme::LegendPosition::Right
4611                )
4612            {
4613                let panel_width = |pos| {
4614                    let mut theme = built.theme.clone();
4615                    theme.legend_position = pos;
4616                    PlotLayout::compute_with_extras(
4617                        w as f64,
4618                        h as f64,
4619                        &theme,
4620                        has_title,
4621                        has_subtitle,
4622                        has_caption,
4623                        has_legend,
4624                        x_axis_top,
4625                        None,
4626                        None,
4627                        crate::render::layout::LayoutExtras::default(),
4628                    )
4629                    .plot_area
4630                    .width
4631                };
4632                // Against the panel it would have with no legend at all
4633                // (the clamped minimum panel width hides the real band).
4634                let free = panel_width(crate::theme::LegendPosition::None);
4635                if panel_width(crate::theme::LegendPosition::Right) < (1.0 - share) * free {
4636                    built.theme.legend_position = crate::theme::LegendPosition::Bottom;
4637                }
4638            }
4639        }
4640
4641        // Auto-tune categorical axis labels so they stay legible. A flip swaps
4642        // which trained scale sits on each visual axis: the bottom (x) axis reads
4643        // the Y scale when flipped, the left (y) axis reads the X scale.
4644        let flipped = built.coord.is_flipped();
4645        let h_aes = if flipped {
4646            crate::aes::Aesthetic::Y
4647        } else {
4648            crate::aes::Aesthetic::X
4649        };
4650        let v_aes = if flipped {
4651            crate::aes::Aesthetic::X
4652        } else {
4653            crate::aes::Aesthetic::Y
4654        };
4655
4656        // The bottom-axis break labels that are actually drawn — a
4657        // `with_labels` override can blank some entries ("" ) to thin a
4658        // crowded discrete axis while keeping every position (sipemu/
4659        // ggplot-rs#162); a blanked entry is never drawn, so it never
4660        // competes for horizontal room or vertical drop below. Shared by
4661        // the auto-rotate decision and the rotated-label height reservation
4662        // just below, so both agree on what's actually on the canvas.
4663        let drawn_x_labels: Vec<(f64, String)> = built
4664            .scales
4665            .get(&h_aes)
4666            .map(|hs| {
4667                hs.breaks()
4668                    .into_iter()
4669                    .filter(|(_, label)| !label.is_empty())
4670                    .collect()
4671            })
4672            .unwrap_or_default();
4673        let h_is_discrete = built
4674            .scales
4675            .get(&h_aes)
4676            .map(|hs| hs.is_discrete())
4677            .unwrap_or(false);
4678
4679        // Crowded discrete bottom-axis labels overlap when drawn flat. Rotate
4680        // them — −45° if that de-collides, otherwise vertical (270°) — only
4681        // when no explicit angle was set (angle.abs() < 1.0 reads as
4682        // "unset"). Sized from the real, measured widths of the labels that
4683        // are actually drawn (`render::text::text_width`), both for the
4684        // label-width estimate and the crowding count `n` — #162's bug was
4685        // counting every break, blanked or not, which over-triggered the
4686        // rotation. −45° (not +45°) is ggplot2's own idiom (`angle = 45,
4687        // hjust = 1`, mirrored to this library's angle sign, sipemu/
4688        // ggplot-rs#163): it ends each label at its own tick and slants
4689        // down-left, rather than +45°'s down-right slant, which — anchored
4690        // the same way — would start under the *previous* category.
4691        if built.theme.axis_text_x.visible
4692            && built.theme.axis_text_x.angle.abs() < 1.0
4693            && h_is_discrete
4694            && !drawn_x_labels.is_empty()
4695        {
4696            let font = built.theme.axis_text_x.size;
4697            let max_w = drawn_x_labels
4698                .iter()
4699                .map(|(_, l)| crate::render::text::text_width(l, font))
4700                .fold(0.0_f64, f64::max);
4701            let n = drawn_x_labels.len() as f64;
4702            let spacing = 0.9 * w as f64 / n; // ~px between adjacent *drawn* labels
4703            if max_w > spacing {
4704                // 45° shrinks the horizontal footprint by cos45; if that
4705                // still doesn't fit, go vertical (270° = reads bottom-to-
4706                // top, hanging below the axis like the y-axis title).
4707                let vertical = max_w * std::f64::consts::FRAC_1_SQRT_2 > spacing;
4708                built.theme.axis_text_x.angle = if vertical { 270.0 } else { -45.0 };
4709            }
4710        }
4711
4712        // Whenever the bottom-axis labels end up rotated — by the
4713        // auto-rotate decision just above, or by an explicit
4714        // `axis_text_x_angle` call — reserve the real bottom space their
4715        // rotated bounding boxes need, so they never overlap the panel
4716        // (#162 also asked for this: an explicit angle reserved nothing).
4717        // `rotated_label_rise_fall` is the same helper `draw_x_axis` calls
4718        // to place its rotation anchor — `rise` must be reserved (as well
4719        // as placed) or a long enough label's far end swings right back up
4720        // over the panel regardless of how much height is reserved here;
4721        // `fall` just needs reserving so the label stays on-canvas. Both
4722        // here and in `draw_x_axis`, the anchor fraction must come from
4723        // `rotated_anchor_frac(angle, dir)` (sipemu/ggplot-rs#163) — not a
4724        // blind `1.0` — or the reservation is sized for the wrong end of
4725        // the label; `dir` matches `draw_x_axis`'s own tick direction.
4726        let x_label_height = if built.theme.axis_text_x.visible
4727            && built.theme.axis_text_x.angle.abs() > 10.0
4728            && !drawn_x_labels.is_empty()
4729        {
4730            let font = built.theme.axis_text_x.size;
4731            let angle = built.theme.axis_text_x.angle;
4732            let dir = if x_axis_top { -1.0 } else { 1.0 };
4733            let (rise, fall) = crate::render::text::rotated_label_rise_fall(
4734                drawn_x_labels.iter().map(|(_, l)| l.as_str()),
4735                font,
4736                angle,
4737                crate::render::text::rotated_anchor_frac(angle, dir),
4738            );
4739            Some(built.theme.legend_spacing / 2.0 + font / 2.0 + rise + fall)
4740        } else {
4741            None
4742        };
4743
4744        // Reserve the left-axis width from the actual label lengths so long
4745        // category names (a flipped bar chart's rows) aren't clipped. Never
4746        // shrinks below the default; grows up to 35% of the width.
4747        let y_label_width = if built.theme.axis_text_y.visible {
4748            built.scales.get(&v_aes).map(|vs| {
4749                crate::guide::axis::y_label_reserve(&built.theme, &vs.breaks()).min(0.35 * w as f64)
4750            })
4751        } else {
4752            None
4753        };
4754
4755        // B3-1 (D6): reserve just enough left/right panel margin to keep
4756        // the outer x-axis labels on-canvas under `AxisLabelFit::Reserve`,
4757        // for a single (non-faceted) panel on a coord that supports it
4758        // (not polar/radar/sf, where a label bbox doesn't map to a simple
4759        // panel margin). A faceted plot skips the layout-level reservation
4760        // and relies on `draw_x_axis`'s own draw-time shift instead — so
4761        // does `AxisLabelFit::Shift` (the panel must keep its size) and
4762        // `Clip` (the 0.21 behaviour, no correction at all). A plot whose
4763        // outer labels already fit never grows `extras`, so it stays
4764        // byte-identical.
4765        // #409: legends moved to another side (`guide_position`) reserve
4766        // that side's band too.
4767        let mut extras = crate::render::layout::LayoutExtras {
4768            extra_legend_sides: crate::guide::legend::extra_legend_sides(
4769                &built.scales,
4770                &built.suppressed_aes,
4771                &built.guide_legend,
4772                &built.theme.legend_position,
4773            ),
4774            ..Default::default()
4775        };
4776        // A secondary y axis draws its ticks, labels and title right of the
4777        // panel: reserve that width so they stay on-canvas (and clear of a
4778        // right-hand legend).
4779        if let (Some(vs), Some(sec)) = (
4780            built.scales.get(&crate::aes::Aesthetic::Y),
4781            built.scales.sec_axis(&crate::aes::Aesthetic::Y),
4782        ) {
4783            let theme = &built.theme;
4784            let max_ch = match sec.own_ticks(vs) {
4785                Some(t) => t.iter().map(|(_, l)| l.chars().count()).max(),
4786                None => vs.breaks().iter().map(|(_, l)| l.chars().count() + 2).max(),
4787            }
4788            .unwrap_or(0);
4789            let text = if theme.axis_text_y.visible {
4790                (max_ch as f64 * theme.axis_text_y.size * 0.6).max(theme.axis_text_y.size * 3.5)
4791            } else {
4792                0.0
4793            };
4794            let title = if !sec.name.is_empty() && theme.axis_title_y.visible {
4795                theme.axis_title_y.size * 1.5
4796            } else {
4797                0.0
4798            };
4799            extras.right += theme.axis_ticks_length + theme.legend_spacing + text + title;
4800        }
4801        // …and a secondary x axis its height above the panel (#409).
4802        if let Some(sec) = built
4803            .scales
4804            .get(&h_aes)
4805            .filter(|s| !s.axis_position_opposite())
4806            .and_then(|s| s.sec_axis())
4807        {
4808            extras.top += crate::guide::axis::sec_x_axis_height(&built.theme, sec);
4809        }
4810        let can_reserve = built.facet.is_none()
4811            && built.theme.axis_text_x.visible
4812            && built.theme.axis_text_x_fit == crate::theme::AxisLabelFit::Reserve
4813            && !built.coord.is_polar()
4814            && built.coord.supports_axis_reserve();
4815        if can_reserve {
4816            if let Some(hs) = built.scales.get(&h_aes) {
4817                let breaks = hs.breaks();
4818                if let (Some(first), Some(last)) = (breaks.first(), breaks.last()) {
4819                    let angle = built.theme.axis_text_x.angle;
4820                    let anchor = if angle.abs() > 10.0 {
4821                        let dir = if x_axis_top { -1.0 } else { 1.0 };
4822                        crate::render::text::rotated_anchor_frac(angle, dir)
4823                    } else {
4824                        0.5
4825                    };
4826                    let size = built.theme.axis_text_x.size;
4827                    const EDGE: f64 = 1.0;
4828                    for _ in 0..2 {
4829                        let layout = PlotLayout::compute_with_extras(
4830                            w as f64,
4831                            h as f64,
4832                            &built.theme,
4833                            has_title,
4834                            has_subtitle,
4835                            has_caption,
4836                            has_legend,
4837                            x_axis_top,
4838                            y_label_width,
4839                            x_label_height,
4840                            extras,
4841                        );
4842                        let area = &layout.plot_area;
4843                        let edge_y = area.y + area.height;
4844                        let to_point = |pos: f64| if flipped { (0.0, pos) } else { (pos, 0.0) };
4845                        let px_first = built.coord.transform(to_point(first.0), area).0;
4846                        let px_last = built.coord.transform(to_point(last.0), area).0;
4847                        let bbox_first = crate::render::text::label_bbox(
4848                            &first.1, size, px_first, edge_y, angle, anchor,
4849                        );
4850                        let bbox_last = crate::render::text::label_bbox(
4851                            &last.1, size, px_last, edge_y, angle, anchor,
4852                        );
4853                        let deficit_left = (EDGE - bbox_first[0]).max(0.0);
4854                        let deficit_right = (bbox_last[2] - (w as f64 - EDGE)).max(0.0);
4855                        if deficit_left <= 0.0 && deficit_right <= 0.0 {
4856                            break;
4857                        }
4858                        // Growing the left margin by `eL` (holding `eR` fixed)
4859                        // shifts a label at normalized position `p` right by
4860                        // `eL·(1 − p)`; growing the right margin by `eR`
4861                        // shifts it left by `eR·p` (the panel maps [0, 1] to
4862                        // [plot_x + eL, plot_x + width − eR]). Review #158
4863                        // finding 1: the original code divided by `p_first`
4864                        // and `1 − p_last` — inverted, which over-reserved
4865                        // by about `1/p_last` (≈20× at a typical p_last≈0.95).
4866                        let (p_first, p_last) = (first.0, last.0);
4867                        if deficit_left > 0.0 && deficit_right > 0.0 {
4868                            // Both ends overflow: solve the 2×2 system so
4869                            // each margin accounts for its effect on *both*
4870                            // labels, rather than correcting them
4871                            // independently and overshooting.
4872                            let (a, b, c, d) = (1.0 - p_first, p_first, 1.0 - p_last, p_last);
4873                            let det = a * d - b * c;
4874                            if det.abs() > 0.01 {
4875                                extras.left +=
4876                                    ((deficit_left * d + deficit_right * b) / det).max(0.0);
4877                                extras.right +=
4878                                    ((deficit_right * a + deficit_left * c) / det).max(0.0);
4879                            } else {
4880                                // Degenerate (first and last break nearly
4881                                // coincide in normalized space): fall back
4882                                // to the independent, clamped formulas.
4883                                extras.left += deficit_left / (1.0 - p_first).max(0.05);
4884                                extras.right += deficit_right / p_last.max(0.05);
4885                            }
4886                        } else if deficit_left > 0.0 {
4887                            extras.left += deficit_left / (1.0 - p_first).max(0.05);
4888                        } else if deficit_right > 0.0 {
4889                            extras.right += deficit_right / p_last.max(0.05);
4890                        }
4891                        // Cap the total reservation so the panel can never
4892                        // start beyond the canvas or be squeezed past the
4893                        // same minimum width `compute_with_extras` already
4894                        // floors it to (review #158's second re-review,
4895                        // LOW): a single, centred break whose label is
4896                        // wider than the whole canvas has `p_first ==
4897                        // p_last == 0.5`, so both `eL` and `eR` grow by
4898                        // roughly the same (large) deficit independently,
4899                        // and together they could place `plot_x` past `w`
4900                        // entirely. Past this cap, Reserve simply stops
4901                        // growing and `draw_x_axis`'s own draw-time shift
4902                        // — which always runs for Reserve, the same as for
4903                        // `Shift` — takes over for whatever's still
4904                        // outside, exactly as D6 already documents.
4905                        const MIN_PANEL_WIDTH: f64 = 50.0;
4906                        let cap = (w as f64 - MIN_PANEL_WIDTH).max(0.0);
4907                        if extras.left + extras.right > cap {
4908                            let scale = if extras.left + extras.right > 0.0 {
4909                                cap / (extras.left + extras.right)
4910                            } else {
4911                                0.0
4912                            };
4913                            extras.left *= scale;
4914                            extras.right *= scale;
4915                        }
4916                    }
4917                }
4918            }
4919        }
4920
4921        // B3-2 (D7): a discrete legend's `nrow`/`ncol` grid, or an
4922        // overflowing horizontal legend's auto-wrap, reserves extra legend
4923        // rows/width. Several simultaneous discrete guides (e.g. `colour`
4924        // and `shape` both mapped to discrete variables) each get their
4925        // own independent plan (sipemu/ggplot-rs#155) — previously this
4926        // only ran for exactly one discrete guide.
4927        if has_legend
4928            && !matches!(
4929                built.theme.legend_position,
4930                crate::theme::LegendPosition::None
4931            )
4932        {
4933            let legend_aes =
4934                crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
4935            // #236: a mapped `size` legend's largest key can need a bigger
4936            // box than the theme's flat defaults — independent of B3-2's
4937            // discrete-guide wrap planning below, so computed unconditionally.
4938            extras.legend_max_key_size = legend_aes
4939                .iter()
4940                .filter_map(|aes| {
4941                    let scale = built.scales.get(aes)?;
4942                    let breaks = scale.breaks();
4943                    Some(crate::guide::legend::size_key_diameter(
4944                        aes,
4945                        &built.scales,
4946                        scale,
4947                        &breaks,
4948                    ))
4949                })
4950                .fold(0.0_f64, f64::max);
4951            // #545: a continuous, non-colourbar guide (`Size`/
4952            // `Linewidth`/… sampled breaks) needs the same B3-2 wrap/grid
4953            // reservation pass a discrete guide gets — only a true
4954            // colourbar (continuous `Color`/`Fill`) is exempt, since it
4955            // draws as a fixed-width bar instead of sampled keys.
4956            // Previously this gate only fired for a discrete guide, so a
4957            // plot mapping *only* a continuous `Size`/`Linewidth` (no
4958            // discrete guide alongside it) skipped the whole reservation
4959            // pass and its legend could run straight off the panel/canvas
4960            // with no wrap, shrink, or "+N more" to catch it.
4961            let has_wrap_guide = legend_aes.iter().any(|a| {
4962                let is_discrete = built
4963                    .scales
4964                    .get(a)
4965                    .map(|s| s.is_discrete())
4966                    .unwrap_or(false);
4967                is_discrete || !crate::guide::legend::is_colorbar_aesthetic(a)
4968            });
4969            if has_wrap_guide {
4970                let layout0 = PlotLayout::compute_with_extras(
4971                    w as f64,
4972                    h as f64,
4973                    &built.theme,
4974                    has_title,
4975                    has_subtitle,
4976                    has_caption,
4977                    has_legend,
4978                    x_axis_top,
4979                    y_label_width,
4980                    x_label_height,
4981                    extras,
4982                );
4983                // `y` is unused here (only `legend_x0`/`is_horizontal` feed
4984                // the avail-width check below), so #233's `Top` row-count
4985                // parameter can't matter — `extras.legend_extra_rows` isn't
4986                // even known yet at this point in the pass. Likewise #225's
4987                // `Inside` justification only matters when `legend_x0` is
4988                // actually used for an `Inside` position combined with an
4989                // explicit `nrow`/`ncol` grid (`Inside` otherwise never
4990                // reaches this discrete-guide-wrap check), too rare to
4991                // bother estimating a real size hint for here.
4992                let (legend_x0, _, mut is_horizontal) = crate::guide::legend::legend_position(
4993                    &built.theme,
4994                    &layout0.plot_area,
4995                    extras.legend_extra_rows,
4996                    (0.0, 0.0),
4997                    0.0,
4998                    &layout0.total,
4999                );
5000                if let Some(dir) = built.theme.legend_direction {
5001                    is_horizontal = matches!(dir, crate::theme::LegendDirection::Horizontal);
5002                }
5003                let avail_width =
5004                    (layout0.plot_area.x + layout0.plot_area.width - legend_x0).max(0.0);
5005                let mut legend_warnings = Vec::new();
5006                let mut plans = crate::guide::legend::plan_all_legends(
5007                    &built.scales,
5008                    &built.guide_legend,
5009                    &built.theme,
5010                    &built.suppressed_aes,
5011                    avail_width,
5012                    layout0.plot_area.height,
5013                    is_horizontal,
5014                    &mut legend_warnings,
5015                );
5016                built.warnings.extend(legend_warnings);
5017
5018                if !plans.is_empty() {
5019                    // Guides laid out side by side (a horizontal legend
5020                    // position) share one row band — its height is set
5021                    // by whichever guide wrapped to the most rows.
5022                    // Guides stacked vertically each add their own full
5023                    // height, so their extra rows sum.
5024                    extras.legend_extra_rows = if is_horizontal {
5025                        plans
5026                            .values()
5027                            .map(|p| p.rows.saturating_sub(1))
5028                            .max()
5029                            .unwrap_or(0)
5030                    } else {
5031                        plans.values().map(|p| p.rows.saturating_sub(1)).sum()
5032                    };
5033                    // Review #158 finding 3: a vertical explicit grid
5034                    // with ncol > 1 needs extra legend band width for
5035                    // its later columns, or they run off the canvas
5036                    // (cols is always 1, col_pitch 0, for the horizontal
5037                    // auto-wrap path, so this is a no-op there). Several
5038                    // guides take the widest requirement among them.
5039                    extras.legend_extra_width = plans
5040                        .values()
5041                        .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
5042                        .fold(0.0_f64, f64::max);
5043
5044                    // #159: a vertical multi-column grid that still runs
5045                    // off the canvas even after reserving the extra width
5046                    // above now (1) tries reducing its column count
5047                    // toward 1 — the first count that fits wins; (2) if
5048                    // even one column still overflows, truncates labels
5049                    // with an ellipsis (keeping the full label available
5050                    // via a `<title>`); and only (3) warns if it still
5051                    // doesn't fit after both. A grid that already fits is
5052                    // untouched — no reduction, no truncation, no warning
5053                    // (review #158's second re-review, LOW, is the
5054                    // original "warn only" version of this check).
5055                    if !is_horizontal {
5056                        let final_layout = PlotLayout::compute_with_extras(
5057                            w as f64,
5058                            h as f64,
5059                            &built.theme,
5060                            has_title,
5061                            has_subtitle,
5062                            has_caption,
5063                            has_legend,
5064                            x_axis_top,
5065                            y_label_width,
5066                            x_label_height,
5067                            extras,
5068                        );
5069                        // `y` is unused here too, but `extras` is final by
5070                        // this point, so pass its real `legend_extra_rows`
5071                        // for consistency with #233's `Top` formula. #225's
5072                        // `Inside` size hint is skipped here for the same
5073                        // reason as the pass above.
5074                        let (legend_x_final, _, _) = crate::guide::legend::legend_position(
5075                            &built.theme,
5076                            &final_layout.plot_area,
5077                            extras.legend_extra_rows,
5078                            (0.0, 0.0),
5079                            0.0,
5080                            &final_layout.total,
5081                        );
5082                        let swatch_and_gap =
5083                            built.theme.legend_key_width + built.theme.legend_spacing;
5084                        let text_size = built.theme.legend_text.size;
5085                        // A plain fn, not a closure: #168's retightening
5086                        // pass below re-runs this same check at a second
5087                        // `legend_x` (the narrower reservation's), so
5088                        // `legend_x` has to be a parameter rather than
5089                        // captured.
5090                        fn right_edge_of(
5091                            legend_x: f64,
5092                            swatch_and_gap: f64,
5093                            text_size: f64,
5094                            plan: &crate::guide::legend::LegendPlan,
5095                            breaks: &[(f64, String)],
5096                        ) -> f64 {
5097                            plan.entries
5098                                .iter()
5099                                .filter_map(|e| breaks.get(e.break_idx).map(|(_, l)| (e, l)))
5100                                .map(|(e, label)| {
5101                                    let text =
5102                                        e.label_override.as_deref().unwrap_or(label.as_str());
5103                                    legend_x
5104                                        + e.x_offset
5105                                        + swatch_and_gap
5106                                        + crate::render::text::text_width(text, text_size)
5107                                })
5108                                .fold(0.0_f64, f64::max)
5109                        }
5110
5111                        let mut updates: Vec<(
5112                            crate::aes::Aesthetic,
5113                            crate::guide::legend::LegendPlan,
5114                        )> = Vec::new();
5115                        // #168: guides narrowed below by *column
5116                        // reduction* (not label truncation) are
5117                        // candidates for the retightening pass after this
5118                        // loop — a truncated guide already picked the
5119                        // narrowest column count, so there's no reserved
5120                        // width left to give back.
5121                        let mut reduced_aes: Vec<crate::aes::Aesthetic> = Vec::new();
5122                        for (aes, plan) in &plans {
5123                            if plan.cols <= 1 {
5124                                continue;
5125                            }
5126                            let Some(scale) = built.scales.get(aes) else {
5127                                continue;
5128                            };
5129                            let breaks = scale.breaks();
5130                            if right_edge_of(
5131                                legend_x_final,
5132                                swatch_and_gap,
5133                                text_size,
5134                                plan,
5135                                &breaks,
5136                            ) <= w as f64
5137                            {
5138                                continue; // already fits — untouched.
5139                            }
5140
5141                            // Step 1: reduce columns toward 1; the first
5142                            // count that fits wins.
5143                            let n = breaks.len();
5144                            let mut reduced: Vec<crate::guide::legend::LegendPlan> = Vec::new();
5145                            for c in (1..plan.cols).rev() {
5146                                let mut candidate_guide = built.guide_legend.clone();
5147                                candidate_guide.ncol = Some(c);
5148                                candidate_guide.nrow = None;
5149                                let mut tmp_warnings = Vec::new();
5150                                let candidate_guide =
5151                                    candidate_guide.validated(n, &mut tmp_warnings);
5152                                if let Some(cand) = crate::guide::legend::plan_legend(
5153                                    &breaks,
5154                                    &candidate_guide,
5155                                    &built.theme,
5156                                    avail_width,
5157                                    layout0.plot_area.height,
5158                                    false,
5159                                ) {
5160                                    reduced.push(cand);
5161                                }
5162                            }
5163                            if let Some(fits) = reduced.iter().find(|c| {
5164                                right_edge_of(legend_x_final, swatch_and_gap, text_size, c, &breaks)
5165                                    <= w as f64
5166                            }) {
5167                                extras.legend_extra_rows =
5168                                    extras.legend_extra_rows.max(fits.rows.saturating_sub(1));
5169                                updates.push((aes.clone(), fits.clone()));
5170                                reduced_aes.push(aes.clone());
5171                                continue;
5172                            }
5173
5174                            // Step 2: no column count fit — truncate
5175                            // labels (starting from the narrowest, 1-
5176                            // column, candidate) with an ellipsis, each
5177                            // to whatever room its own position leaves.
5178                            let base = reduced.last().cloned().unwrap_or_else(|| plan.clone());
5179                            extras.legend_extra_rows =
5180                                extras.legend_extra_rows.max(base.rows.saturating_sub(1));
5181                            let mut truncated = base.clone();
5182                            for e in &mut truncated.entries {
5183                                let Some((_, label)) = breaks.get(e.break_idx) else {
5184                                    continue;
5185                                };
5186                                let avail = (w as f64
5187                                    - (legend_x_final + e.x_offset + swatch_and_gap))
5188                                    .max(0.0);
5189                                if let Some(short) =
5190                                    crate::render::text::truncate_to_width(label, avail, text_size)
5191                                {
5192                                    e.label_override = Some(short);
5193                                }
5194                            }
5195
5196                            // Step 3: only warn if it still doesn't fit
5197                            // after both the reduction and the
5198                            // truncation above.
5199                            let truncated_edge = right_edge_of(
5200                                legend_x_final,
5201                                swatch_and_gap,
5202                                text_size,
5203                                &truncated,
5204                                &breaks,
5205                            );
5206                            if truncated_edge > w as f64 {
5207                                built.warnings.push(format!(
5208                                    "legend: the {}-column grid still doesn't fit the {w}px chart (needs about {} px)",
5209                                    truncated.cols,
5210                                    truncated_edge.ceil() as i64
5211                                ));
5212                            }
5213                            updates.push((aes.clone(), truncated));
5214                        }
5215                        for (aes, new_plan) in &updates {
5216                            plans.insert(aes.clone(), new_plan.clone());
5217                        }
5218
5219                        // #168: `extras.legend_extra_width` above still
5220                        // reserves the *original*, pre-reduction column
5221                        // count's width — that stale, wider reservation
5222                        // is an accident of ordering (reserve → layout →
5223                        // fit? → reduce), not a requirement, so the panel
5224                        // stays narrower than it needs to be once a guide
5225                        // above got fewer columns.
5226                        //
5227                        // Tighten it to the reduced guides' new column
5228                        // counts and re-check fit once more at the
5229                        // narrower reservation (a bounded retry, not an
5230                        // unbounded fixed point: a tighter reservation
5231                        // moves `legend_x_final` right — less headroom
5232                        // before the canvas edge — which could in
5233                        // principle call for yet another round of
5234                        // reduction; rather than chase reserve → layout →
5235                        // fit → reduce → reserve → … indefinitely, this
5236                        // keeps the tighter reservation only if every
5237                        // guide still fits under it, and falls back to
5238                        // the wider, already-proven-safe reservation
5239                        // otherwise — so retightening can only ever
5240                        // help, never regress a plot that fit before
5241                        // this pass existed).
5242                        //
5243                        // Review #167 finding 1 on #171 (HIGH, fixed):
5244                        // the retry must re-check *every* plan in
5245                        // `plans`, not just `reduced_aes`. `legend_x`
5246                        // moves for every guide sharing the row, not
5247                        // only the one(s) that got reduced — a second
5248                        // guide that already fit at the old, wider
5249                        // `legend_x_final` (its own width is a fixed
5250                        // `6·text_size` estimate, unrelated to the
5251                        // reduced guide's labels) or whose labels were
5252                        // truncated against that old `legend_x_final`
5253                        // shifts right by the same amount and was never
5254                        // re-checked, so it could run off the canvas
5255                        // with no warning (the warnings were computed
5256                        // against the old x too). `reduced_aes` is kept
5257                        // only to gate *entering* this block at all —
5258                        // nothing to reclaim if nothing was reduced.
5259                        if !reduced_aes.is_empty() {
5260                            let original_reserve = extras.legend_extra_width;
5261                            let tighter_reserve = plans
5262                                .values()
5263                                .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
5264                                .fold(0.0_f64, f64::max);
5265                            if tighter_reserve < original_reserve {
5266                                let mut retry_extras = extras;
5267                                retry_extras.legend_extra_width = tighter_reserve;
5268                                let retry_layout = PlotLayout::compute_with_extras(
5269                                    w as f64,
5270                                    h as f64,
5271                                    &built.theme,
5272                                    has_title,
5273                                    has_subtitle,
5274                                    has_caption,
5275                                    has_legend,
5276                                    x_axis_top,
5277                                    y_label_width,
5278                                    x_label_height,
5279                                    retry_extras,
5280                                );
5281                                // `y` is unused here too; `retry_extras`
5282                                // only tightened `legend_extra_width`, so
5283                                // its `legend_extra_rows` is still the same
5284                                // real value. #225's `Inside` size hint is
5285                                // skipped for the same reason as above.
5286                                let (retry_x, _, _) = crate::guide::legend::legend_position(
5287                                    &built.theme,
5288                                    &retry_layout.plot_area,
5289                                    retry_extras.legend_extra_rows,
5290                                    (0.0, 0.0),
5291                                    0.0,
5292                                    &retry_layout.total,
5293                                );
5294                                let all_still_fit = plans.iter().all(|(aes, plan)| {
5295                                    let Some(scale) = built.scales.get(aes) else {
5296                                        return true;
5297                                    };
5298                                    let breaks = scale.breaks();
5299                                    right_edge_of(retry_x, swatch_and_gap, text_size, plan, &breaks)
5300                                        <= w as f64
5301                                });
5302                                if all_still_fit {
5303                                    extras.legend_extra_width = tighter_reserve;
5304                                }
5305                            }
5306                        }
5307                    }
5308                    for (aes, plan) in &plans {
5309                        if let Some(ov) = &plan.overflow {
5310                            let n = built
5311                                .scales
5312                                .get(aes)
5313                                .map(|s| s.breaks().len())
5314                                .unwrap_or(ov.dropped);
5315                            let shown = n.saturating_sub(ov.dropped);
5316                            built.warnings.push(format!(
5317                                "legend: {} of {n} entries don't fit the chart; the legend shows {shown} and \"+{} more\"",
5318                                ov.dropped, ov.dropped
5319                            ));
5320                        }
5321                    }
5322                }
5323                // Review #158 finding 2: store these exact plans so
5324                // `draw_legend_planned` draws them verbatim instead of
5325                // recomputing against the (shorter) post-reservation
5326                // panel height, which could warn "+7 more" while
5327                // drawing "+15 more".
5328                built.legend_plans = plans;
5329            }
5330        }
5331
5332        // #409: a `guide_colourbar(bar_width)` wider than a legend key
5333        // widens a side legend's reserved band by the difference.
5334        if has_legend
5335            && matches!(
5336                built.theme.legend_position,
5337                crate::theme::LegendPosition::Left | crate::theme::LegendPosition::Right
5338            )
5339            && !matches!(
5340                built.theme.legend_direction,
5341                Some(crate::theme::LegendDirection::Horizontal)
5342            )
5343        {
5344            let key_w = built.theme.legend_key_width.max(extras.legend_max_key_size);
5345            let extra =
5346                crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes)
5347                    .iter()
5348                    .filter(|aes| {
5349                        crate::guide::legend::is_colorbar_aesthetic(aes)
5350                            && built.scales.get(aes).is_some_and(|s| !s.is_discrete())
5351                    })
5352                    .filter_map(|aes| built.guide_legend.colourbar_for(aes).bar_width)
5353                    .map(|w| (w - key_w).max(0.0))
5354                    .fold(0.0_f64, f64::max);
5355            extras.legend_extra_width = extras.legend_extra_width.max(extra);
5356            // #409: a custom guide wider than a key + its label column.
5357            let text_col = key_w + built.theme.legend_spacing + built.theme.legend_text.size * 6.0;
5358            let custom = built
5359                .guide_legend
5360                .custom
5361                .iter()
5362                .map(|g| (g.width - text_col).max(0.0))
5363                .fold(0.0_f64, f64::max);
5364            extras.legend_extra_width = extras.legend_extra_width.max(custom);
5365        }
5366
5367        // #211: a continuous colourbar at `Top`/`Bottom` (or
5368        // `legend_direction(Horizontal)`) draws wide × short instead of
5369        // its usual tall × narrow bar (see `draw_continuous_legend_at`),
5370        // with its tick labels below rather than beside it — reserve the
5371        // extra band height that needs beyond the flat discrete-row
5372        // height `legend_band` already assumes. Independent of the
5373        // `has_wrap_guide` block above (a plot can have a continuous
5374        // colourbar with no other guide at all), so computed
5375        // unconditionally here, right before the layout that actually
5376        // matters reads `extras`.
5377        if has_legend
5378            && !matches!(
5379                built.theme.legend_position,
5380                crate::theme::LegendPosition::None
5381            )
5382        {
5383            let is_horizontal = match built.theme.legend_direction {
5384                Some(dir) => matches!(dir, crate::theme::LegendDirection::Horizontal),
5385                None => matches!(
5386                    built.theme.legend_position,
5387                    crate::theme::LegendPosition::Top | crate::theme::LegendPosition::Bottom
5388                ),
5389            };
5390            if is_horizontal {
5391                let legend_aes =
5392                    crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
5393                let continuous_colourbar = legend_aes.iter().find_map(|aes| {
5394                    if !matches!(
5395                        aes,
5396                        crate::aes::Aesthetic::Color | crate::aes::Aesthetic::Fill
5397                    ) {
5398                        return None;
5399                    }
5400                    let scale = built.scales.get(aes)?;
5401                    if scale.is_discrete() {
5402                        return None;
5403                    }
5404                    Some(scale)
5405                });
5406                if let Some(scale) = continuous_colourbar {
5407                    let title = built
5408                        .guide_legend
5409                        .title
5410                        .as_deref()
5411                        .unwrap_or_else(|| scale.name());
5412                    let bar_height = crate::guide::legend::continuous_horizontal_bar_height(
5413                        &built.theme,
5414                        !title.is_empty(),
5415                        &built.guide_legend.colourbar_for(&scale.aesthetic()),
5416                    );
5417                    let key_h = built
5418                        .theme
5419                        .legend_key_height
5420                        .max(extras.legend_max_key_size);
5421                    extras.continuous_horizontal_legend_extra_height =
5422                        (bar_height - key_h).max(0.0);
5423                }
5424                // #409: a custom guide taller than a key row.
5425                let key_h = built
5426                    .theme
5427                    .legend_key_height
5428                    .max(extras.legend_max_key_size);
5429                let custom = built
5430                    .guide_legend
5431                    .custom
5432                    .iter()
5433                    .map(|g| (g.title_offset(&built.theme) + g.height - key_h).max(0.0))
5434                    .fold(0.0_f64, f64::max);
5435                extras.continuous_horizontal_legend_extra_height =
5436                    extras.continuous_horizontal_legend_extra_height.max(custom);
5437            }
5438        }
5439
5440        PlotLayout::compute_with_extras(
5441            w as f64,
5442            h as f64,
5443            &built.theme,
5444            has_title,
5445            has_subtitle,
5446            has_caption,
5447            has_legend,
5448            x_axis_top,
5449            y_label_width,
5450            x_label_height,
5451            extras,
5452        )
5453    }
5454
5455    /// Fill the background, render the built plot, and flush — for any plotters
5456    /// backend. (Native only.)
5457    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
5458    fn render_into<DB>(
5459        area: plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
5460        built: &crate::build::BuiltPlot,
5461        layout: &PlotLayout,
5462    ) -> Result<(), GGError>
5463    where
5464        DB: plotters::prelude::DrawingBackend,
5465        DB::ErrorType: 'static,
5466    {
5467        area.fill(&plotters::prelude::WHITE)
5468            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
5469        let mut adapter = PlottersAdapter::new(&area, layout.plot_area.clone());
5470        PlotRenderer::render(built, &mut adapter).map_err(GGError::Render)?;
5471        area.present()
5472            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
5473        Ok(())
5474    }
5475
5476    /// Save with physical dimensions (inches) and DPI. (Feature `plotters`;
5477    /// native only.)
5478    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
5479    pub fn ggsave(
5480        self,
5481        path: &str,
5482        width_inches: f64,
5483        height_inches: f64,
5484        dpi: f64,
5485    ) -> Result<(), GGError> {
5486        let w = (width_inches * dpi) as u32;
5487        let h = (height_inches * dpi) as u32;
5488        self.save_with_size(path, w, h)
5489    }
5490
5491    /// Does this plot have a legend to make room for? (#201) A plot-level
5492    /// `.aes(...)` mapping always counts; so does a *layer's own*
5493    /// `.layer_aes(...)` mapping — e.g. `geom_hex`'s usual pattern of
5494    /// mapping `fill` to a raw column only on that one layer, via
5495    /// `StatIdentity` after pre-binning, rather than on the plot as a
5496    /// whole. Checking only `self.mapping` (as before) missed that case
5497    /// entirely: the legend still drew (the render path always draws
5498    /// whatever guides the trained scales produce, regardless of this
5499    /// flag), just with no panel margin ever reserved for it, so it ran
5500    /// straight off the canvas edge. A layer that opts out with
5501    /// `show_legend(false)` doesn't count towards its own mapping, mirroring
5502    /// `PlotBuilder::compute_suppressed_aes`'s later, more precise
5503    /// (post-build, cross-layer) suppression check — this one only needs to
5504    /// decide *whether to reserve space at all*, not exactly how much.
5505    fn has_legend_mapping(&self) -> bool {
5506        // #241: delegates to `guide::legend::is_legend_aesthetic` (the
5507        // same list `draw_legend_planned` itself draws from) rather than
5508        // keeping its own copy — a second, independently-maintained list
5509        // here had drifted out of sync, missing `Linewidth`.
5510        use crate::guide::legend::is_legend_aesthetic;
5511        let plot_level = self
5512            .mapping
5513            .mappings
5514            .iter()
5515            .any(|m| is_legend_aesthetic(&m.aesthetic));
5516        // #409: a custom guide needs the legend band even with no mapping.
5517        !self.guide_legend.custom.is_empty()
5518            || plot_level
5519            || self.layers.iter().any(|layer| {
5520                if layer.show_legend == Some(false) {
5521                    return false;
5522                }
5523                let effective = if layer.geom.inherit_aes() {
5524                    self.mapping.merge(&layer.mapping)
5525                } else {
5526                    layer.mapping.clone()
5527                };
5528                effective
5529                    .mappings
5530                    .iter()
5531                    .any(|m| is_legend_aesthetic(&m.aesthetic))
5532            })
5533    }
5534}
5535
5536/// Size-independent facts about a built plot that its layout needs.
5537#[derive(Clone, Copy, Debug)]
5538pub(crate) struct RenderMeta {
5539    pub(crate) has_title: bool,
5540    pub(crate) has_subtitle: bool,
5541    pub(crate) has_caption: bool,
5542    pub(crate) has_legend: bool,
5543    pub(crate) legend_bottom_share: Option<f64>,
5544    pub(crate) legend_auto: Option<LegendAuto>,
5545}
5546
5547/// [`GGPlot::legend_inside_auto_with`]'s settings (#332).
5548#[derive(Clone, Copy, Debug)]
5549pub(crate) struct LegendAuto {
5550    corners: [Option<crate::theme::LegendCorner>; 4],
5551    fallback: Option<LegendSide>,
5552}
5553
5554/// An outside legend side (a `Copy` subset of `LegendPosition`).
5555#[derive(Clone, Copy, Debug)]
5556enum LegendSide {
5557    Top,
5558    Right,
5559    Bottom,
5560    Left,
5561}
5562
5563impl LegendSide {
5564    fn position(self) -> crate::theme::LegendPosition {
5565        use crate::theme::LegendPosition as P;
5566        match self {
5567            LegendSide::Top => P::Top,
5568            LegendSide::Right => P::Right,
5569            LegendSide::Bottom => P::Bottom,
5570            LegendSide::Left => P::Left,
5571        }
5572    }
5573}
5574
5575/// Top-level error type.
5576#[derive(Debug)]
5577#[non_exhaustive]
5578pub enum GGError {
5579    Render(RenderError),
5580    UnsupportedFormat(String),
5581    Io(std::io::Error),
5582    ValidationError(String),
5583}
5584
5585impl std::fmt::Display for GGError {
5586    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5587        match self {
5588            GGError::Render(e) => write!(f, "Render error: {e}"),
5589            GGError::UnsupportedFormat(ext) => write!(f, "Unsupported output format: {ext}"),
5590            GGError::Io(e) => write!(f, "IO error: {e}"),
5591            GGError::ValidationError(msg) => write!(f, "Validation error: {msg}"),
5592        }
5593    }
5594}
5595
5596impl std::error::Error for GGError {}
5597
5598/// A Brewer palette as a continuous gradient (`scale_*_distiller`).
5599fn distiller(
5600    aes: crate::aes::Aesthetic,
5601    palette: &crate::scale::palettes::PaletteName,
5602    direction: i32,
5603) -> crate::scale::gradient_n::ScaleColorGradientN {
5604    let mut colors = crate::scale::palettes::palette(palette).to_vec();
5605    if direction < 0 {
5606        colors.reverse();
5607    }
5608    let n = colors.len().max(2) - 1;
5609    let stops = colors
5610        .into_iter()
5611        .enumerate()
5612        .map(|(i, c)| (i as f64 / n as f64, c))
5613        .collect();
5614    crate::scale::gradient_n::ScaleColorGradientN::new(aes, stops)
5615}