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::dotplot::GeomDotplot;
27use crate::geom::errorbar::GeomErrorbar;
28use crate::geom::freqpoly::GeomFreqpoly;
29use crate::geom::hex::GeomHex;
30use crate::geom::histogram::GeomHistogram;
31use crate::geom::jitter::GeomJitter;
32use crate::geom::line::GeomLine;
33use crate::geom::linerange::GeomLinerange;
34use crate::geom::path::GeomPath;
35use crate::geom::point::GeomPoint;
36use crate::geom::pointrange::GeomPointrange;
37use crate::geom::polygon::GeomPolygon;
38use crate::geom::qq::{GeomQQ, GeomQQLine};
39use crate::geom::rect::GeomRect;
40use crate::geom::refline::{GeomAbline, GeomHline, GeomVline};
41use crate::geom::ribbon::GeomRibbon;
42use crate::geom::rug::GeomRug;
43use crate::geom::segment::GeomSegment;
44use crate::geom::smooth::GeomSmooth;
45use crate::geom::spoke::GeomSpoke;
46use crate::geom::step::GeomStep;
47use crate::geom::text::{GeomLabel, GeomText};
48use crate::geom::tile::GeomTile;
49use crate::geom::violin::GeomViolin;
50use crate::geom::{Geom, GeomParams};
51use crate::position::Position;
52use crate::render::layout::PlotLayout;
53#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
54use crate::render::plotters_backend::PlottersAdapter;
55use crate::render::renderer::PlotRenderer;
56use crate::render::RenderError;
57use crate::scale::continuous::ScaleContinuous;
58use crate::scale::transform::ScaleTransform;
59use crate::scale::Scale;
60use crate::stat::Stat;
61use crate::theme::Theme;
62
63// Builder methods for the 0.17 statistical-graphics layers (QQ, step ribbons,
64// ECDF bands, Cook's contours, horizontal error bars).
65mod stat_layers;
66
67/// Labels for the plot.
68#[derive(Clone, Debug, Default)]
69pub struct Labels {
70    pub title: Option<String>,
71    pub subtitle: Option<String>,
72    pub x: Option<String>,
73    pub y: Option<String>,
74    pub caption: Option<String>,
75    /// Corner tag (R's `labs(tag = ...)`), e.g. "A" for figure panels.
76    pub tag: Option<String>,
77}
78
79/// A single layer in the plot.
80pub struct Layer {
81    pub data: Option<DataFrame>,
82    pub mapping: Aes,
83    pub geom: Box<dyn Geom>,
84    pub stat: Box<dyn Stat>,
85    pub position: Box<dyn Position>,
86    pub params: GeomParams,
87    pub show_legend: Option<bool>,
88    /// The geom was configured explicitly (`geom_*_with(...)`), so its colours
89    /// are deliberate and the theme's `primary_color` must not override them.
90    pub explicit_style: bool,
91    /// A `{column}` tooltip template ([`GGPlot::tooltip`]), rendered per row
92    /// from the *built* layer data (post-stat) once that's available.
93    pub tooltip_template: Option<String>,
94}
95
96/// The top-level plot specification — builder pattern.
97pub struct GGPlot {
98    pub(crate) data: DataFrame,
99    pub(crate) mapping: Aes,
100    pub(crate) layers: Vec<Layer>,
101    pub(crate) scales: Vec<Box<dyn Scale>>,
102    pub(crate) coord: Box<dyn Coord>,
103    pub(crate) theme: Theme,
104    pub(crate) labels: Labels,
105    pub(crate) facet: Facet,
106    pub(crate) annotations: Vec<Annotation>,
107    pub(crate) guide_legend: crate::guide::config::GuideLegend,
108    /// Warnings raised while specifying the plot (e.g. a clipped calendar
109    /// span); prepended to the build warnings.
110    pub(crate) warnings: Vec<String>,
111    /// [`GGPlot::legend_bottom_when_narrow`]'s share, if set (#287).
112    pub(crate) legend_bottom_share: Option<f64>,
113    /// Panel aspect ratio used when the theme sets none (helpers such as
114    /// `geom_calendar` need square cells; survives theme presets).
115    pub(crate) default_aspect_ratio: Option<f64>,
116    /// Plot-wide default locale for axis / legend labels ([`GGPlot::locale`]).
117    pub(crate) locale: Option<crate::locale::Locale>,
118    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/…
119    /// ([`svg_root_data`](Self::svg_root_data)). Default `true`; a consumer
120    /// overlaying a fragment on its own basemap (`render_svg_native_at`)
121    /// turns it off so the fragment adds no root attributes of its own.
122    pub(crate) svg_root_data: bool,
123    /// Extra root `<svg>` attributes requested via [`svg_attr`](Self::svg_attr)/
124    /// [`svg_attrs`](Self::svg_attrs), validated and applied at render time.
125    pub(crate) root_attrs: Vec<(String, String)>,
126    /// Whether to emit a `data-warnings` JSON array of the build warnings
127    /// on the root `<svg>` ([`svg_warnings_attr`](Self::svg_warnings_attr)).
128    /// Default off; byte-identical output when off.
129    pub(crate) svg_warnings_attr: bool,
130    /// Whether to emit `data-fvalue`/`data-fx` on marks
131    /// ([`svg_formatted_values`](Self::svg_formatted_values)). Default off;
132    /// byte-identical output when off.
133    pub(crate) svg_formatted_values: bool,
134    /// #221: validated [`layer_svg_attr`](Self::layer_svg_attr)s as
135    /// `(layer index, name, value)`, applied by wrapping that layer's geom
136    /// at build time.
137    pub(crate) layer_svg_attrs: Vec<(usize, String, String)>,
138    /// #255: accessible name for the rendered root `<svg>`
139    /// ([`svg_title`](Self::svg_title)) — a `<title>` first child plus
140    /// `role="img"`/`aria-labelledby`. Default `None`; byte-identical
141    /// output when not set.
142    pub(crate) svg_title: Option<String>,
143    /// #255: accessible description for the rendered root `<svg>`
144    /// ([`svg_desc`](Self::svg_desc)) — a `<desc>` first child plus
145    /// `role="img"`/`aria-describedby`. Default `None`; byte-identical
146    /// output when not set.
147    pub(crate) svg_desc: Option<String>,
148}
149
150impl GGPlot {
151    /// Create a new plot with the given data source.
152    ///
153    /// Never panics on malformed input: e.g. column-oriented data whose columns
154    /// have different lengths is padded with `NA` and reported as a
155    /// [`GGError::ValidationError`] by [`try_build`](Self::try_build) and the
156    /// `render_*`/`save*` methods.
157    pub fn new(data: impl GGData) -> Self {
158        GGPlot {
159            data: data.into_dataframe(),
160            mapping: Aes::default(),
161            layers: Vec::new(),
162            scales: Vec::new(),
163            coord: Box::new(CoordCartesian::new()),
164            theme: Theme::default(),
165            labels: Labels::default(),
166            facet: Facet::default(),
167            annotations: Vec::new(),
168            guide_legend: crate::guide::config::GuideLegend::default(),
169            warnings: Vec::new(),
170            legend_bottom_share: None,
171            default_aspect_ratio: None,
172            locale: None,
173            svg_root_data: true,
174            root_attrs: Vec::new(),
175            svg_warnings_attr: false,
176            svg_formatted_values: false,
177            layer_svg_attrs: Vec::new(),
178            svg_title: None,
179            svg_desc: None,
180        }
181    }
182
183    /// Set the plot-level aesthetic mapping.
184    pub fn aes(mut self, mapping: Aes) -> Self {
185        self.warnings.extend(mapping.warnings.iter().cloned());
186        self.mapping = mapping;
187        self
188    }
189
190    // ─── Geom shortcuts ──────────────────────────────────────────
191
192    pub fn geom_point(self) -> Self {
193        self.add_geom(GeomPoint::default())
194    }
195
196    pub fn geom_point_with(self, geom: GeomPoint) -> Self {
197        self.add_geom_with(geom)
198    }
199
200    pub fn geom_line(self) -> Self {
201        self.add_geom(GeomLine::default())
202    }
203
204    pub fn geom_line_with(self, geom: GeomLine) -> Self {
205        self.add_geom_with(geom)
206    }
207
208    pub fn geom_bar(self) -> Self {
209        self.add_geom(GeomBar::default())
210    }
211
212    pub fn geom_bar_with(self, geom: GeomBar) -> Self {
213        self.add_geom_with(geom)
214    }
215
216    pub fn geom_histogram(self) -> Self {
217        self.add_geom(GeomHistogram::default())
218    }
219
220    pub fn geom_histogram_with(self, geom: GeomHistogram) -> Self {
221        self.add_geom_with(geom)
222    }
223
224    pub fn geom_boxplot(self) -> Self {
225        self.add_geom(GeomBoxplot::default())
226    }
227
228    pub fn geom_boxplot_with(self, geom: GeomBoxplot) -> Self {
229        self.add_geom_with(geom)
230    }
231
232    pub fn geom_smooth(self) -> Self {
233        self.add_geom(GeomSmooth::default())
234    }
235
236    pub fn geom_smooth_with(self, geom: GeomSmooth) -> Self {
237        self.add_geom_with(geom)
238    }
239
240    pub fn geom_col(self) -> Self {
241        self.add_geom(GeomCol::default())
242    }
243
244    pub fn geom_col_with(self, geom: GeomCol) -> Self {
245        self.add_geom_with(geom)
246    }
247
248    /// Horizontal reference line at a constant `yintercept`. Like ggplot2 the
249    /// intercept trains the y scale (the line is always visible) and the line
250    /// appears in every facet panel.
251    pub fn geom_hline(self, yintercept: f64) -> Self {
252        self.add_refline(
253            GeomHline::new(yintercept),
254            false,
255            &[("yintercept", yintercept)],
256        )
257    }
258
259    /// Add a horizontal reference line with custom styling (color/linetype/width).
260    pub fn geom_hline_with(self, geom: GeomHline) -> Self {
261        let y = geom.yintercept;
262        self.add_refline(geom, true, &[("yintercept", y)])
263    }
264
265    /// Data-mapped horizontal lines (ggplot2's `geom_hline(aes(yintercept =
266    /// …))`): one line per row of the layer data (the plot data unless
267    /// [`layer_data`](Self::layer_data) follows), per facet panel, styled by
268    /// any `color`/`linetype`/`alpha` in `mapping`. The plot-level mapping is
269    /// not inherited.
270    ///
271    /// ```
272    /// # use ggplot_rs::prelude::*;
273    /// let thresholds: Vec<(String, Vec<Value>)> = vec![
274    ///     ("bound".into(), vec![Value::Float(-0.2), Value::Float(0.2)]),
275    /// ];
276    /// let svg = GGPlot::new(vec![
277    ///         ("lag".to_string(), vec![Value::Float(1.0), Value::Float(2.0)]),
278    ///         ("acf".to_string(), vec![Value::Float(0.5), Value::Float(0.1)]),
279    ///     ])
280    ///     .aes(Aes::new().x("lag").y("acf"))
281    ///     .geom_col()
282    ///     .geom_hline_aes(Aes::new().yintercept("bound"))
283    ///     .layer_data(thresholds)
284    ///     .render_svg_native()
285    ///     .unwrap();
286    /// assert!(svg.contains("data-value=\"0.2\""));
287    /// ```
288    pub fn geom_hline_aes(self, mapping: Aes) -> Self {
289        self.add_geom(GeomHline::mapped()).layer_aes(mapping)
290    }
291
292    /// [`geom_hline_aes`](Self::geom_hline_aes) with custom default styling.
293    pub fn geom_hline_aes_with(self, geom: GeomHline, mapping: Aes) -> Self {
294        self.add_geom_with(geom).layer_aes(mapping)
295    }
296
297    /// Vertical reference line at a constant `xintercept` (trains the x
298    /// scale, appears in every panel).
299    pub fn geom_vline(self, xintercept: f64) -> Self {
300        self.add_refline(
301            GeomVline::new(xintercept),
302            false,
303            &[("xintercept", xintercept)],
304        )
305    }
306
307    /// Add a vertical reference line with custom styling (color/linetype/width).
308    pub fn geom_vline_with(self, geom: GeomVline) -> Self {
309        let x = geom.xintercept;
310        self.add_refline(geom, true, &[("xintercept", x)])
311    }
312
313    /// Data-mapped vertical lines (`aes(xintercept = …)`), one per row; see
314    /// [`geom_hline_aes`](Self::geom_hline_aes).
315    pub fn geom_vline_aes(self, mapping: Aes) -> Self {
316        self.add_geom(GeomVline::mapped()).layer_aes(mapping)
317    }
318
319    /// [`geom_vline_aes`](Self::geom_vline_aes) with custom default styling.
320    pub fn geom_vline_aes_with(self, geom: GeomVline, mapping: Aes) -> Self {
321        self.add_geom_with(geom).layer_aes(mapping)
322    }
323
324    /// Line `y = intercept + slope · x` in data space, clipped to the panel.
325    /// It does not train any scale (as in ggplot2).
326    pub fn geom_abline(self, slope: f64, intercept: f64) -> Self {
327        self.add_refline(
328            GeomAbline::new(slope, intercept),
329            false,
330            &[("slope", slope), ("intercept", intercept)],
331        )
332    }
333
334    /// Add a slope/intercept reference line with custom styling.
335    pub fn geom_abline_with(self, geom: GeomAbline) -> Self {
336        let (b, a) = (geom.slope, geom.intercept);
337        self.add_refline(geom, true, &[("slope", b), ("intercept", a)])
338    }
339
340    /// Data-mapped ablines (`aes(slope = …, intercept = …)`), one per row; a
341    /// missing aesthetic defaults to slope 1 / intercept 0.
342    pub fn geom_abline_aes(self, mapping: Aes) -> Self {
343        self.add_geom(GeomAbline::mapped()).layer_aes(mapping)
344    }
345
346    /// [`geom_abline_aes`](Self::geom_abline_aes) with custom default styling.
347    pub fn geom_abline_aes_with(self, geom: GeomAbline, mapping: Aes) -> Self {
348        self.add_geom_with(geom).layer_aes(mapping)
349    }
350
351    /// A constant reference line as ggplot2 builds it: a one-row layer frame
352    /// holding the constants, mapped to their aesthetics.
353    fn add_refline(
354        self,
355        geom: impl Geom + 'static,
356        explicit: bool,
357        values: &[(&str, f64)],
358    ) -> Self {
359        let mut data = DataFrame::new();
360        let mut mapping = Aes::new();
361        for (col, v) in values {
362            data.add_column(col.to_string(), vec![Value::Float(*v)]);
363            mapping = match *col {
364                "xintercept" => mapping.xintercept(col),
365                "yintercept" => mapping.yintercept(col),
366                "slope" => mapping.slope(col),
367                _ => mapping.intercept(col),
368            };
369        }
370        let plot = if explicit {
371            self.add_geom_with(geom)
372        } else {
373            self.add_geom(geom)
374        };
375        plot.layer_aes(mapping).layer_data(data)
376    }
377
378    pub fn geom_text(self) -> Self {
379        self.add_geom(GeomText::default())
380    }
381
382    pub fn geom_text_with(self, geom: GeomText) -> Self {
383        self.add_geom_with(geom)
384    }
385
386    /// Annotate with a correlation coefficient + p-value (`ggpubr::stat_cor()`).
387    /// Adds a text layer whose statistic computes Pearson correlation via
388    /// anofox-statistics; use [`GGPlot::stat_cor_with`] to pick Spearman or set
389    /// the label position.
390    #[cfg(feature = "ggpubr")]
391    pub fn stat_cor(self) -> Self {
392        self.geom_text().stat(crate::stat::cor::StatCor::default())
393    }
394
395    /// [`GGPlot::stat_cor`] with an explicit [`StatCor`](crate::stat::cor::StatCor)
396    /// (method / label position).
397    #[cfg(feature = "ggpubr")]
398    pub fn stat_cor_with(self, stat: crate::stat::cor::StatCor) -> Self {
399        self.geom_text().stat(stat)
400    }
401
402    /// Annotate grouped data with a group-comparison p-value
403    /// (`ggpubr::stat_compare_means()`). Adds a text layer whose statistic
404    /// compares y across the discrete x groups (Wilcoxon for two groups,
405    /// Kruskal-Wallis for more) via anofox-statistics.
406    #[cfg(feature = "ggpubr")]
407    pub fn stat_compare_means(self) -> Self {
408        self.geom_text()
409            .stat(crate::stat::compare_means::StatCompareMeans::default())
410    }
411
412    /// [`GGPlot::stat_compare_means`] with an explicit
413    /// [`StatCompareMeans`](crate::stat::compare_means::StatCompareMeans).
414    #[cfg(feature = "ggpubr")]
415    pub fn stat_compare_means_with(
416        self,
417        stat: crate::stat::compare_means::StatCompareMeans,
418    ) -> Self {
419        self.geom_text().stat(stat)
420    }
421
422    /// Auto-draw pairwise significance brackets (`ggpubr::stat_compare_means`
423    /// with `comparisons`). For each `(group_a, group_b)` pair it runs a
424    /// two-sample test (Wilcoxon by default) on the plot's y-values, formats the
425    /// p-value, and stacks a labelled [`geom_bracket`](GGPlot::geom_bracket)
426    /// above the data. Uses the plot's x/y mapping and data.
427    #[cfg(feature = "ggpubr")]
428    pub fn stat_compare_means_pairwise(self, comparisons: &[(&str, &str)]) -> Self {
429        self.stat_compare_means_pairwise_with(
430            crate::stat::compare_means::CompareMethod::Auto,
431            comparisons,
432        )
433    }
434
435    /// [`stat_compare_means_pairwise`](GGPlot::stat_compare_means_pairwise) with
436    /// an explicit test method.
437    #[cfg(feature = "ggpubr")]
438    pub fn stat_compare_means_pairwise_with(
439        self,
440        method: crate::stat::compare_means::CompareMethod,
441        comparisons: &[(&str, &str)],
442    ) -> Self {
443        // Resolve the x/y source columns from the plot mapping + data.
444        let col_for = |a: crate::aes::Aesthetic| {
445            self.mapping
446                .mappings
447                .iter()
448                .find(|m| m.aesthetic == a)
449                .map(|m| m.column.clone())
450        };
451        let (xcol, ycol) = match (
452            col_for(crate::aes::Aesthetic::X),
453            col_for(crate::aes::Aesthetic::Y),
454        ) {
455            (Some(x), Some(y)) => (x, y),
456            _ => return self,
457        };
458        let (xc, yc) = match (self.data.column(&xcol), self.data.column(&ycol)) {
459            (Some(x), Some(y)) => (x, y),
460            _ => return self,
461        };
462
463        // Bucket y by x category (first-seen order) and find the data range.
464        let mut groups: Vec<(String, Vec<f64>)> = Vec::new();
465        let mut ymax = f64::NEG_INFINITY;
466        let mut ymin = f64::INFINITY;
467        for (xv, yv) in xc.iter().zip(yc.iter()) {
468            let y = match yv.as_f64() {
469                Some(y) if y.is_finite() => y,
470                _ => continue,
471            };
472            ymax = ymax.max(y);
473            ymin = ymin.min(y);
474            let key = xv.to_group_key();
475            if let Some(g) = groups.iter_mut().find(|(k, _)| *k == key) {
476                g.1.push(y);
477            } else {
478                groups.push((key, vec![y]));
479            }
480        }
481        if groups.len() < 2 {
482            return self;
483        }
484        let step = if ymax > ymin {
485            (ymax - ymin) * 0.12
486        } else {
487            1.0
488        };
489
490        // One stacked bracket per resolvable comparison.
491        let (mut xmin_v, mut xmax_v, mut y_v, mut label_v) =
492            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
493        let mut placed = 0usize;
494        for (a, b) in comparisons {
495            let ga = groups.iter().find(|(k, _)| k == a).map(|g| &g.1);
496            let gb = groups.iter().find(|(k, _)| k == b).map(|g| &g.1);
497            let (ga, gb) = match (ga, gb) {
498                (Some(x), Some(y)) if x.len() >= 2 && y.len() >= 2 => (x, y),
499                _ => continue,
500            };
501            let p = match crate::stat::compare_means::pairwise_p(method, ga, gb) {
502                Some(p) => p,
503                None => continue,
504            };
505            xmin_v.push(Value::Str((*a).to_string()));
506            xmax_v.push(Value::Str((*b).to_string()));
507            y_v.push(Value::Float(ymax + step * (placed as f64 + 1.0)));
508            label_v.push(Value::Str(crate::stat::cor::format_p_value(p)));
509            placed += 1;
510        }
511        if xmin_v.is_empty() {
512            return self;
513        }
514
515        let data = vec![
516            ("xmin".to_string(), xmin_v),
517            ("xmax".to_string(), xmax_v),
518            ("y".to_string(), y_v),
519            ("label".to_string(), label_v),
520        ];
521        self.add_geom(crate::geom::bracket::GeomBracket::default())
522            .layer_data(data)
523            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
524    }
525
526    /// Draw a significance bracket over the plot (`ggpubr::geom_bracket`): a bar
527    /// spanning the categorical positions `xmin`..`xmax` at height `y`, captioned
528    /// with `label` (e.g. a p-value or significance stars). Pairs with a boxplot
529    /// and [`stat_compare_means`](GGPlot::stat_compare_means).
530    pub fn geom_bracket(self, xmin: &str, xmax: &str, y: f64, label: &str) -> Self {
531        self.geom_bracket_many(
532            crate::geom::bracket::GeomBracket::default(),
533            &[(xmin, xmax, y, label)],
534        )
535    }
536
537    /// Draw several significance brackets at once with a configured
538    /// [`GeomBracket`](crate::geom::bracket::GeomBracket). Each tuple is
539    /// `(xmin, xmax, y, label)`.
540    pub fn geom_bracket_many(
541        self,
542        geom: crate::geom::bracket::GeomBracket,
543        brackets: &[(&str, &str, f64, &str)],
544    ) -> Self {
545        let xmin = brackets
546            .iter()
547            .map(|b| Value::Str(b.0.to_string()))
548            .collect::<Vec<_>>();
549        let xmax = brackets
550            .iter()
551            .map(|b| Value::Str(b.1.to_string()))
552            .collect::<Vec<_>>();
553        let y = brackets
554            .iter()
555            .map(|b| Value::Float(b.2))
556            .collect::<Vec<_>>();
557        let label = brackets
558            .iter()
559            .map(|b| Value::Str(b.3.to_string()))
560            .collect::<Vec<_>>();
561        let data = vec![
562            ("xmin".to_string(), xmin),
563            ("xmax".to_string(), xmax),
564            ("y".to_string(), y),
565            ("label".to_string(), label),
566        ];
567        self.add_geom(geom)
568            .layer_data(data)
569            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
570    }
571
572    /// Significance brackets from a precomputed test table (ggpubr's
573    /// `stat_pvalue_manual` / `geom_bracket(data = …)`) — e.g. the anofox
574    /// `test` contract output (`group1`, `group2`, `p_adj`/`p_value`, optional
575    /// `y_position`, `label`). No test is recomputed. See
576    /// [`BracketTable`](crate::geom::bracket::BracketTable) for the column
577    /// rules, label templates (`"p = {p_adj}"`, `"{p.signif}"`) and the
578    /// automatic stacking of rows without a `y_position`. Rows that cannot be
579    /// drawn are dropped with a build warning.
580    pub fn geom_bracket_table(
581        mut self,
582        table: impl GGData,
583        spec: crate::geom::bracket::BracketTable,
584    ) -> Self {
585        let table = table.into_dataframe();
586        let col_for = |a: crate::aes::Aesthetic| {
587            self.mapping
588                .mappings
589                .iter()
590                .find(|m| m.aesthetic == a)
591                .map(|m| m.column.clone())
592        };
593        // The plot's x categories (to reject unknown groups) and finite y
594        // range (to stack brackets above the data).
595        let x_levels: Vec<String> = col_for(crate::aes::Aesthetic::X)
596            .and_then(|c| self.data.column(&c))
597            .filter(|col| col.iter().any(|v| matches!(v, Value::Str(_))))
598            .map(|col| {
599                let mut seen = std::collections::HashSet::new();
600                col.iter()
601                    .filter(|v| !v.is_na())
602                    .map(|v| v.to_group_key())
603                    .filter(|k| seen.insert(k.clone()))
604                    .collect()
605            })
606            .unwrap_or_default();
607        let y_range = col_for(crate::aes::Aesthetic::Y)
608            .and_then(|c| self.data.column(&c))
609            .and_then(|col| {
610                let (lo, hi) = col
611                    .iter()
612                    .filter_map(|v| v.as_f64())
613                    .filter(|v| v.is_finite())
614                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
615                        (lo.min(v), hi.max(v))
616                    });
617                (lo <= hi).then_some((lo, hi))
618            });
619        let mut warnings = Vec::new();
620        let resolved = spec.resolve(&table, &x_levels, y_range, &mut warnings);
621        self.warnings.extend(warnings);
622        match resolved {
623            Some(data) => self
624                .add_geom(crate::geom::bracket::GeomBracket::from(spec.geom))
625                .layer_data(data)
626                .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label")),
627            None => self,
628        }
629    }
630
631    /// Text labels that repel each other and their points
632    /// (`ggrepel::geom_text_repel`) — deterministic (seeded) layout; see
633    /// [`GeomTextRepel`](crate::geom::repel::GeomTextRepel). Requires `x`,
634    /// `y` and `label`.
635    pub fn geom_text_repel(self) -> Self {
636        self.add_geom(crate::geom::repel::GeomTextRepel::default())
637    }
638
639    /// [`geom_text_repel`](Self::geom_text_repel) with a configured geom
640    /// (padding, nudge, `max_overlaps`, seed, …).
641    pub fn geom_text_repel_with(self, geom: crate::geom::repel::GeomTextRepel) -> Self {
642        self.add_geom_with(geom)
643    }
644
645    /// Boxed labels that repel each other and their points
646    /// (`ggrepel::geom_label_repel`).
647    pub fn geom_label_repel(self) -> Self {
648        self.add_geom(crate::geom::repel::GeomLabelRepel::default())
649    }
650
651    /// [`geom_label_repel`](Self::geom_label_repel) with a configured geom.
652    pub fn geom_label_repel_with(self, geom: crate::geom::repel::GeomLabelRepel) -> Self {
653        self.add_geom_with(geom)
654    }
655
656    pub fn geom_label(self) -> Self {
657        self.add_geom(GeomLabel::default())
658    }
659
660    pub fn geom_label_with(self, geom: GeomLabel) -> Self {
661        self.add_geom_with(geom)
662    }
663
664    pub fn geom_area(self) -> Self {
665        self.add_geom(GeomArea::default())
666    }
667
668    pub fn geom_area_with(self, geom: GeomArea) -> Self {
669        self.add_geom_with(geom)
670    }
671
672    pub fn geom_ribbon(self) -> Self {
673        self.add_geom(GeomRibbon::default())
674    }
675
676    pub fn geom_ribbon_with(self, geom: GeomRibbon) -> Self {
677        self.add_geom_with(geom)
678    }
679
680    pub fn geom_errorbar(self) -> Self {
681        self.add_geom(GeomErrorbar::default())
682    }
683
684    pub fn geom_errorbar_with(self, geom: GeomErrorbar) -> Self {
685        self.add_geom_with(geom)
686    }
687
688    pub fn geom_segment(self) -> Self {
689        self.add_geom(GeomSegment::default())
690    }
691
692    pub fn geom_segment_with(self, geom: GeomSegment) -> Self {
693        self.add_geom_with(geom)
694    }
695
696    pub fn geom_density(self) -> Self {
697        self.add_geom(GeomDensity::default())
698    }
699
700    pub fn geom_density_with(self, geom: GeomDensity) -> Self {
701        self.add_geom_with(geom)
702    }
703
704    pub fn geom_rug(self) -> Self {
705        self.add_geom(GeomRug::default())
706    }
707
708    pub fn geom_rug_with(self, geom: GeomRug) -> Self {
709        self.add_geom_with(geom)
710    }
711
712    pub fn geom_jitter(self) -> Self {
713        self.add_geom(GeomJitter::default())
714    }
715
716    pub fn geom_jitter_with(self, geom: GeomJitter) -> Self {
717        self.add_geom_with(geom)
718    }
719
720    pub fn geom_path(self) -> Self {
721        self.add_geom(GeomPath::default())
722    }
723
724    pub fn geom_path_with(self, geom: GeomPath) -> Self {
725        self.add_geom_with(geom)
726    }
727
728    /// Add a confidence-ellipse layer (default 95%) as a path per group.
729    pub fn stat_ellipse(self) -> Self {
730        self.geom_path()
731            .stat(crate::stat::ellipse::StatEllipse::default())
732    }
733
734    /// Add a confidence-ellipse layer at the given level (0, 1).
735    pub fn stat_ellipse_level(self, level: f64) -> Self {
736        self.geom_path()
737            .stat(crate::stat::ellipse::StatEllipse::new(level))
738    }
739
740    /// Add a quantile-regression line for each `tau` as a separate path layer
741    /// (R's `stat_quantile`). Backed by anofox-regression (feature `regression`).
742    #[cfg(feature = "regression")]
743    pub fn stat_quantile(mut self, taus: &[f64]) -> Self {
744        for &tau in taus {
745            self = self
746                .geom_path()
747                .stat(crate::stat::quantile::StatQuantile::new(tau));
748        }
749        self
750    }
751
752    /// Quantile-regression lines at the quartiles (0.25, 0.5, 0.75).
753    #[cfg(feature = "regression")]
754    pub fn geom_quantile(self) -> Self {
755        self.stat_quantile(&[0.25, 0.5, 0.75])
756    }
757
758    pub fn geom_step(self) -> Self {
759        self.add_geom(GeomStep::default())
760    }
761
762    pub fn geom_step_with(self, geom: GeomStep) -> Self {
763        self.add_geom_with(geom)
764    }
765
766    pub fn geom_freqpoly(self) -> Self {
767        self.add_geom(GeomFreqpoly::default())
768    }
769
770    pub fn geom_freqpoly_with(self, geom: GeomFreqpoly) -> Self {
771        self.add_geom_with(geom)
772    }
773
774    pub fn geom_linerange(self) -> Self {
775        self.add_geom(GeomLinerange::default())
776    }
777
778    pub fn geom_linerange_with(self, geom: GeomLinerange) -> Self {
779        self.add_geom_with(geom)
780    }
781
782    pub fn geom_pointrange(self) -> Self {
783        self.add_geom(GeomPointrange::default())
784    }
785
786    pub fn geom_pointrange_with(self, geom: GeomPointrange) -> Self {
787        self.add_geom_with(geom)
788    }
789
790    pub fn geom_crossbar(self) -> Self {
791        self.add_geom(GeomCrossbar::default())
792    }
793
794    pub fn geom_crossbar_with(self, geom: GeomCrossbar) -> Self {
795        self.add_geom_with(geom)
796    }
797
798    pub fn geom_spoke(self) -> Self {
799        self.add_geom(GeomSpoke::default())
800    }
801
802    pub fn geom_spoke_with(self, geom: GeomSpoke) -> Self {
803        self.add_geom_with(geom)
804    }
805
806    pub fn geom_rect(self) -> Self {
807        self.add_geom(GeomRect::default())
808    }
809
810    pub fn geom_rect_with(self, geom: GeomRect) -> Self {
811        self.add_geom_with(geom)
812    }
813
814    pub fn geom_tile(self) -> Self {
815        self.add_geom(GeomTile::default())
816    }
817
818    pub fn geom_tile_with(self, geom: GeomTile) -> Self {
819        self.add_geom_with(geom)
820    }
821
822    /// Dense regular grid of filled cells (heatmap/raster) from x, y, fill.
823    pub fn geom_raster(self) -> Self {
824        self.add_geom(crate::geom::raster::GeomRaster::default())
825    }
826
827    pub fn geom_raster_with(self, geom: crate::geom::raster::GeomRaster) -> Self {
828        self.add_geom_with(geom)
829    }
830
831    pub fn geom_polygon(self) -> Self {
832        self.add_geom(GeomPolygon::default())
833    }
834
835    pub fn geom_polygon_with(self, geom: GeomPolygon) -> Self {
836        self.add_geom_with(geom)
837    }
838
839    /// Render simple-features geometry from a WKT `geometry` column (feature `sf`).
840    #[cfg(feature = "sf")]
841    pub fn geom_sf(self) -> Self {
842        self.add_geom(crate::geom::sf::GeomSf::default())
843    }
844
845    #[cfg(feature = "sf")]
846    pub fn geom_sf_with(self, geom: crate::geom::sf::GeomSf) -> Self {
847        self.add_geom_with(geom)
848    }
849
850    /// Labels placed inside `geom_sf` polygons (feature `sf`): `label`
851    /// aesthetic, `geometry` column — ggplot2's `geom_sf_text`.
852    #[cfg(feature = "sf")]
853    pub fn geom_sf_text(self) -> Self {
854        self.add_geom(crate::geom::sf_text::GeomSfText::default())
855    }
856
857    #[cfg(feature = "sf")]
858    pub fn geom_sf_text_with(self, geom: crate::geom::sf_text::GeomSfText) -> Self {
859        self.add_geom_with(geom)
860    }
861
862    /// Like [`geom_sf_text`](Self::geom_sf_text), on a background box —
863    /// ggplot2's `geom_sf_label`.
864    #[cfg(feature = "sf")]
865    pub fn geom_sf_label(self) -> Self {
866        self.add_geom(crate::geom::sf_text::GeomSfLabel::default())
867    }
868
869    #[cfg(feature = "sf")]
870    pub fn geom_sf_label_with(self, geom: crate::geom::sf_text::GeomSfLabel) -> Self {
871        self.add_geom_with(geom)
872    }
873
874    /// A metric scale bar in a panel corner (feature `sf`) — ggspatial's
875    /// `annotation_scale()`. Assumes the X/Y domain is in metres (any
876    /// `geom_sf` projection other than `SfProjection::PlateCarree`).
877    #[cfg(feature = "sf")]
878    pub fn annotation_scale(self) -> Self {
879        self.add_geom(crate::geom::annotation_scale::GeomAnnotationScale::default())
880    }
881
882    #[cfg(feature = "sf")]
883    pub fn annotation_scale_with(
884        self,
885        geom: crate::geom::annotation_scale::GeomAnnotationScale,
886    ) -> Self {
887        self.add_geom_with(geom)
888    }
889
890    /// A small, muted attribution text in a panel corner (feature `sf`) —
891    /// e.g. `"© Natural Earth"`.
892    #[cfg(feature = "sf")]
893    pub fn annotation_attribution(self, text: impl Into<String>) -> Self {
894        self.add_geom(crate::geom::annotation_scale::GeomAttribution::new(text))
895    }
896
897    #[cfg(feature = "sf")]
898    pub fn annotation_attribution_with(
899        self,
900        geom: crate::geom::annotation_scale::GeomAttribution,
901    ) -> Self {
902        self.add_geom_with(geom)
903    }
904
905    /// The square `n × m` guide for a
906    /// [`ScaleFillBivariate`](crate::scale::bivariate::ScaleFillBivariate)
907    /// fill scale (feature `sf`): two axis captions, biscale's own legend
908    /// shape — drawn as a furniture layer, not through the ordinary
909    /// per-aesthetic legend (set `.legend_position(LegendPosition::None)`
910    /// to hide that one). [`GeomBivariateLegend::from_scale`] builds this
911    /// from the same scale used for the fill, so the swatches match.
912    #[cfg(feature = "sf")]
913    pub fn bivariate_legend(
914        self,
915        geom: crate::geom::bivariate_legend::GeomBivariateLegend,
916    ) -> Self {
917        self.add_geom(geom)
918    }
919
920    /// Like [`Self::bivariate_legend`], but with each cell's row count
921    /// drawn centred in its swatch — build with
922    /// [`GeomBivariateLegend::counts`](crate::geom::bivariate_legend::GeomBivariateLegend::counts)
923    /// (#259).
924    #[cfg(feature = "sf")]
925    pub fn bivariate_legend_counts(
926        self,
927        geom: crate::geom::bivariate_legend::GeomBivariateLegendCounts,
928    ) -> Self {
929        self.add_geom(geom)
930    }
931
932    pub fn geom_curve(self) -> Self {
933        self.add_geom(GeomCurve::default())
934    }
935
936    pub fn geom_curve_with(self, geom: GeomCurve) -> Self {
937        self.add_geom_with(geom)
938    }
939
940    pub fn geom_violin(self) -> Self {
941        self.add_geom(GeomViolin::default())
942    }
943
944    pub fn geom_violin_with(self, geom: GeomViolin) -> Self {
945        self.add_geom_with(geom)
946    }
947
948    pub fn geom_dotplot(self) -> Self {
949        self.add_geom(GeomDotplot::default())
950    }
951
952    pub fn geom_dotplot_with(self, geom: GeomDotplot) -> Self {
953        self.add_geom_with(geom)
954    }
955
956    pub fn geom_qq(self) -> Self {
957        self.add_geom(GeomQQ::default())
958    }
959
960    pub fn geom_qq_with(self, geom: GeomQQ) -> Self {
961        self.add_geom_with(geom)
962    }
963
964    pub fn geom_qq_line(self) -> Self {
965        self.add_geom(GeomQQLine::default())
966    }
967
968    pub fn geom_qq_line_with(self, geom: GeomQQLine) -> Self {
969        self.add_geom_with(geom)
970    }
971
972    pub fn geom_bin2d(self) -> Self {
973        self.add_geom(GeomBin2d::default())
974    }
975
976    pub fn geom_bin2d_with(self, geom: GeomBin2d) -> Self {
977        self.add_geom_with(geom)
978    }
979
980    pub fn geom_hex(self) -> Self {
981        self.add_geom(GeomHex::default())
982    }
983
984    pub fn geom_hex_with(self, geom: GeomHex) -> Self {
985        self.add_geom_with(geom)
986    }
987
988    pub fn geom_count(self) -> Self {
989        self.add_geom(GeomCount::default())
990    }
991
992    pub fn geom_count_with(self, geom: GeomCount) -> Self {
993        self.add_geom_with(geom)
994    }
995
996    pub fn geom_contour(self) -> Self {
997        self.add_geom(GeomContour::default())
998    }
999
1000    pub fn geom_contour_with(self, geom: GeomContour) -> Self {
1001        self.add_geom_with(geom)
1002    }
1003
1004    /// Filled contour bands from gridded (x, y, z) data — draws polygons filled by
1005    /// band level. Pair with a continuous fill scale (e.g. `scale_fill_viridis_c`).
1006    pub fn geom_contour_filled(self) -> Self {
1007        self.add_geom(GeomPolygon {
1008            line_width: 0.0,
1009            alpha: 1.0,
1010            ..GeomPolygon::default()
1011        })
1012        .stat(crate::stat::contour_filled::StatContourFilled::default())
1013    }
1014
1015    pub fn geom_density2d(self) -> Self {
1016        self.add_geom(GeomDensity2d::default())
1017    }
1018
1019    pub fn geom_density2d_with(self, geom: GeomDensity2d) -> Self {
1020        self.add_geom_with(geom)
1021    }
1022
1023    /// Candlestick chart: map `x` and `open`/`high`/`low`/`close`
1024    /// (`Aes::new().x("date").open("o").high("h").low("l").close("c")`).
1025    pub fn geom_candlestick(self) -> Self {
1026        self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
1027    }
1028
1029    pub fn geom_candlestick_with(self, geom: crate::geom::candlestick::GeomCandlestick) -> Self {
1030        self.add_geom_with(geom)
1031    }
1032
1033    /// OHLC bar chart (high–low bar with open/close ticks); same aesthetics as
1034    /// [`geom_candlestick`](Self::geom_candlestick).
1035    pub fn geom_ohlc(self) -> Self {
1036        self.add_geom(crate::geom::candlestick::GeomOhlc::default())
1037    }
1038
1039    pub fn geom_ohlc_with(self, geom: crate::geom::candlestick::GeomOhlc) -> Self {
1040        self.add_geom_with(geom)
1041    }
1042
1043    /// Calendar heatmap (GitHub/ECharts style): the plot's `x` (a date —
1044    /// `DateTime`, epoch seconds or `"YYYY-MM-DD"`) is laid out as week
1045    /// columns × weekday rows (Sunday on top) via [`StatCalendar`], coloured
1046    /// by `fill`, with month labels along x, Mon/Wed/Fri along y, month
1047    /// boundary outlines and square cells. Spans over
1048    /// [`MAX_CALENDAR_YEARS`] are clipped to the most recent years (with a
1049    /// build warning). Uses the plot-level data and `x` mapping.
1050    ///
1051    /// [`StatCalendar`]: crate::stat::calendar::StatCalendar
1052    /// [`MAX_CALENDAR_YEARS`]: crate::stat::calendar::MAX_CALENDAR_YEARS
1053    pub fn geom_calendar(self) -> Self {
1054        self.geom_calendar_with(
1055            GeomTile {
1056                color: (255, 255, 255),
1057                line_width: 1.5,
1058                ..Default::default()
1059            },
1060            false,
1061        )
1062    }
1063
1064    /// [`geom_calendar`](Self::geom_calendar) with a custom cell style and
1065    /// optionally Monday-first weeks.
1066    pub fn geom_calendar_with(mut self, tile: GeomTile, monday_first: bool) -> Self {
1067        use crate::stat::calendar::{
1068            day_number, month_boundaries, month_breaks, month_breaks_localized, weekday_labels,
1069            CalendarGrid, StatCalendar, MAX_CALENDAR_YEARS,
1070        };
1071        let grid = self
1072            .mapping
1073            .get_mapping(&crate::aes::Aesthetic::X)
1074            .and_then(|c| self.data.column(c))
1075            .and_then(|col| {
1076                CalendarGrid::from_days(col.iter().filter_map(day_number), monday_first)
1077            });
1078        let Some((grid, clipped)) = grid else {
1079            // No dates: an empty calendar layer (renders an empty panel).
1080            return self.add_geom_with(tile).stat(StatCalendar {
1081                grid: None,
1082                monday_first,
1083            });
1084        };
1085        if clipped {
1086            self.warnings.push(format!(
1087                "geom_calendar: dates more than {MAX_CALENDAR_YEARS} years before the newest were dropped"
1088            ));
1089        }
1090        let (xb, _) = month_breaks(&grid);
1091        // Rows: y = 6 - weekday; label Mon/Wed/Fri.
1092        let yb = if monday_first {
1093            vec![6.0, 4.0, 2.0]
1094        } else {
1095            vec![5.0, 3.0, 1.0]
1096        };
1097        let segs = month_boundaries(&grid);
1098        let col = |f: fn(&(f64, f64, f64, f64)) -> f64| -> Vec<Value> {
1099            segs.iter().map(|s| Value::Float(f(s))).collect()
1100        };
1101        let boundaries = vec![
1102            ("x".to_string(), col(|s| s.0)),
1103            ("y".to_string(), col(|s| s.1)),
1104            ("xend".to_string(), col(|s| s.2)),
1105            ("yend".to_string(), col(|s| s.3)),
1106        ];
1107        self.default_aspect_ratio = Some(7.0 / grid.n_weeks().max(1) as f64);
1108        let plot = self
1109            .add_geom_with(tile)
1110            .stat(StatCalendar {
1111                grid: Some(grid),
1112                monday_first,
1113            })
1114            .scale_x_continuous(
1115                ScaleContinuous::new()
1116                    .with_breaks(xb)
1117                    // Month / weekday names follow the plot locale.
1118                    .with_localized_labels(move |l| month_breaks_localized(&grid, l).1)
1119                    .with_expand(0.0, 0.0),
1120            )
1121            .scale_y_continuous(
1122                ScaleContinuous::new()
1123                    .with_breaks(yb)
1124                    .with_localized_labels(weekday_labels)
1125                    .with_expand(0.0, 0.0),
1126            );
1127        if segs.is_empty() {
1128            return plot;
1129        }
1130        // Styled by the theme's `calendar_month_border` at draw time.
1131        plot.add_geom_with(crate::geom::segment::GeomCalendarBorder)
1132            .layer_data(boundaries)
1133            .layer_aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
1134            .show_legend(false)
1135    }
1136
1137    pub fn geom_blank(self) -> Self {
1138        self.add_geom(GeomBlank)
1139    }
1140
1141    /// Add a geom configured explicitly by the caller: its colours win over
1142    /// the theme's `primary_color`.
1143    fn add_geom_with(self, geom: impl Geom + 'static) -> Self {
1144        let mut plot = self.add_geom(geom);
1145        if let Some(layer) = plot.layers.last_mut() {
1146            layer.explicit_style = true;
1147        }
1148        plot
1149    }
1150
1151    fn add_geom(mut self, geom: impl Geom + 'static) -> Self {
1152        let stat = geom.default_stat();
1153        let position = geom.default_position();
1154        let params = geom.default_params();
1155        self.layers.push(Layer {
1156            data: None,
1157            mapping: Aes::default(),
1158            geom: Box::new(geom),
1159            stat,
1160            position,
1161            params,
1162            show_legend: None,
1163            explicit_style: false,
1164            tooltip_template: None,
1165        });
1166        self
1167    }
1168
1169    // ─── Layer-level overrides ──────────────────────────────────
1170
1171    /// Override the stat for the most recently added layer.
1172    pub fn stat(mut self, stat: impl Stat + 'static) -> Self {
1173        if let Some(layer) = self.layers.last_mut() {
1174            layer.stat = Box::new(stat);
1175        }
1176        self
1177    }
1178
1179    /// Override the position for the most recently added layer.
1180    pub fn position(mut self, pos: impl Position + 'static) -> Self {
1181        if let Some(layer) = self.layers.last_mut() {
1182            layer.position = Box::new(pos);
1183        }
1184        self
1185    }
1186
1187    /// Override the data for the most recently added layer.
1188    pub fn layer_data(mut self, data: impl GGData) -> Self {
1189        if let Some(layer) = self.layers.last_mut() {
1190            layer.data = Some(data.into_dataframe());
1191        }
1192        self
1193    }
1194
1195    /// Override the aesthetic mapping for the most recently added layer.
1196    pub fn layer_aes(mut self, mapping: Aes) -> Self {
1197        self.warnings.extend(mapping.warnings.iter().cloned());
1198        if let Some(layer) = self.layers.last_mut() {
1199            layer.mapping = mapping;
1200        }
1201        self
1202    }
1203
1204    /// A `{column}` tooltip template for the most recently added layer
1205    /// (B2-5), replacing its default `<title>`. Each placeholder is filled
1206    /// from the *built* layer data (so it can reference a stat-computed
1207    /// column, e.g. a hex's `count`) at that row, formatted through the
1208    /// column's scale when it has one
1209    /// ([`Scale::format_value`](crate::scale::Scale::format_value)) — the same
1210    /// `data-fvalue` logic, but written into the tooltip text. A column
1211    /// that doesn't exist on this layer renders as empty, not literally
1212    /// `{column}`. `{{`/`}}` are literal braces. The result is escaped the
1213    /// same way any other tooltip is — this is plain text, not markup.
1214    pub fn tooltip(mut self, template: &str) -> Self {
1215        if let Some(layer) = self.layers.last_mut() {
1216            layer.tooltip_template = Some(template.to_string());
1217        }
1218        self
1219    }
1220
1221    /// Control whether the most recently added layer contributes to the legend.
1222    /// `true` = always show, `false` = always hide, default (None) = auto.
1223    pub fn show_legend(mut self, show: bool) -> Self {
1224        if let Some(layer) = self.layers.last_mut() {
1225            layer.show_legend = Some(show);
1226        }
1227        self
1228    }
1229
1230    /// Mark the most recently added layer as purely decorative (#161): its
1231    /// drawn marks keep their own visual style but carry **no** per-mark
1232    /// metadata — no `<title>`, no `data-x`/`data-series`/`data-value`/
1233    /// `data-fvalue`, and no [`data_attr`](crate::aes::Aes::data_attr)
1234    /// attributes — so an SVG consumer that treats "has a non-empty
1235    /// `<title>`" as "is a selectable data point" doesn't pick it up. Meant
1236    /// for a layer that annotates another layer's mark rather than drawing
1237    /// data in its own right (e.g. a boxplot's own mean dot, drawn by a
1238    /// separate `geom_point` layer purely to mark the spot the box's own
1239    /// tooltip already names). Each mark also carries
1240    /// `data-part="decorative"` and `aria-hidden="true"` (`data-geom`
1241    /// still names the real geom), so a consumer can select decorative
1242    /// marks positively rather than only infer them from what they lack.
1243    /// Their class is `gg-mark gg-decorative`, not the geom's own
1244    /// (`gg-point`, `gg-line`, …).
1245    ///
1246    /// A `.tooltip(...)` template on a decorative layer has no visible
1247    /// effect — the geom's marks carry no tooltip regardless — and warns,
1248    /// like the existing has-no-effect warning for a geom that doesn't
1249    /// read tooltips at all.
1250    ///
1251    /// A decorative layer also defaults to hidden in the legend (it's
1252    /// annotating, not its own series), unless
1253    /// [`show_legend`](Self::show_legend)`(true)` is called — before or
1254    /// after `decorative()` — to opt back in; an explicit
1255    /// `show_legend(false)` is left untouched either way.
1256    pub fn decorative(mut self) -> Self {
1257        if let Some(layer) = self.layers.last_mut() {
1258            let geom = std::mem::replace(&mut layer.geom, Box::new(GeomBlank));
1259            layer.geom = Box::new(crate::geom::decorative::Decorative(geom));
1260            if layer.show_legend.is_none() {
1261                layer.show_legend = Some(false);
1262            }
1263        }
1264        self
1265    }
1266
1267    /// Add one SVG attribute to **every mark** of the most recently added
1268    /// layer (#221) — e.g. to make a label layer drawn over node boxes inert,
1269    /// so hover/click and screen readers pass through to the box below:
1270    ///
1271    /// ```
1272    /// # use ggplot_rs::{aes::Aes, data::Value, GGPlot};
1273    /// # let data = vec![("x".to_string(), vec![Value::Float(1.0)]),
1274    /// #   ("y".to_string(), vec![Value::Float(1.0)]),
1275    /// #   ("l".to_string(), vec![Value::Str("a".into())])];
1276    /// let svg = GGPlot::new(data)
1277    ///     .aes(Aes::new().x("x").y("y").label("l"))
1278    ///     .geom_text()
1279    ///     .layer_svg_attr("aria-hidden", "true")
1280    ///     .layer_svg_attr("pointer-events", "none")
1281    ///     .layer_svg_attr("class", "node-label")
1282    ///     .render_svg_native_with_size(200, 200)
1283    ///     .unwrap();
1284    /// assert!(svg.contains(r#"aria-hidden="true" pointer-events="none""#));
1285    /// ```
1286    ///
1287    /// The allow-list is deliberately small: `class` (space-separated
1288    /// tokens, each `[A-Za-z][A-Za-z0-9_-]*`, appended to the mark's own
1289    /// `gg-mark gg-<kind>` class; invalid tokens are dropped), `aria-hidden`
1290    /// (`"true"`/`"false"`), `pointer-events` (an SVG keyword such as
1291    /// `"none"`), and `data-*` (`Aes::data_attr`'s name rules; a row's own
1292    /// `data_attr` of the same name wins). Anything else — in particular
1293    /// `style` and `on*` handlers, so a strict CSP without `unsafe-inline`
1294    /// still holds — is ignored with a build warning, as is a bad value or a
1295    /// call before any layer. A later call with the same name replaces the
1296    /// earlier value. Values are escaped on output. For a per-row class use
1297    /// [`Aes::class`](crate::aes::Aes::class); to wrap several layers' marks
1298    /// per key in one `<g>`, [`Aes::group_wrap`](crate::aes::Aes::group_wrap).
1299    /// SVG backend only.
1300    pub fn layer_svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1301        let (name, value) = (name.into(), value.into());
1302        let Some(idx) = self.layers.len().checked_sub(1) else {
1303            self.warnings.push(format!(
1304                "layer_svg_attr(\"{name}\") called before any layer was added — ignored"
1305            ));
1306            return self;
1307        };
1308        if let Some((n, v)) =
1309            crate::render::svg_backend::validate_layer_svg_attr(&name, &value, &mut self.warnings)
1310        {
1311            self.layer_svg_attrs
1312                .retain(|(i, k, _)| !(*i == idx && *k == n));
1313            self.layer_svg_attrs.push((idx, n, v));
1314        }
1315        self
1316    }
1317
1318    /// [`layer_svg_attr`](Self::layer_svg_attr) for several attributes at once.
1319    pub fn layer_svg_attrs<N: Into<String>, V: Into<String>>(
1320        self,
1321        attrs: impl IntoIterator<Item = (N, V)>,
1322    ) -> Self {
1323        attrs
1324            .into_iter()
1325            .fold(self, |p, (n, v)| p.layer_svg_attr(n, v))
1326    }
1327
1328    // ─── Scales ──────────────────────────────────────────────────
1329
1330    pub fn scale_x_continuous(mut self, s: ScaleContinuous) -> Self {
1331        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1332        self.scales.push(Box::new(s));
1333        self
1334    }
1335
1336    pub fn scale_y_continuous(mut self, s: ScaleContinuous) -> Self {
1337        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1338        self.scales.push(Box::new(s));
1339        self
1340    }
1341
1342    pub fn scale_x_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
1343        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1344        self.scales.push(Box::new(s));
1345        self
1346    }
1347
1348    pub fn scale_y_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
1349        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1350        self.scales.push(Box::new(s));
1351        self
1352    }
1353
1354    pub fn scale_color(mut self, s: impl Scale + 'static) -> Self {
1355        self.scales.push(Box::new(s));
1356        self
1357    }
1358
1359    pub fn scale_fill(mut self, s: impl Scale + 'static) -> Self {
1360        self.scales.push(Box::new(s));
1361        self
1362    }
1363
1364    pub fn scale_color_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
1365        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Color, values);
1366        self.scale_color(s)
1367    }
1368
1369    pub fn scale_fill_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
1370        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Fill, values);
1371        self.scale_fill(s)
1372    }
1373
1374    /// The `colour`/`color` column already holds `#RRGGBB`/`#RGB` hex
1375    /// strings, used as-is — no legend (R's `scale_colour_identity`).
1376    pub fn scale_colour_identity(self) -> Self {
1377        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Color);
1378        self.scale_color(s)
1379    }
1380
1381    /// American-spelling alias for [`scale_colour_identity`](Self::scale_colour_identity).
1382    pub fn scale_color_identity(self) -> Self {
1383        self.scale_colour_identity()
1384    }
1385
1386    /// The `fill` column already holds `#RRGGBB`/`#RGB` hex strings, used
1387    /// as-is — no legend (R's `scale_fill_identity`).
1388    pub fn scale_fill_identity(self) -> Self {
1389        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Fill);
1390        self.scale_fill(s)
1391    }
1392
1393    pub fn scale_color_viridis(self) -> Self {
1394        use crate::scale::color::ScaleColorDiscrete;
1395        use crate::scale::palettes::PaletteName;
1396        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
1397            .with_named_palette(&PaletteName::Viridis);
1398        self.scale_color(s)
1399    }
1400
1401    pub fn scale_color_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
1402        use crate::scale::color::ScaleColorDiscrete;
1403        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).with_named_palette(&name);
1404        self.scale_color(s)
1405    }
1406
1407    pub fn scale_color_gradient(
1408        self,
1409        low: crate::scale::color::RGBAColor,
1410        high: crate::scale::color::RGBAColor,
1411    ) -> Self {
1412        use crate::scale::color::ScaleColorContinuous;
1413        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Color).with_colors(low, high);
1414        self.scale_color(s)
1415    }
1416
1417    pub fn scale_fill_gradient(
1418        self,
1419        low: crate::scale::color::RGBAColor,
1420        high: crate::scale::color::RGBAColor,
1421    ) -> Self {
1422        use crate::scale::color::ScaleColorContinuous;
1423        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Fill).with_colors(low, high);
1424        self.scale_fill(s)
1425    }
1426
1427    pub fn scale_color_gradient2(
1428        self,
1429        low: crate::scale::color::RGBAColor,
1430        mid: crate::scale::color::RGBAColor,
1431        high: crate::scale::color::RGBAColor,
1432    ) -> Self {
1433        use crate::scale::gradient::ScaleColorGradient2;
1434        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Color).with_colors(low, mid, high);
1435        self.scale_color(s)
1436    }
1437
1438    pub fn scale_fill_gradient2(
1439        self,
1440        low: crate::scale::color::RGBAColor,
1441        mid: crate::scale::color::RGBAColor,
1442        high: crate::scale::color::RGBAColor,
1443    ) -> Self {
1444        use crate::scale::gradient::ScaleColorGradient2;
1445        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Fill).with_colors(low, mid, high);
1446        self.scale_fill(s)
1447    }
1448
1449    pub fn scale_fill_viridis(self) -> Self {
1450        use crate::scale::color::ScaleColorDiscrete;
1451        use crate::scale::palettes::PaletteName;
1452        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
1453            .with_named_palette(&PaletteName::Viridis);
1454        self.scale_fill(s)
1455    }
1456
1457    /// Continuous viridis color scale (for numeric data).
1458    pub fn scale_color_viridis_c(self) -> Self {
1459        use crate::scale::gradient_n::ScaleColorGradientN;
1460        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Color);
1461        self.scale_color(s)
1462    }
1463
1464    /// Continuous viridis fill scale (for numeric data).
1465    pub fn scale_fill_viridis_c(self) -> Self {
1466        use crate::scale::gradient_n::ScaleColorGradientN;
1467        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Fill);
1468        self.scale_fill(s)
1469    }
1470
1471    /// N-stop continuous color gradient.
1472    pub fn scale_color_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
1473        use crate::scale::gradient_n::ScaleColorGradientN;
1474        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Color, stops);
1475        self.scale_color(s)
1476    }
1477
1478    /// N-stop continuous fill gradient.
1479    pub fn scale_fill_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
1480        use crate::scale::gradient_n::ScaleColorGradientN;
1481        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Fill, stops);
1482        self.scale_fill(s)
1483    }
1484
1485    /// Binned (stepped) two-colour continuous colour scale — buckets the mapped
1486    /// variable into `n_bins` bins, each a discrete colour, with a stepped legend.
1487    pub fn scale_color_steps(
1488        self,
1489        low: crate::scale::color::RGBAColor,
1490        high: crate::scale::color::RGBAColor,
1491        n_bins: usize,
1492    ) -> Self {
1493        let s = crate::scale::steps::ScaleColorSteps::two(
1494            crate::aes::Aesthetic::Color,
1495            (low.r, low.g, low.b),
1496            (high.r, high.g, high.b),
1497            n_bins,
1498        );
1499        self.scale_color(s)
1500    }
1501
1502    /// Binned N-stop continuous colour scale.
1503    pub fn scale_color_stepsn(
1504        self,
1505        stops: Vec<crate::scale::color::RGBAColor>,
1506        n_bins: usize,
1507    ) -> Self {
1508        let s = crate::scale::steps::ScaleColorSteps::new(
1509            crate::aes::Aesthetic::Color,
1510            stops.iter().map(|c| (c.r, c.g, c.b)).collect(),
1511            n_bins,
1512        );
1513        self.scale_color(s)
1514    }
1515
1516    /// Binned ColorBrewer colour scale (R's `scale_color_fermenter`).
1517    pub fn scale_color_fermenter(
1518        self,
1519        name: crate::scale::palettes::PaletteName,
1520        n_bins: usize,
1521    ) -> Self {
1522        let stops = crate::scale::palettes::palette(&name)
1523            .iter()
1524            .map(|c| (c.r, c.g, c.b))
1525            .collect();
1526        let s =
1527            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Color, stops, n_bins);
1528        self.scale_color(s)
1529    }
1530
1531    /// Binned (stepped) two-colour continuous fill scale.
1532    pub fn scale_fill_steps(
1533        self,
1534        low: crate::scale::color::RGBAColor,
1535        high: crate::scale::color::RGBAColor,
1536        n_bins: usize,
1537    ) -> Self {
1538        let s = crate::scale::steps::ScaleColorSteps::two(
1539            crate::aes::Aesthetic::Fill,
1540            (low.r, low.g, low.b),
1541            (high.r, high.g, high.b),
1542            n_bins,
1543        );
1544        self.scale_fill(s)
1545    }
1546
1547    /// Binned fill scale with *explicit* class breaks (`n + 1` increasing
1548    /// edges, `n` colours interpolated `low`→`high`) — R's
1549    /// `scale_fill_steps(breaks = ...)`, backing a `::CLASSES` choropleth
1550    /// (sipemu/ggplot-rs#180). The legend shows each class's trained count
1551    /// (`"10–50 (12)"`) and, when any value is `Value::Na`, a "no data" key
1552    /// in `na_color` (default grey50) — see
1553    /// [`ScaleFillBinned`](crate::scale::binned::ScaleFillBinned) for the
1554    /// `.na_color(..)`/`.na_label(..)` builders. The break maths itself
1555    /// (quantile/Jenks/equal-width/custom edges) is the caller's job; this
1556    /// only bins against the edges it's given.
1557    pub fn scale_fill_binned(
1558        self,
1559        breaks: Vec<f64>,
1560        low: crate::scale::color::RGBAColor,
1561        high: crate::scale::color::RGBAColor,
1562    ) -> Self {
1563        let s = crate::scale::binned::ScaleFillBinned::two(
1564            crate::aes::Aesthetic::Fill,
1565            breaks,
1566            (low.r, low.g, low.b),
1567            (high.r, high.g, high.b),
1568        );
1569        self.scale_fill(s)
1570    }
1571
1572    /// Like [`scale_fill_binned`](Self::scale_fill_binned), with an
1573    /// explicit colour per bin (`colors.len()` should be
1574    /// `breaks.len() - 1`) instead of a two-colour interpolation.
1575    pub fn scale_fill_binned_with(
1576        self,
1577        breaks: Vec<f64>,
1578        colors: Vec<crate::scale::color::RGBAColor>,
1579    ) -> Self {
1580        let s = crate::scale::binned::ScaleFillBinned::new(
1581            crate::aes::Aesthetic::Fill,
1582            breaks,
1583            colors.iter().map(|c| (c.r, c.g, c.b)).collect(),
1584        );
1585        self.scale_fill(s)
1586    }
1587
1588    /// Binned ColorBrewer fill scale.
1589    pub fn scale_fill_fermenter(
1590        self,
1591        name: crate::scale::palettes::PaletteName,
1592        n_bins: usize,
1593    ) -> Self {
1594        let stops = crate::scale::palettes::palette(&name)
1595            .iter()
1596            .map(|c| (c.r, c.g, c.b))
1597            .collect();
1598        let s =
1599            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Fill, stops, n_bins);
1600        self.scale_fill(s)
1601    }
1602
1603    /// Default discrete fill palette with levels in sorted order, so a level
1604    /// keeps its colour across charts regardless of data order. For a custom
1605    /// palette: `scale_fill(ScaleColorDiscrete::new(Aesthetic::Fill)
1606    /// .with_palette(p).sorted())`.
1607    pub fn scale_fill_discrete_sorted(self) -> Self {
1608        use crate::scale::color::ScaleColorDiscrete;
1609        self.scale_fill(ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).sorted())
1610    }
1611
1612    /// Default discrete colour palette with levels in sorted order (see
1613    /// [`scale_fill_discrete_sorted`](Self::scale_fill_discrete_sorted)).
1614    pub fn scale_color_discrete_sorted(self) -> Self {
1615        use crate::scale::color::ScaleColorDiscrete;
1616        self.scale_color(ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).sorted())
1617    }
1618
1619    pub fn scale_fill_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
1620        use crate::scale::color::ScaleColorDiscrete;
1621        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).with_named_palette(&name);
1622        self.scale_fill(s)
1623    }
1624
1625    pub fn scale_linetype_manual(
1626        self,
1627        values: Vec<(&str, crate::render::backend::Linetype)>,
1628    ) -> Self {
1629        let s = crate::scale::linetype_manual::ScaleLinetypeManual::new(values);
1630        self.scale_color(s)
1631    }
1632
1633    pub fn scale_shape_manual(
1634        self,
1635        values: Vec<(&str, crate::render::backend::PointShape)>,
1636    ) -> Self {
1637        let s = crate::scale::shape_manual::ScaleShapeManual::new(values);
1638        self.scale_color(s)
1639    }
1640
1641    pub fn scale_color_grey(self) -> Self {
1642        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Color);
1643        self.scale_color(s)
1644    }
1645
1646    pub fn scale_fill_grey(self) -> Self {
1647        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Fill);
1648        self.scale_fill(s)
1649    }
1650
1651    pub fn scale_color_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
1652        self.scale_color(s)
1653    }
1654
1655    pub fn scale_fill_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
1656        self.scale_fill(s)
1657    }
1658
1659    pub fn scale_x_reverse(self) -> Self {
1660        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
1661    }
1662
1663    pub fn scale_y_reverse(self) -> Self {
1664        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
1665    }
1666
1667    pub fn scale_x_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
1668        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1669        self.scales.push(Box::new(s));
1670        self
1671    }
1672
1673    pub fn scale_y_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
1674        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1675        self.scales.push(Box::new(s));
1676        self
1677    }
1678
1679    pub fn scale_size(mut self, s: crate::scale::size::ScaleSizeContinuous) -> Self {
1680        self.scales.push(Box::new(s));
1681        self
1682    }
1683
1684    /// `scale_size_area(max_size)` (ggplot2, B3-6): size scale where
1685    /// *area*, not radius, is proportional to the value, and 0 maps to 0.
1686    /// See [`ScaleSizeContinuous::area`](crate::scale::size::ScaleSizeContinuous::area).
1687    pub fn scale_size_area(mut self, max_size: f64) -> Self {
1688        self.scales.push(Box::new(
1689            crate::scale::size::ScaleSizeContinuous::new().area(max_size),
1690        ));
1691        self
1692    }
1693
1694    pub fn scale_alpha(mut self, s: crate::scale::alpha::ScaleAlphaContinuous) -> Self {
1695        self.scales.push(Box::new(s));
1696        self
1697    }
1698
1699    /// Continuous linewidth scale for the `linewidth` aesthetic (segment,
1700    /// curve, path, line) — see
1701    /// [`ScaleLinewidthContinuous`](crate::scale::linewidth::ScaleLinewidthContinuous).
1702    pub fn scale_linewidth(mut self, s: crate::scale::linewidth::ScaleLinewidthContinuous) -> Self {
1703        self.scales.push(Box::new(s));
1704        self
1705    }
1706
1707    pub fn xlim(self, min: f64, max: f64) -> Self {
1708        self.scale_x_continuous(ScaleContinuous::new().with_limits(min, max))
1709    }
1710
1711    pub fn ylim(self, min: f64, max: f64) -> Self {
1712        self.scale_y_continuous(ScaleContinuous::new().with_limits(min, max))
1713    }
1714
1715    pub fn scale_x_log10(self) -> Self {
1716        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
1717    }
1718
1719    pub fn scale_y_log10(self) -> Self {
1720        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
1721    }
1722
1723    pub fn scale_x_sqrt(self) -> Self {
1724        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
1725    }
1726
1727    pub fn scale_y_sqrt(self) -> Self {
1728        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
1729    }
1730
1731    pub fn scale_x_log2(self) -> Self {
1732        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
1733    }
1734
1735    pub fn scale_y_log2(self) -> Self {
1736        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
1737    }
1738
1739    pub fn scale_x_ln(self) -> Self {
1740        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
1741    }
1742
1743    pub fn scale_y_ln(self) -> Self {
1744        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
1745    }
1746
1747    /// Logit-transformed x axis (for proportions in (0, 1)).
1748    pub fn scale_x_logit(self) -> Self {
1749        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
1750    }
1751
1752    pub fn scale_y_logit(self) -> Self {
1753        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
1754    }
1755
1756    /// Probit-transformed x axis (inverse normal CDF, for proportions in (0, 1)).
1757    pub fn scale_x_probit(self) -> Self {
1758        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
1759    }
1760
1761    pub fn scale_y_probit(self) -> Self {
1762        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
1763    }
1764
1765    /// Sign-preserving pseudo-log x axis (handles zero and negative values).
1766    pub fn scale_x_pseudo_log(self) -> Self {
1767        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
1768    }
1769
1770    pub fn scale_y_pseudo_log(self) -> Self {
1771        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
1772    }
1773
1774    /// Reciprocal (1/x) x axis.
1775    pub fn scale_x_reciprocal(self) -> Self {
1776        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
1777    }
1778
1779    pub fn scale_y_reciprocal(self) -> Self {
1780        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
1781    }
1782
1783    /// Exponential x axis (labels spaced logarithmically).
1784    pub fn scale_x_exp(self) -> Self {
1785        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
1786    }
1787
1788    pub fn scale_y_exp(self) -> Self {
1789        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
1790    }
1791
1792    /// Box–Cox x axis with the given lambda (x > 0).
1793    pub fn scale_x_boxcox(self, lambda: f64) -> Self {
1794        self.scale_x_continuous(
1795            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
1796        )
1797    }
1798
1799    pub fn scale_y_boxcox(self, lambda: f64) -> Self {
1800        self.scale_y_continuous(
1801            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
1802        )
1803    }
1804
1805    // ─── Faceting ─────────────────────────────────────────────────
1806
1807    pub fn facet_wrap(mut self, var: &str, ncol: Option<usize>) -> Self {
1808        self.facet = Facet::Wrap {
1809            var: var.to_string(),
1810            ncol,
1811            scales: FacetScales::Fixed,
1812            labeller: FacetLabeller::default(),
1813        };
1814        self
1815    }
1816
1817    pub fn facet_wrap_free(mut self, var: &str, ncol: Option<usize>, scales: FacetScales) -> Self {
1818        self.facet = Facet::Wrap {
1819            var: var.to_string(),
1820            ncol,
1821            scales,
1822            labeller: FacetLabeller::default(),
1823        };
1824        self
1825    }
1826
1827    pub fn facet_wrap_labeller(
1828        mut self,
1829        var: &str,
1830        ncol: Option<usize>,
1831        labeller: FacetLabeller,
1832    ) -> Self {
1833        self.facet = Facet::Wrap {
1834            var: var.to_string(),
1835            ncol,
1836            scales: FacetScales::Fixed,
1837            labeller,
1838        };
1839        self
1840    }
1841
1842    pub fn facet_grid(mut self, row: Option<&str>, col: Option<&str>) -> Self {
1843        self.facet = Facet::Grid {
1844            row_var: row.map(String::from),
1845            col_var: col.map(String::from),
1846            scales: FacetScales::Fixed,
1847            labeller: FacetLabeller::default(),
1848            space: FacetSpace::Fixed,
1849        };
1850        self
1851    }
1852
1853    pub fn facet_grid_free(
1854        mut self,
1855        row: Option<&str>,
1856        col: Option<&str>,
1857        scales: FacetScales,
1858    ) -> Self {
1859        self.facet = Facet::Grid {
1860            row_var: row.map(String::from),
1861            col_var: col.map(String::from),
1862            scales,
1863            labeller: FacetLabeller::default(),
1864            space: FacetSpace::Fixed,
1865        };
1866        self
1867    }
1868
1869    /// `facet_grid` over **multiple** column variables (R's `rows ~ b + c`):
1870    /// the columns become the combination of the given variables' values.
1871    /// Also accepts free scales + proportional `space` for full parity.
1872    pub fn facet_grid_multi(
1873        mut self,
1874        row: Option<&str>,
1875        cols: &[&str],
1876        scales: FacetScales,
1877        space: FacetSpace,
1878    ) -> Self {
1879        let col_var = if cols.len() > 1 {
1880            // Build a synthetic column that is the interaction of the col vars.
1881            let n = self.data.nrows();
1882            let mut combined = Vec::with_capacity(n);
1883            for i in 0..n {
1884                let parts: Vec<String> = cols
1885                    .iter()
1886                    .map(|c| {
1887                        self.data
1888                            .column(c)
1889                            .and_then(|col| col.get(i))
1890                            .map(|v| v.to_group_key())
1891                            .unwrap_or_default()
1892                    })
1893                    .collect();
1894                combined.push(crate::data::Value::Str(parts.join(" . ")));
1895            }
1896            let name = "__facet_cols__".to_string();
1897            self.data.add_column(name.clone(), combined);
1898            Some(name)
1899        } else {
1900            cols.first().map(|s| s.to_string())
1901        };
1902        self.facet = Facet::Grid {
1903            row_var: row.map(String::from),
1904            col_var,
1905            scales,
1906            labeller: FacetLabeller::default(),
1907            space,
1908        };
1909        self
1910    }
1911
1912    /// `facet_grid` with proportional panel sizing (R's `space =`): panels are
1913    /// sized to their data range. Typically paired with free scales.
1914    pub fn facet_grid_space(
1915        mut self,
1916        row: Option<&str>,
1917        col: Option<&str>,
1918        scales: FacetScales,
1919        space: FacetSpace,
1920    ) -> Self {
1921        self.facet = Facet::Grid {
1922            row_var: row.map(String::from),
1923            col_var: col.map(String::from),
1924            scales,
1925            labeller: FacetLabeller::default(),
1926            space,
1927        };
1928        self
1929    }
1930
1931    pub fn facet_grid_labeller(
1932        mut self,
1933        row: Option<&str>,
1934        col: Option<&str>,
1935        labeller: FacetLabeller,
1936    ) -> Self {
1937        self.facet = Facet::Grid {
1938            row_var: row.map(String::from),
1939            col_var: col.map(String::from),
1940            scales: FacetScales::Fixed,
1941            labeller,
1942            space: FacetSpace::Fixed,
1943        };
1944        self
1945    }
1946
1947    // ─── Coordinates ─────────────────────────────────────────────
1948
1949    pub fn coord_flip(mut self) -> Self {
1950        self.coord = Box::new(CoordFlip);
1951        self
1952    }
1953
1954    pub fn coord_fixed(mut self, ratio: f64) -> Self {
1955        self.coord = Box::new(CoordFixed::new(ratio));
1956        self
1957    }
1958
1959    /// Spatial coordinate system (feature `sf`): equal aspect derived from the
1960    /// data extent, so projected geometry keeps its shape. Pair with a `geom_sf`
1961    /// projection (e.g. Mercator) for a conformal map.
1962    #[cfg(feature = "sf")]
1963    pub fn coord_sf(mut self) -> Self {
1964        self.coord = Box::new(crate::coord::sf::CoordSf::new());
1965        self
1966    }
1967
1968    /// Spatial coordinate system with explicit settings (`xlim`/`ylim`/
1969    /// `expand`) — see [`CoordSf`](crate::coord::sf::CoordSf). Used by
1970    /// consumers overlaying a fragment on their own projected basemap: a
1971    /// fixed pixel window via `xlim`/`ylim` and `expand(false)`.
1972    #[cfg(feature = "sf")]
1973    pub fn coord_sf_with(mut self, coord: crate::coord::sf::CoordSf) -> Self {
1974        self.coord = Box::new(coord);
1975        self
1976    }
1977
1978    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/
1979    /// `data-xdomain`/… (see [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
1980    /// Default `true`. A consumer that overlays a rendered fragment
1981    /// (`render_svg_native_at`) on its own basemap — which already has its
1982    /// own root attributes and window — turns this off so the fragment adds
1983    /// none of its own.
1984    pub fn svg_root_data(mut self, on: bool) -> Self {
1985        self.svg_root_data = on;
1986        self
1987    }
1988
1989    /// Add one extra attribute to the root `<svg>` element — a host
1990    /// identifier, an ARIA label, a CSS hook, and so on. Allowed names:
1991    /// `data-*`, `aria-*`, `role`, `id`, `class`, `lang`; anything else, or
1992    /// a name ggplot-rs already writes to the root (`data-plot`,
1993    /// `data-domain`, …, or `data-warnings` when
1994    /// [`svg_warnings_attr`](Self::svg_warnings_attr) is also on), is
1995    /// ignored with a build warning instead of being silently dropped or
1996    /// duplicated. Values are escaped on output. PlotGrid has the same API
1997    /// ([`PlotGrid::svg_attr`](crate::compose::PlotGrid::svg_attr)).
1998    pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1999        self.root_attrs.push((name.into(), value.into()));
2000        self
2001    }
2002
2003    /// [`svg_attr`](Self::svg_attr) for several attributes at once.
2004    pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
2005        self.root_attrs.extend(attrs);
2006        self
2007    }
2008
2009    /// Emit a `data-warnings` attribute on the root `<svg>` — a JSON array
2010    /// of the build warnings (rows dropped for non-finite positions, an
2011    /// `svg_attr` name rejected, …), `[]` when there are none. Default off,
2012    /// and omitted entirely when off (byte-identical to not calling this).
2013    pub fn svg_warnings_attr(mut self, on: bool) -> Self {
2014        self.svg_warnings_attr = on;
2015        self
2016    }
2017
2018    /// Emit `data-fvalue`/`data-fx` on marks: the value aesthetic's raw
2019    /// data value (y for most geoms, fill for hex/tile) and the x value,
2020    /// each formatted through its scale (currency/locale numbers, ISO or
2021    /// locale dates — [`Scale::format_value`](crate::scale::Scale::format_value))
2022    /// rather than the plain display string `data-value`/`data-x` already
2023    /// carry. `data-fx` is omitted when it would just duplicate `data-x`.
2024    /// Default off, and omitted entirely when off (byte-identical to not
2025    /// calling this).
2026    pub fn svg_formatted_values(mut self, on: bool) -> Self {
2027        self.svg_formatted_values = on;
2028        self
2029    }
2030
2031    /// Give the rendered root `<svg>` an accessible name: a `<title>`
2032    /// written (escaped) as its first child, plus `role="img"` and
2033    /// `aria-labelledby` pointing at that `<title>`'s id — the SVG
2034    /// accessibility practice of naming an image via `role="img"` +
2035    /// `aria-labelledby`/`-describedby` rather than a bare `<title>`,
2036    /// which some screen readers treat as a tooltip instead of a name.
2037    /// Pairs with [`svg_desc`](Self::svg_desc) for a longer description;
2038    /// either may be set alone. Default off (`None`), so output stays
2039    /// byte-identical when this is never called.
2040    pub fn svg_title(mut self, title: impl Into<String>) -> Self {
2041        self.svg_title = Some(title.into());
2042        self
2043    }
2044
2045    /// Give the rendered root `<svg>` an accessible description: a
2046    /// `<desc>` written (escaped) as a first child (after `<title>`, if
2047    /// [`svg_title`](Self::svg_title) is also set), plus `role="img"` and
2048    /// `aria-describedby` pointing at that `<desc>`'s id — e.g. a data
2049    /// summary like "4 regions; highest Bavaria (5.2); 1 without data".
2050    /// Default off (`None`), so output stays byte-identical when this is
2051    /// never called.
2052    pub fn svg_desc(mut self, desc: impl Into<String>) -> Self {
2053        self.svg_desc = Some(desc.into());
2054        self
2055    }
2056
2057    /// Transform the coordinate space at draw time (R's `coord_trans`) — stats are
2058    /// computed on raw data but drawn on non-linear axes. Pass a per-axis
2059    /// [`ScaleTransform`] (e.g. `Some(ScaleTransform::Log10)`), `None` to leave an
2060    /// axis linear.
2061    pub fn coord_trans(mut self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
2062        self.coord = Box::new(crate::coord::trans::CoordTrans::new(x, y));
2063        self
2064    }
2065
2066    /// `coord_trans` on the y-axis only.
2067    pub fn coord_trans_y(self, y: ScaleTransform) -> Self {
2068        self.coord_trans(None, Some(y))
2069    }
2070
2071    /// `coord_trans` on the x-axis only.
2072    pub fn coord_trans_x(self, x: ScaleTransform) -> Self {
2073        self.coord_trans(Some(x), None)
2074    }
2075
2076    /// Zoom into a region without filtering data (unlike xlim/ylim which filter).
2077    pub fn coord_cartesian_zoom(
2078        mut self,
2079        xlim: Option<(f64, f64)>,
2080        ylim: Option<(f64, f64)>,
2081    ) -> Self {
2082        let mut c = CoordCartesian::new();
2083        if let Some((min, max)) = xlim {
2084            c = c.xlim(min, max);
2085        }
2086        if let Some((min, max)) = ylim {
2087            c = c.ylim(min, max);
2088        }
2089        self.coord = Box::new(c);
2090        self
2091    }
2092
2093    pub fn coord_polar(mut self) -> Self {
2094        self.coord = Box::new(CoordPolar::new());
2095        self
2096    }
2097
2098    /// Radar / spider chart coordinates: discrete `x` → spokes, `y` → distance
2099    /// from the centre, straight segments, ring/spoke guides. Pair with
2100    /// `geom_polygon` (closed series) and `geom_point`.
2101    pub fn coord_radar(mut self) -> Self {
2102        self.coord = Box::new(crate::coord::radar::CoordRadar::new());
2103        self
2104    }
2105
2106    pub fn coord_radar_with(mut self, coord: crate::coord::radar::CoordRadar) -> Self {
2107        self.coord = Box::new(coord);
2108        self
2109    }
2110
2111    pub fn coord_polar_with(mut self, coord: CoordPolar) -> Self {
2112        self.coord = Box::new(coord);
2113        self
2114    }
2115
2116    // ─── Theme ───────────────────────────────────────────────────
2117
2118    /// Replace the theme. A `primary_color` set earlier is kept unless the new
2119    /// theme sets its own, so preset/`primary_color` call order doesn't matter.
2120    pub fn theme(mut self, theme: Theme) -> Self {
2121        self.apply_preset(theme);
2122        self
2123    }
2124
2125    fn apply_preset(&mut self, theme: Theme) {
2126        let primary = self.theme.primary;
2127        self.theme = theme;
2128        if self.theme.primary.is_none() {
2129            self.theme.primary = primary;
2130        }
2131    }
2132
2133    /// Rotate the x-axis tick labels by `degrees` (R's
2134    /// `guides(x = guide_axis(angle = ...))` / `axis.text.x = element_text(angle)`).
2135    /// Useful for long category labels. Call after any `theme_*()` preset.
2136    pub fn axis_text_x_angle(mut self, degrees: f64) -> Self {
2137        self.theme.axis_text_x.angle = degrees;
2138        self
2139    }
2140
2141    /// Rotate the y-axis tick labels by `degrees`.
2142    pub fn axis_text_y_angle(mut self, degrees: f64) -> Self {
2143        self.theme.axis_text_y.angle = degrees;
2144        self
2145    }
2146
2147    /// Stagger x-axis tick labels across `n` rows to avoid overlap (R's
2148    /// `guides(x = guide_axis(n.dodge = n))`). `1` = no dodging.
2149    pub fn axis_text_x_dodge(mut self, n: usize) -> Self {
2150        self.theme.axis_text_x_dodge = n.max(1);
2151        self
2152    }
2153
2154    /// Fix the panel's height:width ratio (R's `aspect.ratio`). Call after any
2155    /// `theme_*()` preset.
2156    pub fn aspect_ratio(mut self, ratio: f64) -> Self {
2157        self.theme.aspect_ratio = Some(ratio);
2158        self
2159    }
2160
2161    /// Draw gridlines on top of the data layers (R's `panel.ontop`).
2162    pub fn panel_ontop(mut self) -> Self {
2163        self.theme.panel_ontop = true;
2164        self
2165    }
2166
2167    /// Draw minor tick marks between major ticks (R's `axis.minor.ticks`).
2168    pub fn axis_minor_ticks(mut self) -> Self {
2169        self.theme.axis_minor_ticks = true;
2170        self
2171    }
2172
2173    /// How an outer x-axis label that would cross the SVG edge is handled
2174    /// (B3-1, D6): [`AxisLabelFit::Reserve`](crate::theme::AxisLabelFit::Reserve) (default), `Shift`, or `Clip`
2175    /// (the 0.21 behaviour). Use `Shift` for panels that must stay
2176    /// pixel-aligned with other elements (e.g. a host's own aligned strip).
2177    pub fn axis_text_x_fit(mut self, fit: crate::theme::AxisLabelFit) -> Self {
2178        self.theme.axis_text_x_fit = fit;
2179        self
2180    }
2181
2182    /// Thin crowded x-axis labels in ggplot2's `check.overlap` priority
2183    /// order (B3-1, D5). Off by default.
2184    pub fn axis_text_x_check_overlap(mut self, on: bool) -> Self {
2185        self.theme.axis_text_x_check_overlap = on;
2186        self
2187    }
2188
2189    /// Align title/subtitle/caption to the panel or the whole plot width
2190    /// (R's `plot.title.position`).
2191    pub fn title_position(mut self, pos: crate::theme::TitlePosition) -> Self {
2192        self.theme.title_position = pos;
2193        self
2194    }
2195
2196    /// Corner for the `tag()` label (R's `plot.tag.position`).
2197    pub fn tag_position(mut self, pos: crate::theme::TagPosition) -> Self {
2198        self.theme.tag_position = pos;
2199        self
2200    }
2201
2202    /// Force the legend key layout direction (R's `legend.direction`).
2203    pub fn legend_direction(mut self, dir: crate::theme::LegendDirection) -> Self {
2204        self.theme.legend_direction = Some(dir);
2205        self
2206    }
2207
2208    /// Set the brand/primary color used as the default for single-series geoms
2209    /// that have no color/fill aesthetic mapped. Composes with any theme — one
2210    /// render process can serve different tenants' brands at render time.
2211    /// Place the legend inside the panel at panel-relative coordinates
2212    /// (0..1, 0..1) — `(0,0)` bottom-left, `(1,1)` top-right (R's
2213    /// `legend.position = c(x, y)`).
2214    pub fn legend_position_inside(mut self, x: f64, y: f64) -> Self {
2215        self.theme.legend_position = crate::theme::LegendPosition::Inside(x, y);
2216        self
2217    }
2218
2219    /// Set the legend position (R's `legend.position`, e.g. `Top`/`Bottom`).
2220    pub fn legend_position(mut self, pos: crate::theme::LegendPosition) -> Self {
2221        self.theme.legend_position = pos;
2222        self
2223    }
2224
2225    /// Move a [`Right`](crate::theme::LegendPosition::Right) legend to
2226    /// `Bottom` (drawn horizontally) when it would take more than `share`
2227    /// (0..1) of the panel's width — the width the panel has with no legend
2228    /// at all (#287). The band is roughly fixed in size, so on a narrow
2229    /// render it can take most of the panel; a render wide enough keeps
2230    /// `Right`, unchanged. Off by default; no effect on any other position.
2231    pub fn legend_bottom_when_narrow(mut self, share: f64) -> Self {
2232        self.legend_bottom_share = Some(share);
2233        self
2234    }
2235
2236    pub fn primary_color(mut self, color: (u8, u8, u8)) -> Self {
2237        self.theme.primary = Some(color);
2238        self
2239    }
2240
2241    pub fn theme_minimal(mut self) -> Self {
2242        self.apply_preset(crate::theme::presets::theme_minimal());
2243        self
2244    }
2245
2246    pub fn theme_bw(mut self) -> Self {
2247        self.apply_preset(crate::theme::presets::theme_bw());
2248        self
2249    }
2250
2251    pub fn theme_gray(mut self) -> Self {
2252        self.apply_preset(crate::theme::presets::theme_gray());
2253        self
2254    }
2255
2256    pub fn theme_classic(mut self) -> Self {
2257        self.apply_preset(crate::theme::presets::theme_classic());
2258        self
2259    }
2260
2261    /// Apply the publication-ready `theme_pubr()` (ggpubr style).
2262    pub fn theme_pubr(mut self) -> Self {
2263        self.apply_preset(crate::theme::presets::theme_pubr());
2264        self
2265    }
2266
2267    pub fn theme_linedraw(mut self) -> Self {
2268        self.apply_preset(crate::theme::presets::theme_linedraw());
2269        self
2270    }
2271
2272    pub fn theme_light(mut self) -> Self {
2273        self.apply_preset(crate::theme::presets::theme_light());
2274        self
2275    }
2276
2277    pub fn theme_dark(mut self) -> Self {
2278        self.apply_preset(crate::theme::presets::theme_dark());
2279        self
2280    }
2281
2282    pub fn theme_void(mut self) -> Self {
2283        self.apply_preset(crate::theme::presets::theme_void());
2284        self
2285    }
2286
2287    /// Apply incremental theme modifications on top of the current theme.
2288    /// Like R's `+ theme(axis.text.x = element_text(...))`.
2289    pub fn theme_update(mut self, update: crate::theme::ThemeUpdate) -> Self {
2290        self.theme = self.theme.update(update);
2291        self
2292    }
2293
2294    // ─── Guides ──────────────────────────────────────────────────
2295
2296    /// Configure legend guide (title, ncol, reverse).
2297    pub fn guides(mut self, guide: crate::guide::config::GuideLegend) -> Self {
2298        self.guide_legend = guide;
2299        self
2300    }
2301
2302    // ─── Labels ──────────────────────────────────────────────────
2303
2304    pub fn labs(mut self, labels: Labels) -> Self {
2305        if labels.title.is_some() {
2306            self.labels.title = labels.title;
2307        }
2308        if labels.subtitle.is_some() {
2309            self.labels.subtitle = labels.subtitle;
2310        }
2311        if labels.x.is_some() {
2312            self.labels.x = labels.x;
2313        }
2314        if labels.y.is_some() {
2315            self.labels.y = labels.y;
2316        }
2317        if labels.caption.is_some() {
2318            self.labels.caption = labels.caption;
2319        }
2320        if labels.tag.is_some() {
2321            self.labels.tag = labels.tag;
2322        }
2323        self
2324    }
2325
2326    pub fn title(mut self, title: &str) -> Self {
2327        self.labels.title = Some(title.to_string());
2328        self
2329    }
2330
2331    /// Corner tag label (R's `labs(tag = ...)`), drawn at the top-left — handy
2332    /// for labelling figure panels ("A", "B", …).
2333    pub fn tag(mut self, tag: &str) -> Self {
2334        self.labels.tag = Some(tag.to_string());
2335        self
2336    }
2337
2338    pub fn subtitle(mut self, subtitle: &str) -> Self {
2339        self.labels.subtitle = Some(subtitle.to_string());
2340        self
2341    }
2342
2343    pub fn xlab(mut self, label: &str) -> Self {
2344        self.labels.x = Some(label.to_string());
2345        self
2346    }
2347
2348    pub fn ylab(mut self, label: &str) -> Self {
2349        self.labels.y = Some(label.to_string());
2350        self
2351    }
2352
2353    pub fn caption(mut self, caption: &str) -> Self {
2354        self.labels.caption = Some(caption.to_string());
2355        self
2356    }
2357
2358    // ─── Annotations ──────────────────────────────────────────────
2359
2360    /// Add an annotation to the plot.
2361    pub fn annotate(mut self, annotation: Annotation) -> Self {
2362        self.annotations.push(annotation);
2363        self
2364    }
2365
2366    /// Add a text annotation at data coordinates.
2367    pub fn annotate_text(self, label: &str, x: f64, y: f64) -> Self {
2368        self.annotate(Annotation::text(label, x, y))
2369    }
2370
2371    /// Add a rectangle annotation at data coordinates.
2372    pub fn annotate_rect(self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
2373        self.annotate(Annotation::rect(xmin, xmax, ymin, ymax))
2374    }
2375
2376    /// Add a segment annotation between data coordinates.
2377    pub fn annotate_segment(self, x: f64, y: f64, xend: f64, yend: f64) -> Self {
2378        self.annotate(Annotation::segment(x, y, xend, yend))
2379    }
2380
2381    /// Default [`Locale`](crate::locale::Locale) for the plot's axis and
2382    /// legend labels: every continuous position / colour / size / alpha scale
2383    /// labels its default breaks with the locale's decimal and thousands marks
2384    /// (`1.000`, `2,5` in de-DE), and date/datetime scales use its month names
2385    /// and date formats (`Okt. 2026`, `15. Okt. 2026`). A scale's own
2386    /// `with_locale` and custom `label_*` formatters take precedence.
2387    /// Without this call labels are unchanged (`.` decimal mark, no grouping,
2388    /// ISO dates).
2389    ///
2390    /// ```
2391    /// use ggplot_rs::prelude::*;
2392    /// let svg = GGPlot::new(vec![
2393    ///         ("x".to_string(), vec![Value::Float(0.0), Value::Float(3000.0)]),
2394    ///         ("y".to_string(), vec![Value::Float(0.5), Value::Float(2.5)]),
2395    ///     ])
2396    ///     .aes(Aes::new().x("x").y("y"))
2397    ///     .geom_point()
2398    ///     .locale(Locale::from_tag("de-DE"))
2399    ///     .render_svg_native()
2400    ///     .unwrap();
2401    /// assert!(svg.contains(">1.000<") && svg.contains(">1,5<"));
2402    /// ```
2403    pub fn locale(mut self, locale: crate::locale::Locale) -> Self {
2404        self.locale = Some(locale);
2405        self
2406    }
2407
2408    // ─── Build and Render ────────────────────────────────────────
2409
2410    /// Build the plot without rendering, returning errors on validation failure.
2411    pub fn try_build(self) -> Result<crate::build::BuiltPlot, GGError> {
2412        PlotBuilder::build(self)
2413    }
2414
2415    /// Build the plot without rendering (analogous to R's ggplot_build()).
2416    /// Returns the fully computed BuiltPlot with layer data ready for inspection.
2417    /// Panics on validation errors — use `try_build()` for error handling.
2418    pub fn build(self) -> crate::build::BuiltPlot {
2419        self.try_build().expect("plot build failed")
2420    }
2421
2422    /// Build and save the plot to a file. Format determined by extension.
2423    /// (Requires the `plotters` feature, on by default; native only — wasm has
2424    /// no filesystem/plotters backend.)
2425    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2426    pub fn save(self, path: &str) -> Result<(), GGError> {
2427        self.save_with_size(path, 800, 600)
2428    }
2429
2430    /// Build and save with custom dimensions. (Feature `plotters`; native only.)
2431    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2432    pub fn save_with_size(self, path: &str, w: u32, h: u32) -> Result<(), GGError> {
2433        let (built, layout) = self.prepare(w, h)?;
2434
2435        // Determine backend from file extension
2436        let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
2437
2438        match ext.as_str() {
2439            "svg" => {
2440                let backend = plotters::prelude::SVGBackend::new(path, (w, h));
2441                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2442            }
2443            "png" | "bmp" | "gif" | "jpeg" | "jpg" | "tiff" => {
2444                let backend = plotters::prelude::BitMapBackend::new(path, (w, h));
2445                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2446            }
2447            _ => {
2448                return Err(GGError::UnsupportedFormat(ext));
2449            }
2450        }
2451
2452        Ok(())
2453    }
2454
2455    /// Render the plot to an in-memory SVG document (default 800x600).
2456    ///
2457    /// Unlike [`save`](Self::save), this writes nothing to disk — handy for
2458    /// serving charts from a web/MCP service. Requires the `plotters` feature
2459    /// (on by default); without it use [`render_svg_native`](Self::render_svg_native).
2460    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2461    pub fn render_svg(self) -> Result<String, GGError> {
2462        self.render_svg_with_size(800, 600)
2463    }
2464
2465    /// Render the plot to an in-memory SVG document with custom dimensions.
2466    /// (Feature `plotters`; native only — on wasm or without `plotters` use
2467    /// [`render_svg_native_with_size`](Self::render_svg_native_with_size).)
2468    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2469    pub fn render_svg_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
2470        let (built, layout) = self.prepare(w, h)?;
2471        let mut buf = String::new();
2472        {
2473            let backend = plotters::prelude::SVGBackend::with_string(&mut buf, (w, h));
2474            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2475        }
2476        Ok(buf)
2477    }
2478
2479    /// Render to SVG through the self-contained [`SvgBackend`](crate::render::svg_backend::SvgBackend)
2480    /// — a plotters-free path that drives the same `PlotRenderer`, proving the
2481    /// `DrawBackend` abstraction (and needing no glyph rasterization).
2482    pub fn render_svg_native(self) -> Result<String, GGError> {
2483        self.render_svg_native_with_size(800, 600)
2484    }
2485
2486    /// [`render_svg_native`](Self::render_svg_native) with an explicit size.
2487    ///
2488    /// The root `<svg>` carries `data-plot="x y w h"` (the panel rect) and the
2489    /// trained position domains (`data-domain`, `data-xdomain`, `data-ydomain`,
2490    /// `data-xlevels`, `data-ylevels` — see
2491    /// [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
2492    /// Hoverable marks carry `data-x`, `data-series` and `data-value`.
2493    pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
2494        Ok(self.render_native(w, h)?.0.finish())
2495    }
2496
2497    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
2498    /// but also returns the build warnings (rows dropped for non-finite
2499    /// positions, layers whose stat produced no data, …) — see
2500    /// [`BuiltPlot::warnings`](crate::build::BuiltPlot::warnings).
2501    pub fn render_svg_native_with_warnings(
2502        self,
2503        w: u32,
2504        h: u32,
2505    ) -> Result<(String, Vec<String>), GGError> {
2506        let (backend, warnings, _) = self.render_native(w, h)?;
2507        Ok((backend.finish(), warnings))
2508    }
2509
2510    /// Render a `w`×`h` chart as a *nested* `<svg x=.. y=.. width=.. height=..
2511    /// viewBox="0 0 w h">` fragment for composition into a larger SVG (a
2512    /// dashboard): no `xmlns` (inherited from the parent), positioned at
2513    /// `(x, y)` in the parent's user space. No string surgery needed:
2514    ///
2515    /// ```ignore
2516    /// let mut page = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="900" height="400">"#);
2517    /// page += &plot_a.render_svg_native_at(0.0, 0.0, 450, 400)?;
2518    /// page += &plot_b.render_svg_native_at(450.0, 0.0, 450, 400)?;
2519    /// page += "</svg>";
2520    /// ```
2521    pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
2522        Ok(self.render_native(w, h)?.0.finish_fragment(x, y))
2523    }
2524
2525    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
2526    /// but also returns the panel rect in pixels `[x, y, w, h]` — enough to
2527    /// overlay a WebGL/canvas layer that draws marks in data coordinates.
2528    pub fn render_svg_area_with_size(self, w: u32, h: u32) -> Result<(String, [f64; 4]), GGError> {
2529        let (backend, _, pa) = self.render_native(w, h)?;
2530        Ok((backend.finish(), [pa.x, pa.y, pa.width, pa.height]))
2531    }
2532
2533    /// Shared native-SVG pipeline: build, lay out, render into an
2534    /// [`SvgBackend`](crate::render::svg_backend::SvgBackend) (not yet
2535    /// finished), returning it with the build warnings and the panel rect.
2536    fn render_native(
2537        self,
2538        w: u32,
2539        h: u32,
2540    ) -> Result<
2541        (
2542            crate::render::svg_backend::SvgBackend,
2543            Vec<String>,
2544            crate::render::Rect,
2545        ),
2546        GGError,
2547    > {
2548        let svg_root_data = self.svg_root_data;
2549        let root_attrs = self.root_attrs.clone();
2550        let svg_warnings_attr = self.svg_warnings_attr;
2551        let svg_formatted_values = self.svg_formatted_values;
2552        let svg_title = self.svg_title.clone();
2553        let svg_desc = self.svg_desc.clone();
2554        let (built, layout) = self.prepare(w, h)?;
2555        let pa = layout.plot_area.clone();
2556        let mut backend = crate::render::svg_backend::SvgBackend::new(w, h, pa.clone());
2557        backend.set_formatted_values(svg_formatted_values);
2558        backend.set_svg_title(svg_title.clone());
2559        backend.set_svg_desc(svg_desc.clone());
2560        let existing_root_attrs = if svg_root_data {
2561            let attrs = crate::render::svg_backend::root_data_attrs(&built);
2562            backend.set_root_attrs(attrs.clone());
2563            // `data-plot` itself is a literal in `root_open`, not part of
2564            // `root_data_attrs`'s output, but it is written whenever
2565            // `svg_root_data` is on — reserve it too.
2566            let mut reserved = attrs;
2567            reserved.push(("data-plot".to_string(), String::new()));
2568            reserved
2569        } else {
2570            backend.without_plot_attr();
2571            Vec::new()
2572        };
2573        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2574        let mut warnings = built.warnings;
2575        warnings.extend(backend.take_warnings());
2576
2577        let mut reserved = existing_root_attrs;
2578        if svg_warnings_attr {
2579            reserved.push(("data-warnings".to_string(), String::new()));
2580        }
2581        // #255: `role`/`aria-labelledby`/`aria-describedby` are written
2582        // directly by `SvgBackend::root_open` when a title/desc was set —
2583        // reserve them so a colliding `svg_attr` call is dropped with a
2584        // warning instead of duplicating the attribute.
2585        if svg_title.is_some() || svg_desc.is_some() {
2586            reserved.push(("role".to_string(), String::new()));
2587        }
2588        if svg_title.is_some() {
2589            reserved.push(("aria-labelledby".to_string(), String::new()));
2590        }
2591        if svg_desc.is_some() {
2592            reserved.push(("aria-describedby".to_string(), String::new()));
2593        }
2594        let extra = crate::render::svg_backend::validate_root_attrs(
2595            &root_attrs,
2596            &reserved,
2597            "plot",
2598            &mut warnings,
2599        );
2600        backend.extend_root_attrs(extra);
2601        if svg_warnings_attr {
2602            backend.extend_root_attrs(vec![(
2603                "data-warnings".to_string(),
2604                crate::render::svg_backend::warnings_json(&warnings),
2605            )]);
2606        }
2607        Ok((backend, warnings, pa))
2608    }
2609
2610    /// Render to a raw RGBA pixel buffer via the self-contained raster
2611    /// [`PixelBackend`](crate::render::pixel_backend::PixelBackend) (feature
2612    /// `canvas`) — fast for large-N and wasm-compatible. Returns `(w, h, rgba)`,
2613    /// ready for a `<canvas>` `putImageData`.
2614    #[cfg(feature = "canvas")]
2615    pub fn render_rgba_with_size(self, w: u32, h: u32) -> Result<(u32, u32, Vec<u8>), GGError> {
2616        let (built, layout) = self.prepare(w, h)?;
2617        let mut backend =
2618            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
2619        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2620        let (ow, oh) = backend.dimensions();
2621        Ok((ow, oh, backend.into_rgba()))
2622    }
2623
2624    /// Like [`render_rgba_with_size`](Self::render_rgba_with_size), but also
2625    /// returns the panel rect in pixels `[x, y, w, h]` — enough to map a canvas
2626    /// pixel back to data coordinates for interactive hover.
2627    #[cfg(feature = "canvas")]
2628    pub fn render_rgba_area_with_size(
2629        self,
2630        w: u32,
2631        h: u32,
2632    ) -> Result<(Vec<u8>, [f64; 4]), GGError> {
2633        let (built, layout) = self.prepare(w, h)?;
2634        let pa = layout.plot_area.clone();
2635        let mut backend = crate::render::pixel_backend::PixelBackend::new(w, h, pa.clone());
2636        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2637        Ok((backend.into_rgba(), [pa.x, pa.y, pa.width, pa.height]))
2638    }
2639
2640    /// Render to PNG bytes via the raster [`PixelBackend`](crate::render::pixel_backend::PixelBackend)
2641    /// (feature `canvas`). Unlike [`render_png`](Self::render_png) this needs no
2642    /// plotters bitmap backend, so it also works on wasm.
2643    #[cfg(feature = "canvas")]
2644    pub fn render_png_raster_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
2645        let (built, layout) = self.prepare(w, h)?;
2646        let mut backend =
2647            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
2648        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2649        backend.into_png().map_err(GGError::Render)
2650    }
2651
2652    /// Render the plot to in-memory PNG bytes (default 800x600).
2653    ///
2654    /// Returns a fully-encoded PNG, ready to write to an HTTP response or
2655    /// embed as a data URI — no temp files involved. Requires the `plotters`
2656    /// feature (on by default); see also `render_png_raster_with_size`
2657    /// (feature `canvas`).
2658    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2659    pub fn render_png(self) -> Result<Vec<u8>, GGError> {
2660        self.render_png_with_size(800, 600)
2661    }
2662
2663    /// Render the plot to in-memory PNG bytes with custom dimensions. (Feature
2664    /// `plotters`; native only — PNG needs the plotters bitmap backend.)
2665    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2666    pub fn render_png_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
2667        let (built, layout) = self.prepare(w, h)?;
2668
2669        // plotters' BitMapBackend draws into a raw RGB buffer; we then encode
2670        // that buffer to PNG via the `image` crate.
2671        let mut rgb = vec![0u8; (w as usize) * (h as usize) * 3];
2672        {
2673            let backend = plotters::prelude::BitMapBackend::with_buffer(&mut rgb, (w, h));
2674            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2675        }
2676
2677        let img = image::RgbImage::from_raw(w, h, rgb).ok_or_else(|| {
2678            GGError::Render(RenderError::BackendError(
2679                "PNG buffer size mismatch".to_string(),
2680            ))
2681        })?;
2682        let mut out = std::io::Cursor::new(Vec::new());
2683        img.write_to(&mut out, image::ImageOutputFormat::Png)
2684            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2685        Ok(out.into_inner())
2686    }
2687
2688    /// Shared pipeline: build the plot, apply label overrides, compute layout.
2689    pub(crate) fn prepare(
2690        self,
2691        w: u32,
2692        h: u32,
2693    ) -> Result<(crate::build::BuiltPlot, PlotLayout), GGError> {
2694        let (mut built, meta) = self.build_for_render()?;
2695        let layout = Self::layout_built(&mut built, &meta, w, h);
2696        Ok((built, layout))
2697    }
2698
2699    /// The size-independent half of [`prepare`](Self::prepare): build the plot,
2700    /// resolve theme inheritance and apply axis-label overrides.
2701    pub(crate) fn build_for_render(self) -> Result<(crate::build::BuiltPlot, RenderMeta), GGError> {
2702        let plot = self;
2703
2704        let has_title = plot.labels.title.is_some();
2705        let has_subtitle = plot.labels.subtitle.is_some();
2706        let has_caption = plot.labels.caption.is_some();
2707        let has_legend = plot.has_legend_mapping();
2708        let legend_bottom_share = plot.legend_bottom_share;
2709        let x_label = plot.labels.x.clone();
2710        let y_label = plot.labels.y.clone();
2711
2712        let mut built = PlotBuilder::build(plot)?;
2713
2714        // Resolve R-style theme inheritance (root `text` → child text elements).
2715        built.theme.resolve_inheritance();
2716
2717        // Apply user label overrides to scales
2718        if let Some(ref label) = x_label {
2719            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::X) {
2720                s.set_name(label);
2721            }
2722        }
2723        if let Some(ref label) = y_label {
2724            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::Y) {
2725                s.set_name(label);
2726            }
2727        }
2728
2729        Ok((
2730            built,
2731            RenderMeta {
2732                has_title,
2733                has_subtitle,
2734                has_caption,
2735                has_legend,
2736                legend_bottom_share,
2737            },
2738        ))
2739    }
2740
2741    /// The size-dependent half of [`prepare`](Self::prepare): auto-tune axis
2742    /// labels for `w`×`h` and compute the layout.
2743    pub(crate) fn layout_built(
2744        built: &mut crate::build::BuiltPlot,
2745        meta: &RenderMeta,
2746        w: u32,
2747        h: u32,
2748    ) -> PlotLayout {
2749        let RenderMeta {
2750            has_title,
2751            has_subtitle,
2752            has_caption,
2753            has_legend,
2754            legend_bottom_share,
2755        } = *meta;
2756        let x_axis_top = built
2757            .scales
2758            .get(&crate::aes::Aesthetic::X)
2759            .map(|s| s.axis_position_opposite())
2760            .unwrap_or(false);
2761
2762        // #287: decided first, so every legend pass below plans for the
2763        // position actually drawn, on this render's own layout.
2764        if let Some(share) = legend_bottom_share {
2765            if has_legend
2766                && matches!(
2767                    built.theme.legend_position,
2768                    crate::theme::LegendPosition::Right
2769                )
2770            {
2771                let panel_width = |pos| {
2772                    let mut theme = built.theme.clone();
2773                    theme.legend_position = pos;
2774                    PlotLayout::compute_with_extras(
2775                        w as f64,
2776                        h as f64,
2777                        &theme,
2778                        has_title,
2779                        has_subtitle,
2780                        has_caption,
2781                        has_legend,
2782                        x_axis_top,
2783                        None,
2784                        None,
2785                        crate::render::layout::LayoutExtras::default(),
2786                    )
2787                    .plot_area
2788                    .width
2789                };
2790                // Against the panel it would have with no legend at all
2791                // (the clamped minimum panel width hides the real band).
2792                let free = panel_width(crate::theme::LegendPosition::None);
2793                if panel_width(crate::theme::LegendPosition::Right) < (1.0 - share) * free {
2794                    built.theme.legend_position = crate::theme::LegendPosition::Bottom;
2795                }
2796            }
2797        }
2798
2799        // Auto-tune categorical axis labels so they stay legible. A flip swaps
2800        // which trained scale sits on each visual axis: the bottom (x) axis reads
2801        // the Y scale when flipped, the left (y) axis reads the X scale.
2802        let flipped = built.coord.is_flipped();
2803        let h_aes = if flipped {
2804            crate::aes::Aesthetic::Y
2805        } else {
2806            crate::aes::Aesthetic::X
2807        };
2808        let v_aes = if flipped {
2809            crate::aes::Aesthetic::X
2810        } else {
2811            crate::aes::Aesthetic::Y
2812        };
2813
2814        // The bottom-axis break labels that are actually drawn — a
2815        // `with_labels` override can blank some entries ("" ) to thin a
2816        // crowded discrete axis while keeping every position (sipemu/
2817        // ggplot-rs#162); a blanked entry is never drawn, so it never
2818        // competes for horizontal room or vertical drop below. Shared by
2819        // the auto-rotate decision and the rotated-label height reservation
2820        // just below, so both agree on what's actually on the canvas.
2821        let drawn_x_labels: Vec<(f64, String)> = built
2822            .scales
2823            .get(&h_aes)
2824            .map(|hs| {
2825                hs.breaks()
2826                    .into_iter()
2827                    .filter(|(_, label)| !label.is_empty())
2828                    .collect()
2829            })
2830            .unwrap_or_default();
2831        let h_is_discrete = built
2832            .scales
2833            .get(&h_aes)
2834            .map(|hs| hs.is_discrete())
2835            .unwrap_or(false);
2836
2837        // Crowded discrete bottom-axis labels overlap when drawn flat. Rotate
2838        // them — −45° if that de-collides, otherwise vertical (270°) — only
2839        // when no explicit angle was set (angle.abs() < 1.0 reads as
2840        // "unset"). Sized from the real, measured widths of the labels that
2841        // are actually drawn (`render::text::text_width`), both for the
2842        // label-width estimate and the crowding count `n` — #162's bug was
2843        // counting every break, blanked or not, which over-triggered the
2844        // rotation. −45° (not +45°) is ggplot2's own idiom (`angle = 45,
2845        // hjust = 1`, mirrored to this library's angle sign, sipemu/
2846        // ggplot-rs#163): it ends each label at its own tick and slants
2847        // down-left, rather than +45°'s down-right slant, which — anchored
2848        // the same way — would start under the *previous* category.
2849        if built.theme.axis_text_x.visible
2850            && built.theme.axis_text_x.angle.abs() < 1.0
2851            && h_is_discrete
2852            && !drawn_x_labels.is_empty()
2853        {
2854            let font = built.theme.axis_text_x.size;
2855            let max_w = drawn_x_labels
2856                .iter()
2857                .map(|(_, l)| crate::render::text::text_width(l, font))
2858                .fold(0.0_f64, f64::max);
2859            let n = drawn_x_labels.len() as f64;
2860            let spacing = 0.9 * w as f64 / n; // ~px between adjacent *drawn* labels
2861            if max_w > spacing {
2862                // 45° shrinks the horizontal footprint by cos45; if that
2863                // still doesn't fit, go vertical (270° = reads bottom-to-
2864                // top, hanging below the axis like the y-axis title).
2865                let vertical = max_w * std::f64::consts::FRAC_1_SQRT_2 > spacing;
2866                built.theme.axis_text_x.angle = if vertical { 270.0 } else { -45.0 };
2867            }
2868        }
2869
2870        // Whenever the bottom-axis labels end up rotated — by the
2871        // auto-rotate decision just above, or by an explicit
2872        // `axis_text_x_angle` call — reserve the real bottom space their
2873        // rotated bounding boxes need, so they never overlap the panel
2874        // (#162 also asked for this: an explicit angle reserved nothing).
2875        // `rotated_label_rise_fall` is the same helper `draw_x_axis` calls
2876        // to place its rotation anchor — `rise` must be reserved (as well
2877        // as placed) or a long enough label's far end swings right back up
2878        // over the panel regardless of how much height is reserved here;
2879        // `fall` just needs reserving so the label stays on-canvas. Both
2880        // here and in `draw_x_axis`, the anchor fraction must come from
2881        // `rotated_anchor_frac(angle, dir)` (sipemu/ggplot-rs#163) — not a
2882        // blind `1.0` — or the reservation is sized for the wrong end of
2883        // the label; `dir` matches `draw_x_axis`'s own tick direction.
2884        let x_label_height = if built.theme.axis_text_x.visible
2885            && built.theme.axis_text_x.angle.abs() > 10.0
2886            && !drawn_x_labels.is_empty()
2887        {
2888            let font = built.theme.axis_text_x.size;
2889            let angle = built.theme.axis_text_x.angle;
2890            let dir = if x_axis_top { -1.0 } else { 1.0 };
2891            let (rise, fall) = crate::render::text::rotated_label_rise_fall(
2892                drawn_x_labels.iter().map(|(_, l)| l.as_str()),
2893                font,
2894                angle,
2895                crate::render::text::rotated_anchor_frac(angle, dir),
2896            );
2897            Some(built.theme.legend_spacing / 2.0 + font / 2.0 + rise + fall)
2898        } else {
2899            None
2900        };
2901
2902        // Reserve the left-axis width from the actual label lengths so long
2903        // category names (a flipped bar chart's rows) aren't clipped. Never
2904        // shrinks below the default; grows up to 35% of the width.
2905        let y_label_width = if built.theme.axis_text_y.visible {
2906            built.scales.get(&v_aes).map(|vs| {
2907                let max_ch = vs
2908                    .breaks()
2909                    .iter()
2910                    .map(|(_, l)| l.chars().count())
2911                    .max()
2912                    .unwrap_or(0);
2913                let measured = max_ch as f64 * built.theme.axis_text_y.size * 0.6 + 4.0;
2914                let default = built.theme.axis_text_y.size * 3.5 + 4.0;
2915                measured.max(default).min(0.35 * w as f64)
2916            })
2917        } else {
2918            None
2919        };
2920
2921        // B3-1 (D6): reserve just enough left/right panel margin to keep
2922        // the outer x-axis labels on-canvas under `AxisLabelFit::Reserve`,
2923        // for a single (non-faceted) panel on a coord that supports it
2924        // (not polar/radar/sf, where a label bbox doesn't map to a simple
2925        // panel margin). A faceted plot skips the layout-level reservation
2926        // and relies on `draw_x_axis`'s own draw-time shift instead — so
2927        // does `AxisLabelFit::Shift` (the panel must keep its size) and
2928        // `Clip` (the 0.21 behaviour, no correction at all). A plot whose
2929        // outer labels already fit never grows `extras`, so it stays
2930        // byte-identical.
2931        let mut extras = crate::render::layout::LayoutExtras::default();
2932        let can_reserve = built.facet.is_none()
2933            && built.theme.axis_text_x.visible
2934            && built.theme.axis_text_x_fit == crate::theme::AxisLabelFit::Reserve
2935            && !built.coord.is_polar()
2936            && built.coord.supports_axis_reserve();
2937        if can_reserve {
2938            if let Some(hs) = built.scales.get(&h_aes) {
2939                let breaks = hs.breaks();
2940                if let (Some(first), Some(last)) = (breaks.first(), breaks.last()) {
2941                    let angle = built.theme.axis_text_x.angle;
2942                    let anchor = if angle.abs() > 10.0 {
2943                        let dir = if x_axis_top { -1.0 } else { 1.0 };
2944                        crate::render::text::rotated_anchor_frac(angle, dir)
2945                    } else {
2946                        0.5
2947                    };
2948                    let size = built.theme.axis_text_x.size;
2949                    const EDGE: f64 = 1.0;
2950                    for _ in 0..2 {
2951                        let layout = PlotLayout::compute_with_extras(
2952                            w as f64,
2953                            h as f64,
2954                            &built.theme,
2955                            has_title,
2956                            has_subtitle,
2957                            has_caption,
2958                            has_legend,
2959                            x_axis_top,
2960                            y_label_width,
2961                            x_label_height,
2962                            extras,
2963                        );
2964                        let area = &layout.plot_area;
2965                        let edge_y = area.y + area.height;
2966                        let to_point = |pos: f64| if flipped { (0.0, pos) } else { (pos, 0.0) };
2967                        let px_first = built.coord.transform(to_point(first.0), area).0;
2968                        let px_last = built.coord.transform(to_point(last.0), area).0;
2969                        let bbox_first = crate::render::text::label_bbox(
2970                            &first.1, size, px_first, edge_y, angle, anchor,
2971                        );
2972                        let bbox_last = crate::render::text::label_bbox(
2973                            &last.1, size, px_last, edge_y, angle, anchor,
2974                        );
2975                        let deficit_left = (EDGE - bbox_first[0]).max(0.0);
2976                        let deficit_right = (bbox_last[2] - (w as f64 - EDGE)).max(0.0);
2977                        if deficit_left <= 0.0 && deficit_right <= 0.0 {
2978                            break;
2979                        }
2980                        // Growing the left margin by `eL` (holding `eR` fixed)
2981                        // shifts a label at normalized position `p` right by
2982                        // `eL·(1 − p)`; growing the right margin by `eR`
2983                        // shifts it left by `eR·p` (the panel maps [0, 1] to
2984                        // [plot_x + eL, plot_x + width − eR]). Review #158
2985                        // finding 1: the original code divided by `p_first`
2986                        // and `1 − p_last` — inverted, which over-reserved
2987                        // by about `1/p_last` (≈20× at a typical p_last≈0.95).
2988                        let (p_first, p_last) = (first.0, last.0);
2989                        if deficit_left > 0.0 && deficit_right > 0.0 {
2990                            // Both ends overflow: solve the 2×2 system so
2991                            // each margin accounts for its effect on *both*
2992                            // labels, rather than correcting them
2993                            // independently and overshooting.
2994                            let (a, b, c, d) = (1.0 - p_first, p_first, 1.0 - p_last, p_last);
2995                            let det = a * d - b * c;
2996                            if det.abs() > 0.01 {
2997                                extras.left +=
2998                                    ((deficit_left * d + deficit_right * b) / det).max(0.0);
2999                                extras.right +=
3000                                    ((deficit_right * a + deficit_left * c) / det).max(0.0);
3001                            } else {
3002                                // Degenerate (first and last break nearly
3003                                // coincide in normalized space): fall back
3004                                // to the independent, clamped formulas.
3005                                extras.left += deficit_left / (1.0 - p_first).max(0.05);
3006                                extras.right += deficit_right / p_last.max(0.05);
3007                            }
3008                        } else if deficit_left > 0.0 {
3009                            extras.left += deficit_left / (1.0 - p_first).max(0.05);
3010                        } else if deficit_right > 0.0 {
3011                            extras.right += deficit_right / p_last.max(0.05);
3012                        }
3013                        // Cap the total reservation so the panel can never
3014                        // start beyond the canvas or be squeezed past the
3015                        // same minimum width `compute_with_extras` already
3016                        // floors it to (review #158's second re-review,
3017                        // LOW): a single, centred break whose label is
3018                        // wider than the whole canvas has `p_first ==
3019                        // p_last == 0.5`, so both `eL` and `eR` grow by
3020                        // roughly the same (large) deficit independently,
3021                        // and together they could place `plot_x` past `w`
3022                        // entirely. Past this cap, Reserve simply stops
3023                        // growing and `draw_x_axis`'s own draw-time shift
3024                        // — which always runs for Reserve, the same as for
3025                        // `Shift` — takes over for whatever's still
3026                        // outside, exactly as D6 already documents.
3027                        const MIN_PANEL_WIDTH: f64 = 50.0;
3028                        let cap = (w as f64 - MIN_PANEL_WIDTH).max(0.0);
3029                        if extras.left + extras.right > cap {
3030                            let scale = if extras.left + extras.right > 0.0 {
3031                                cap / (extras.left + extras.right)
3032                            } else {
3033                                0.0
3034                            };
3035                            extras.left *= scale;
3036                            extras.right *= scale;
3037                        }
3038                    }
3039                }
3040            }
3041        }
3042
3043        // B3-2 (D7): a discrete legend's `nrow`/`ncol` grid, or an
3044        // overflowing horizontal legend's auto-wrap, reserves extra legend
3045        // rows/width. Several simultaneous discrete guides (e.g. `colour`
3046        // and `shape` both mapped to discrete variables) each get their
3047        // own independent plan (sipemu/ggplot-rs#155) — previously this
3048        // only ran for exactly one discrete guide.
3049        if has_legend
3050            && !matches!(
3051                built.theme.legend_position,
3052                crate::theme::LegendPosition::None
3053            )
3054        {
3055            let legend_aes =
3056                crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
3057            // #236: a mapped `size` legend's largest key can need a bigger
3058            // box than the theme's flat defaults — independent of B3-2's
3059            // discrete-guide wrap planning below, so computed unconditionally.
3060            extras.legend_max_key_size = legend_aes
3061                .iter()
3062                .filter_map(|aes| {
3063                    let scale = built.scales.get(aes)?;
3064                    let breaks = scale.breaks();
3065                    Some(crate::guide::legend::size_key_diameter(
3066                        aes,
3067                        &built.scales,
3068                        scale,
3069                        &breaks,
3070                    ))
3071                })
3072                .fold(0.0_f64, f64::max);
3073            // #545: a continuous, non-colourbar guide (`Size`/
3074            // `Linewidth`/… sampled breaks) needs the same B3-2 wrap/grid
3075            // reservation pass a discrete guide gets — only a true
3076            // colourbar (continuous `Color`/`Fill`) is exempt, since it
3077            // draws as a fixed-width bar instead of sampled keys.
3078            // Previously this gate only fired for a discrete guide, so a
3079            // plot mapping *only* a continuous `Size`/`Linewidth` (no
3080            // discrete guide alongside it) skipped the whole reservation
3081            // pass and its legend could run straight off the panel/canvas
3082            // with no wrap, shrink, or "+N more" to catch it.
3083            let has_wrap_guide = legend_aes.iter().any(|a| {
3084                let is_discrete = built
3085                    .scales
3086                    .get(a)
3087                    .map(|s| s.is_discrete())
3088                    .unwrap_or(false);
3089                is_discrete || !crate::guide::legend::is_colorbar_aesthetic(a)
3090            });
3091            if has_wrap_guide {
3092                let layout0 = PlotLayout::compute_with_extras(
3093                    w as f64,
3094                    h as f64,
3095                    &built.theme,
3096                    has_title,
3097                    has_subtitle,
3098                    has_caption,
3099                    has_legend,
3100                    x_axis_top,
3101                    y_label_width,
3102                    x_label_height,
3103                    extras,
3104                );
3105                // `y` is unused here (only `legend_x0`/`is_horizontal` feed
3106                // the avail-width check below), so #233's `Top` row-count
3107                // parameter can't matter — `extras.legend_extra_rows` isn't
3108                // even known yet at this point in the pass. Likewise #225's
3109                // `Inside` justification only matters when `legend_x0` is
3110                // actually used for an `Inside` position combined with an
3111                // explicit `nrow`/`ncol` grid (`Inside` otherwise never
3112                // reaches this discrete-guide-wrap check), too rare to
3113                // bother estimating a real size hint for here.
3114                let (legend_x0, _, mut is_horizontal) = crate::guide::legend::legend_position(
3115                    &built.theme,
3116                    &layout0.plot_area,
3117                    extras.legend_extra_rows,
3118                    (0.0, 0.0),
3119                    &layout0.total,
3120                );
3121                if let Some(dir) = built.theme.legend_direction {
3122                    is_horizontal = matches!(dir, crate::theme::LegendDirection::Horizontal);
3123                }
3124                let avail_width =
3125                    (layout0.plot_area.x + layout0.plot_area.width - legend_x0).max(0.0);
3126                let mut legend_warnings = Vec::new();
3127                let mut plans = crate::guide::legend::plan_all_legends(
3128                    &built.scales,
3129                    &built.guide_legend,
3130                    &built.theme,
3131                    &built.suppressed_aes,
3132                    avail_width,
3133                    layout0.plot_area.height,
3134                    is_horizontal,
3135                    &mut legend_warnings,
3136                );
3137                built.warnings.extend(legend_warnings);
3138
3139                if !plans.is_empty() {
3140                    // Guides laid out side by side (a horizontal legend
3141                    // position) share one row band — its height is set
3142                    // by whichever guide wrapped to the most rows.
3143                    // Guides stacked vertically each add their own full
3144                    // height, so their extra rows sum.
3145                    extras.legend_extra_rows = if is_horizontal {
3146                        plans
3147                            .values()
3148                            .map(|p| p.rows.saturating_sub(1))
3149                            .max()
3150                            .unwrap_or(0)
3151                    } else {
3152                        plans.values().map(|p| p.rows.saturating_sub(1)).sum()
3153                    };
3154                    // Review #158 finding 3: a vertical explicit grid
3155                    // with ncol > 1 needs extra legend band width for
3156                    // its later columns, or they run off the canvas
3157                    // (cols is always 1, col_pitch 0, for the horizontal
3158                    // auto-wrap path, so this is a no-op there). Several
3159                    // guides take the widest requirement among them.
3160                    extras.legend_extra_width = plans
3161                        .values()
3162                        .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
3163                        .fold(0.0_f64, f64::max);
3164
3165                    // #159: a vertical multi-column grid that still runs
3166                    // off the canvas even after reserving the extra width
3167                    // above now (1) tries reducing its column count
3168                    // toward 1 — the first count that fits wins; (2) if
3169                    // even one column still overflows, truncates labels
3170                    // with an ellipsis (keeping the full label available
3171                    // via a `<title>`); and only (3) warns if it still
3172                    // doesn't fit after both. A grid that already fits is
3173                    // untouched — no reduction, no truncation, no warning
3174                    // (review #158's second re-review, LOW, is the
3175                    // original "warn only" version of this check).
3176                    if !is_horizontal {
3177                        let final_layout = PlotLayout::compute_with_extras(
3178                            w as f64,
3179                            h as f64,
3180                            &built.theme,
3181                            has_title,
3182                            has_subtitle,
3183                            has_caption,
3184                            has_legend,
3185                            x_axis_top,
3186                            y_label_width,
3187                            x_label_height,
3188                            extras,
3189                        );
3190                        // `y` is unused here too, but `extras` is final by
3191                        // this point, so pass its real `legend_extra_rows`
3192                        // for consistency with #233's `Top` formula. #225's
3193                        // `Inside` size hint is skipped here for the same
3194                        // reason as the pass above.
3195                        let (legend_x_final, _, _) = crate::guide::legend::legend_position(
3196                            &built.theme,
3197                            &final_layout.plot_area,
3198                            extras.legend_extra_rows,
3199                            (0.0, 0.0),
3200                            &final_layout.total,
3201                        );
3202                        let swatch_and_gap =
3203                            built.theme.legend_key_width + built.theme.legend_spacing;
3204                        let text_size = built.theme.legend_text.size;
3205                        // A plain fn, not a closure: #168's retightening
3206                        // pass below re-runs this same check at a second
3207                        // `legend_x` (the narrower reservation's), so
3208                        // `legend_x` has to be a parameter rather than
3209                        // captured.
3210                        fn right_edge_of(
3211                            legend_x: f64,
3212                            swatch_and_gap: f64,
3213                            text_size: f64,
3214                            plan: &crate::guide::legend::LegendPlan,
3215                            breaks: &[(f64, String)],
3216                        ) -> f64 {
3217                            plan.entries
3218                                .iter()
3219                                .filter_map(|e| breaks.get(e.break_idx).map(|(_, l)| (e, l)))
3220                                .map(|(e, label)| {
3221                                    let text =
3222                                        e.label_override.as_deref().unwrap_or(label.as_str());
3223                                    legend_x
3224                                        + e.x_offset
3225                                        + swatch_and_gap
3226                                        + crate::render::text::text_width(text, text_size)
3227                                })
3228                                .fold(0.0_f64, f64::max)
3229                        }
3230
3231                        let mut updates: Vec<(
3232                            crate::aes::Aesthetic,
3233                            crate::guide::legend::LegendPlan,
3234                        )> = Vec::new();
3235                        // #168: guides narrowed below by *column
3236                        // reduction* (not label truncation) are
3237                        // candidates for the retightening pass after this
3238                        // loop — a truncated guide already picked the
3239                        // narrowest column count, so there's no reserved
3240                        // width left to give back.
3241                        let mut reduced_aes: Vec<crate::aes::Aesthetic> = Vec::new();
3242                        for (aes, plan) in &plans {
3243                            if plan.cols <= 1 {
3244                                continue;
3245                            }
3246                            let Some(scale) = built.scales.get(aes) else {
3247                                continue;
3248                            };
3249                            let breaks = scale.breaks();
3250                            if right_edge_of(
3251                                legend_x_final,
3252                                swatch_and_gap,
3253                                text_size,
3254                                plan,
3255                                &breaks,
3256                            ) <= w as f64
3257                            {
3258                                continue; // already fits — untouched.
3259                            }
3260
3261                            // Step 1: reduce columns toward 1; the first
3262                            // count that fits wins.
3263                            let n = breaks.len();
3264                            let mut reduced: Vec<crate::guide::legend::LegendPlan> = Vec::new();
3265                            for c in (1..plan.cols).rev() {
3266                                let mut candidate_guide = built.guide_legend.clone();
3267                                candidate_guide.ncol = Some(c);
3268                                candidate_guide.nrow = None;
3269                                let mut tmp_warnings = Vec::new();
3270                                let candidate_guide =
3271                                    candidate_guide.validated(n, &mut tmp_warnings);
3272                                if let Some(cand) = crate::guide::legend::plan_legend(
3273                                    &breaks,
3274                                    &candidate_guide,
3275                                    &built.theme,
3276                                    avail_width,
3277                                    layout0.plot_area.height,
3278                                    false,
3279                                ) {
3280                                    reduced.push(cand);
3281                                }
3282                            }
3283                            if let Some(fits) = reduced.iter().find(|c| {
3284                                right_edge_of(legend_x_final, swatch_and_gap, text_size, c, &breaks)
3285                                    <= w as f64
3286                            }) {
3287                                extras.legend_extra_rows =
3288                                    extras.legend_extra_rows.max(fits.rows.saturating_sub(1));
3289                                updates.push((aes.clone(), fits.clone()));
3290                                reduced_aes.push(aes.clone());
3291                                continue;
3292                            }
3293
3294                            // Step 2: no column count fit — truncate
3295                            // labels (starting from the narrowest, 1-
3296                            // column, candidate) with an ellipsis, each
3297                            // to whatever room its own position leaves.
3298                            let base = reduced.last().cloned().unwrap_or_else(|| plan.clone());
3299                            extras.legend_extra_rows =
3300                                extras.legend_extra_rows.max(base.rows.saturating_sub(1));
3301                            let mut truncated = base.clone();
3302                            for e in &mut truncated.entries {
3303                                let Some((_, label)) = breaks.get(e.break_idx) else {
3304                                    continue;
3305                                };
3306                                let avail = (w as f64
3307                                    - (legend_x_final + e.x_offset + swatch_and_gap))
3308                                    .max(0.0);
3309                                if let Some(short) =
3310                                    crate::render::text::truncate_to_width(label, avail, text_size)
3311                                {
3312                                    e.label_override = Some(short);
3313                                }
3314                            }
3315
3316                            // Step 3: only warn if it still doesn't fit
3317                            // after both the reduction and the
3318                            // truncation above.
3319                            let truncated_edge = right_edge_of(
3320                                legend_x_final,
3321                                swatch_and_gap,
3322                                text_size,
3323                                &truncated,
3324                                &breaks,
3325                            );
3326                            if truncated_edge > w as f64 {
3327                                built.warnings.push(format!(
3328                                    "legend: the {}-column grid still doesn't fit the {w}px chart (needs about {} px)",
3329                                    truncated.cols,
3330                                    truncated_edge.ceil() as i64
3331                                ));
3332                            }
3333                            updates.push((aes.clone(), truncated));
3334                        }
3335                        for (aes, new_plan) in &updates {
3336                            plans.insert(aes.clone(), new_plan.clone());
3337                        }
3338
3339                        // #168: `extras.legend_extra_width` above still
3340                        // reserves the *original*, pre-reduction column
3341                        // count's width — that stale, wider reservation
3342                        // is an accident of ordering (reserve → layout →
3343                        // fit? → reduce), not a requirement, so the panel
3344                        // stays narrower than it needs to be once a guide
3345                        // above got fewer columns.
3346                        //
3347                        // Tighten it to the reduced guides' new column
3348                        // counts and re-check fit once more at the
3349                        // narrower reservation (a bounded retry, not an
3350                        // unbounded fixed point: a tighter reservation
3351                        // moves `legend_x_final` right — less headroom
3352                        // before the canvas edge — which could in
3353                        // principle call for yet another round of
3354                        // reduction; rather than chase reserve → layout →
3355                        // fit → reduce → reserve → … indefinitely, this
3356                        // keeps the tighter reservation only if every
3357                        // guide still fits under it, and falls back to
3358                        // the wider, already-proven-safe reservation
3359                        // otherwise — so retightening can only ever
3360                        // help, never regress a plot that fit before
3361                        // this pass existed).
3362                        //
3363                        // Review #167 finding 1 on #171 (HIGH, fixed):
3364                        // the retry must re-check *every* plan in
3365                        // `plans`, not just `reduced_aes`. `legend_x`
3366                        // moves for every guide sharing the row, not
3367                        // only the one(s) that got reduced — a second
3368                        // guide that already fit at the old, wider
3369                        // `legend_x_final` (its own width is a fixed
3370                        // `6·text_size` estimate, unrelated to the
3371                        // reduced guide's labels) or whose labels were
3372                        // truncated against that old `legend_x_final`
3373                        // shifts right by the same amount and was never
3374                        // re-checked, so it could run off the canvas
3375                        // with no warning (the warnings were computed
3376                        // against the old x too). `reduced_aes` is kept
3377                        // only to gate *entering* this block at all —
3378                        // nothing to reclaim if nothing was reduced.
3379                        if !reduced_aes.is_empty() {
3380                            let original_reserve = extras.legend_extra_width;
3381                            let tighter_reserve = plans
3382                                .values()
3383                                .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
3384                                .fold(0.0_f64, f64::max);
3385                            if tighter_reserve < original_reserve {
3386                                let mut retry_extras = extras;
3387                                retry_extras.legend_extra_width = tighter_reserve;
3388                                let retry_layout = PlotLayout::compute_with_extras(
3389                                    w as f64,
3390                                    h as f64,
3391                                    &built.theme,
3392                                    has_title,
3393                                    has_subtitle,
3394                                    has_caption,
3395                                    has_legend,
3396                                    x_axis_top,
3397                                    y_label_width,
3398                                    x_label_height,
3399                                    retry_extras,
3400                                );
3401                                // `y` is unused here too; `retry_extras`
3402                                // only tightened `legend_extra_width`, so
3403                                // its `legend_extra_rows` is still the same
3404                                // real value. #225's `Inside` size hint is
3405                                // skipped for the same reason as above.
3406                                let (retry_x, _, _) = crate::guide::legend::legend_position(
3407                                    &built.theme,
3408                                    &retry_layout.plot_area,
3409                                    retry_extras.legend_extra_rows,
3410                                    (0.0, 0.0),
3411                                    &retry_layout.total,
3412                                );
3413                                let all_still_fit = plans.iter().all(|(aes, plan)| {
3414                                    let Some(scale) = built.scales.get(aes) else {
3415                                        return true;
3416                                    };
3417                                    let breaks = scale.breaks();
3418                                    right_edge_of(retry_x, swatch_and_gap, text_size, plan, &breaks)
3419                                        <= w as f64
3420                                });
3421                                if all_still_fit {
3422                                    extras.legend_extra_width = tighter_reserve;
3423                                }
3424                            }
3425                        }
3426                    }
3427                    for (aes, plan) in &plans {
3428                        if let Some(ov) = &plan.overflow {
3429                            let n = built
3430                                .scales
3431                                .get(aes)
3432                                .map(|s| s.breaks().len())
3433                                .unwrap_or(ov.dropped);
3434                            let shown = n.saturating_sub(ov.dropped);
3435                            built.warnings.push(format!(
3436                                "legend: {} of {n} entries don't fit the chart; the legend shows {shown} and \"+{} more\"",
3437                                ov.dropped, ov.dropped
3438                            ));
3439                        }
3440                    }
3441                }
3442                // Review #158 finding 2: store these exact plans so
3443                // `draw_legend_planned` draws them verbatim instead of
3444                // recomputing against the (shorter) post-reservation
3445                // panel height, which could warn "+7 more" while
3446                // drawing "+15 more".
3447                built.legend_plans = plans;
3448            }
3449        }
3450
3451        // #211: a continuous colourbar at `Top`/`Bottom` (or
3452        // `legend_direction(Horizontal)`) draws wide × short instead of
3453        // its usual tall × narrow bar (see `draw_continuous_legend_at`),
3454        // with its tick labels below rather than beside it — reserve the
3455        // extra band height that needs beyond the flat discrete-row
3456        // height `legend_band` already assumes. Independent of the
3457        // `has_wrap_guide` block above (a plot can have a continuous
3458        // colourbar with no other guide at all), so computed
3459        // unconditionally here, right before the layout that actually
3460        // matters reads `extras`.
3461        if has_legend
3462            && !matches!(
3463                built.theme.legend_position,
3464                crate::theme::LegendPosition::None
3465            )
3466        {
3467            let is_horizontal = match built.theme.legend_direction {
3468                Some(dir) => matches!(dir, crate::theme::LegendDirection::Horizontal),
3469                None => matches!(
3470                    built.theme.legend_position,
3471                    crate::theme::LegendPosition::Top | crate::theme::LegendPosition::Bottom
3472                ),
3473            };
3474            if is_horizontal {
3475                let legend_aes =
3476                    crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
3477                let continuous_colourbar = legend_aes.iter().find_map(|aes| {
3478                    if !matches!(
3479                        aes,
3480                        crate::aes::Aesthetic::Color | crate::aes::Aesthetic::Fill
3481                    ) {
3482                        return None;
3483                    }
3484                    let scale = built.scales.get(aes)?;
3485                    if scale.is_discrete() {
3486                        return None;
3487                    }
3488                    Some(scale)
3489                });
3490                if let Some(scale) = continuous_colourbar {
3491                    let title = built
3492                        .guide_legend
3493                        .title
3494                        .as_deref()
3495                        .unwrap_or_else(|| scale.name());
3496                    let bar_height = crate::guide::legend::continuous_horizontal_bar_height(
3497                        &built.theme,
3498                        !title.is_empty(),
3499                    );
3500                    let key_h = built
3501                        .theme
3502                        .legend_key_height
3503                        .max(extras.legend_max_key_size);
3504                    extras.continuous_horizontal_legend_extra_height =
3505                        (bar_height - key_h).max(0.0);
3506                }
3507            }
3508        }
3509
3510        PlotLayout::compute_with_extras(
3511            w as f64,
3512            h as f64,
3513            &built.theme,
3514            has_title,
3515            has_subtitle,
3516            has_caption,
3517            has_legend,
3518            x_axis_top,
3519            y_label_width,
3520            x_label_height,
3521            extras,
3522        )
3523    }
3524
3525    /// Fill the background, render the built plot, and flush — for any plotters
3526    /// backend. (Native only.)
3527    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
3528    fn render_into<DB>(
3529        area: plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
3530        built: &crate::build::BuiltPlot,
3531        layout: &PlotLayout,
3532    ) -> Result<(), GGError>
3533    where
3534        DB: plotters::prelude::DrawingBackend,
3535        DB::ErrorType: 'static,
3536    {
3537        area.fill(&plotters::prelude::WHITE)
3538            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
3539        let mut adapter = PlottersAdapter::new(&area, layout.plot_area.clone());
3540        PlotRenderer::render(built, &mut adapter).map_err(GGError::Render)?;
3541        area.present()
3542            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
3543        Ok(())
3544    }
3545
3546    /// Save with physical dimensions (inches) and DPI. (Feature `plotters`;
3547    /// native only.)
3548    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
3549    pub fn ggsave(
3550        self,
3551        path: &str,
3552        width_inches: f64,
3553        height_inches: f64,
3554        dpi: f64,
3555    ) -> Result<(), GGError> {
3556        let w = (width_inches * dpi) as u32;
3557        let h = (height_inches * dpi) as u32;
3558        self.save_with_size(path, w, h)
3559    }
3560
3561    /// Does this plot have a legend to make room for? (#201) A plot-level
3562    /// `.aes(...)` mapping always counts; so does a *layer's own*
3563    /// `.layer_aes(...)` mapping — e.g. `geom_hex`'s usual pattern of
3564    /// mapping `fill` to a raw column only on that one layer, via
3565    /// `StatIdentity` after pre-binning, rather than on the plot as a
3566    /// whole. Checking only `self.mapping` (as before) missed that case
3567    /// entirely: the legend still drew (the render path always draws
3568    /// whatever guides the trained scales produce, regardless of this
3569    /// flag), just with no panel margin ever reserved for it, so it ran
3570    /// straight off the canvas edge. A layer that opts out with
3571    /// `show_legend(false)` doesn't count towards its own mapping, mirroring
3572    /// `PlotBuilder::compute_suppressed_aes`'s later, more precise
3573    /// (post-build, cross-layer) suppression check — this one only needs to
3574    /// decide *whether to reserve space at all*, not exactly how much.
3575    fn has_legend_mapping(&self) -> bool {
3576        // #241: delegates to `guide::legend::is_legend_aesthetic` (the
3577        // same list `draw_legend_planned` itself draws from) rather than
3578        // keeping its own copy — a second, independently-maintained list
3579        // here had drifted out of sync, missing `Linewidth`.
3580        use crate::guide::legend::is_legend_aesthetic;
3581        let plot_level = self
3582            .mapping
3583            .mappings
3584            .iter()
3585            .any(|m| is_legend_aesthetic(&m.aesthetic));
3586        plot_level
3587            || self.layers.iter().any(|layer| {
3588                if layer.show_legend == Some(false) {
3589                    return false;
3590                }
3591                let effective = if layer.geom.inherit_aes() {
3592                    self.mapping.merge(&layer.mapping)
3593                } else {
3594                    layer.mapping.clone()
3595                };
3596                effective
3597                    .mappings
3598                    .iter()
3599                    .any(|m| is_legend_aesthetic(&m.aesthetic))
3600            })
3601    }
3602}
3603
3604/// Size-independent facts about a built plot that its layout needs.
3605#[derive(Clone, Copy, Debug)]
3606pub(crate) struct RenderMeta {
3607    pub(crate) has_title: bool,
3608    pub(crate) has_subtitle: bool,
3609    pub(crate) has_caption: bool,
3610    pub(crate) has_legend: bool,
3611    pub(crate) legend_bottom_share: Option<f64>,
3612}
3613
3614/// Top-level error type.
3615#[derive(Debug)]
3616#[non_exhaustive]
3617pub enum GGError {
3618    Render(RenderError),
3619    UnsupportedFormat(String),
3620    Io(std::io::Error),
3621    ValidationError(String),
3622}
3623
3624impl std::fmt::Display for GGError {
3625    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3626        match self {
3627            GGError::Render(e) => write!(f, "Render error: {e}"),
3628            GGError::UnsupportedFormat(ext) => write!(f, "Unsupported output format: {ext}"),
3629            GGError::Io(e) => write!(f, "IO error: {e}"),
3630            GGError::ValidationError(msg) => write!(f, "Validation error: {msg}"),
3631        }
3632    }
3633}
3634
3635impl std::error::Error for GGError {}