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    /// Panel aspect ratio used when the theme sets none (helpers such as
112    /// `geom_calendar` need square cells; survives theme presets).
113    pub(crate) default_aspect_ratio: Option<f64>,
114    /// Plot-wide default locale for axis / legend labels ([`GGPlot::locale`]).
115    pub(crate) locale: Option<crate::locale::Locale>,
116    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/…
117    /// ([`svg_root_data`](Self::svg_root_data)). Default `true`; a consumer
118    /// overlaying a fragment on its own basemap (`render_svg_native_at`)
119    /// turns it off so the fragment adds no root attributes of its own.
120    pub(crate) svg_root_data: bool,
121    /// Extra root `<svg>` attributes requested via [`svg_attr`](Self::svg_attr)/
122    /// [`svg_attrs`](Self::svg_attrs), validated and applied at render time.
123    pub(crate) root_attrs: Vec<(String, String)>,
124    /// Whether to emit a `data-warnings` JSON array of the build warnings
125    /// on the root `<svg>` ([`svg_warnings_attr`](Self::svg_warnings_attr)).
126    /// Default off; byte-identical output when off.
127    pub(crate) svg_warnings_attr: bool,
128    /// Whether to emit `data-fvalue`/`data-fx` on marks
129    /// ([`svg_formatted_values`](Self::svg_formatted_values)). Default off;
130    /// byte-identical output when off.
131    pub(crate) svg_formatted_values: bool,
132}
133
134impl GGPlot {
135    /// Create a new plot with the given data source.
136    ///
137    /// Never panics on malformed input: e.g. column-oriented data whose columns
138    /// have different lengths is padded with `NA` and reported as a
139    /// [`GGError::ValidationError`] by [`try_build`](Self::try_build) and the
140    /// `render_*`/`save*` methods.
141    pub fn new(data: impl GGData) -> Self {
142        GGPlot {
143            data: data.into_dataframe(),
144            mapping: Aes::default(),
145            layers: Vec::new(),
146            scales: Vec::new(),
147            coord: Box::new(CoordCartesian::new()),
148            theme: Theme::default(),
149            labels: Labels::default(),
150            facet: Facet::default(),
151            annotations: Vec::new(),
152            guide_legend: crate::guide::config::GuideLegend::default(),
153            warnings: Vec::new(),
154            default_aspect_ratio: None,
155            locale: None,
156            svg_root_data: true,
157            root_attrs: Vec::new(),
158            svg_warnings_attr: false,
159            svg_formatted_values: false,
160        }
161    }
162
163    /// Set the plot-level aesthetic mapping.
164    pub fn aes(mut self, mapping: Aes) -> Self {
165        self.warnings.extend(mapping.warnings.iter().cloned());
166        self.mapping = mapping;
167        self
168    }
169
170    // ─── Geom shortcuts ──────────────────────────────────────────
171
172    pub fn geom_point(self) -> Self {
173        self.add_geom(GeomPoint::default())
174    }
175
176    pub fn geom_point_with(self, geom: GeomPoint) -> Self {
177        self.add_geom_with(geom)
178    }
179
180    pub fn geom_line(self) -> Self {
181        self.add_geom(GeomLine::default())
182    }
183
184    pub fn geom_line_with(self, geom: GeomLine) -> Self {
185        self.add_geom_with(geom)
186    }
187
188    pub fn geom_bar(self) -> Self {
189        self.add_geom(GeomBar::default())
190    }
191
192    pub fn geom_bar_with(self, geom: GeomBar) -> Self {
193        self.add_geom_with(geom)
194    }
195
196    pub fn geom_histogram(self) -> Self {
197        self.add_geom(GeomHistogram::default())
198    }
199
200    pub fn geom_histogram_with(self, geom: GeomHistogram) -> Self {
201        self.add_geom_with(geom)
202    }
203
204    pub fn geom_boxplot(self) -> Self {
205        self.add_geom(GeomBoxplot::default())
206    }
207
208    pub fn geom_boxplot_with(self, geom: GeomBoxplot) -> Self {
209        self.add_geom_with(geom)
210    }
211
212    pub fn geom_smooth(self) -> Self {
213        self.add_geom(GeomSmooth::default())
214    }
215
216    pub fn geom_smooth_with(self, geom: GeomSmooth) -> Self {
217        self.add_geom_with(geom)
218    }
219
220    pub fn geom_col(self) -> Self {
221        self.add_geom(GeomCol::default())
222    }
223
224    pub fn geom_col_with(self, geom: GeomCol) -> Self {
225        self.add_geom_with(geom)
226    }
227
228    /// Horizontal reference line at a constant `yintercept`. Like ggplot2 the
229    /// intercept trains the y scale (the line is always visible) and the line
230    /// appears in every facet panel.
231    pub fn geom_hline(self, yintercept: f64) -> Self {
232        self.add_refline(
233            GeomHline::new(yintercept),
234            false,
235            &[("yintercept", yintercept)],
236        )
237    }
238
239    /// Add a horizontal reference line with custom styling (color/linetype/width).
240    pub fn geom_hline_with(self, geom: GeomHline) -> Self {
241        let y = geom.yintercept;
242        self.add_refline(geom, true, &[("yintercept", y)])
243    }
244
245    /// Data-mapped horizontal lines (ggplot2's `geom_hline(aes(yintercept =
246    /// …))`): one line per row of the layer data (the plot data unless
247    /// [`layer_data`](Self::layer_data) follows), per facet panel, styled by
248    /// any `color`/`linetype`/`alpha` in `mapping`. The plot-level mapping is
249    /// not inherited.
250    ///
251    /// ```
252    /// # use ggplot_rs::prelude::*;
253    /// let thresholds: Vec<(String, Vec<Value>)> = vec![
254    ///     ("bound".into(), vec![Value::Float(-0.2), Value::Float(0.2)]),
255    /// ];
256    /// let svg = GGPlot::new(vec![
257    ///         ("lag".to_string(), vec![Value::Float(1.0), Value::Float(2.0)]),
258    ///         ("acf".to_string(), vec![Value::Float(0.5), Value::Float(0.1)]),
259    ///     ])
260    ///     .aes(Aes::new().x("lag").y("acf"))
261    ///     .geom_col()
262    ///     .geom_hline_aes(Aes::new().yintercept("bound"))
263    ///     .layer_data(thresholds)
264    ///     .render_svg_native()
265    ///     .unwrap();
266    /// assert!(svg.contains("data-value=\"0.2\""));
267    /// ```
268    pub fn geom_hline_aes(self, mapping: Aes) -> Self {
269        self.add_geom(GeomHline::mapped()).layer_aes(mapping)
270    }
271
272    /// [`geom_hline_aes`](Self::geom_hline_aes) with custom default styling.
273    pub fn geom_hline_aes_with(self, geom: GeomHline, mapping: Aes) -> Self {
274        self.add_geom_with(geom).layer_aes(mapping)
275    }
276
277    /// Vertical reference line at a constant `xintercept` (trains the x
278    /// scale, appears in every panel).
279    pub fn geom_vline(self, xintercept: f64) -> Self {
280        self.add_refline(
281            GeomVline::new(xintercept),
282            false,
283            &[("xintercept", xintercept)],
284        )
285    }
286
287    /// Add a vertical reference line with custom styling (color/linetype/width).
288    pub fn geom_vline_with(self, geom: GeomVline) -> Self {
289        let x = geom.xintercept;
290        self.add_refline(geom, true, &[("xintercept", x)])
291    }
292
293    /// Data-mapped vertical lines (`aes(xintercept = …)`), one per row; see
294    /// [`geom_hline_aes`](Self::geom_hline_aes).
295    pub fn geom_vline_aes(self, mapping: Aes) -> Self {
296        self.add_geom(GeomVline::mapped()).layer_aes(mapping)
297    }
298
299    /// [`geom_vline_aes`](Self::geom_vline_aes) with custom default styling.
300    pub fn geom_vline_aes_with(self, geom: GeomVline, mapping: Aes) -> Self {
301        self.add_geom_with(geom).layer_aes(mapping)
302    }
303
304    /// Line `y = intercept + slope · x` in data space, clipped to the panel.
305    /// It does not train any scale (as in ggplot2).
306    pub fn geom_abline(self, slope: f64, intercept: f64) -> Self {
307        self.add_refline(
308            GeomAbline::new(slope, intercept),
309            false,
310            &[("slope", slope), ("intercept", intercept)],
311        )
312    }
313
314    /// Add a slope/intercept reference line with custom styling.
315    pub fn geom_abline_with(self, geom: GeomAbline) -> Self {
316        let (b, a) = (geom.slope, geom.intercept);
317        self.add_refline(geom, true, &[("slope", b), ("intercept", a)])
318    }
319
320    /// Data-mapped ablines (`aes(slope = …, intercept = …)`), one per row; a
321    /// missing aesthetic defaults to slope 1 / intercept 0.
322    pub fn geom_abline_aes(self, mapping: Aes) -> Self {
323        self.add_geom(GeomAbline::mapped()).layer_aes(mapping)
324    }
325
326    /// [`geom_abline_aes`](Self::geom_abline_aes) with custom default styling.
327    pub fn geom_abline_aes_with(self, geom: GeomAbline, mapping: Aes) -> Self {
328        self.add_geom_with(geom).layer_aes(mapping)
329    }
330
331    /// A constant reference line as ggplot2 builds it: a one-row layer frame
332    /// holding the constants, mapped to their aesthetics.
333    fn add_refline(
334        self,
335        geom: impl Geom + 'static,
336        explicit: bool,
337        values: &[(&str, f64)],
338    ) -> Self {
339        let mut data = DataFrame::new();
340        let mut mapping = Aes::new();
341        for (col, v) in values {
342            data.add_column(col.to_string(), vec![Value::Float(*v)]);
343            mapping = match *col {
344                "xintercept" => mapping.xintercept(col),
345                "yintercept" => mapping.yintercept(col),
346                "slope" => mapping.slope(col),
347                _ => mapping.intercept(col),
348            };
349        }
350        let plot = if explicit {
351            self.add_geom_with(geom)
352        } else {
353            self.add_geom(geom)
354        };
355        plot.layer_aes(mapping).layer_data(data)
356    }
357
358    pub fn geom_text(self) -> Self {
359        self.add_geom(GeomText::default())
360    }
361
362    pub fn geom_text_with(self, geom: GeomText) -> Self {
363        self.add_geom_with(geom)
364    }
365
366    /// Annotate with a correlation coefficient + p-value (`ggpubr::stat_cor()`).
367    /// Adds a text layer whose statistic computes Pearson correlation via
368    /// anofox-statistics; use [`GGPlot::stat_cor_with`] to pick Spearman or set
369    /// the label position.
370    #[cfg(feature = "ggpubr")]
371    pub fn stat_cor(self) -> Self {
372        self.geom_text().stat(crate::stat::cor::StatCor::default())
373    }
374
375    /// [`GGPlot::stat_cor`] with an explicit [`StatCor`](crate::stat::cor::StatCor)
376    /// (method / label position).
377    #[cfg(feature = "ggpubr")]
378    pub fn stat_cor_with(self, stat: crate::stat::cor::StatCor) -> Self {
379        self.geom_text().stat(stat)
380    }
381
382    /// Annotate grouped data with a group-comparison p-value
383    /// (`ggpubr::stat_compare_means()`). Adds a text layer whose statistic
384    /// compares y across the discrete x groups (Wilcoxon for two groups,
385    /// Kruskal-Wallis for more) via anofox-statistics.
386    #[cfg(feature = "ggpubr")]
387    pub fn stat_compare_means(self) -> Self {
388        self.geom_text()
389            .stat(crate::stat::compare_means::StatCompareMeans::default())
390    }
391
392    /// [`GGPlot::stat_compare_means`] with an explicit
393    /// [`StatCompareMeans`](crate::stat::compare_means::StatCompareMeans).
394    #[cfg(feature = "ggpubr")]
395    pub fn stat_compare_means_with(
396        self,
397        stat: crate::stat::compare_means::StatCompareMeans,
398    ) -> Self {
399        self.geom_text().stat(stat)
400    }
401
402    /// Auto-draw pairwise significance brackets (`ggpubr::stat_compare_means`
403    /// with `comparisons`). For each `(group_a, group_b)` pair it runs a
404    /// two-sample test (Wilcoxon by default) on the plot's y-values, formats the
405    /// p-value, and stacks a labelled [`geom_bracket`](GGPlot::geom_bracket)
406    /// above the data. Uses the plot's x/y mapping and data.
407    #[cfg(feature = "ggpubr")]
408    pub fn stat_compare_means_pairwise(self, comparisons: &[(&str, &str)]) -> Self {
409        self.stat_compare_means_pairwise_with(
410            crate::stat::compare_means::CompareMethod::Auto,
411            comparisons,
412        )
413    }
414
415    /// [`stat_compare_means_pairwise`](GGPlot::stat_compare_means_pairwise) with
416    /// an explicit test method.
417    #[cfg(feature = "ggpubr")]
418    pub fn stat_compare_means_pairwise_with(
419        self,
420        method: crate::stat::compare_means::CompareMethod,
421        comparisons: &[(&str, &str)],
422    ) -> Self {
423        // Resolve the x/y source columns from the plot mapping + data.
424        let col_for = |a: crate::aes::Aesthetic| {
425            self.mapping
426                .mappings
427                .iter()
428                .find(|m| m.aesthetic == a)
429                .map(|m| m.column.clone())
430        };
431        let (xcol, ycol) = match (
432            col_for(crate::aes::Aesthetic::X),
433            col_for(crate::aes::Aesthetic::Y),
434        ) {
435            (Some(x), Some(y)) => (x, y),
436            _ => return self,
437        };
438        let (xc, yc) = match (self.data.column(&xcol), self.data.column(&ycol)) {
439            (Some(x), Some(y)) => (x, y),
440            _ => return self,
441        };
442
443        // Bucket y by x category (first-seen order) and find the data range.
444        let mut groups: Vec<(String, Vec<f64>)> = Vec::new();
445        let mut ymax = f64::NEG_INFINITY;
446        let mut ymin = f64::INFINITY;
447        for (xv, yv) in xc.iter().zip(yc.iter()) {
448            let y = match yv.as_f64() {
449                Some(y) if y.is_finite() => y,
450                _ => continue,
451            };
452            ymax = ymax.max(y);
453            ymin = ymin.min(y);
454            let key = xv.to_group_key();
455            if let Some(g) = groups.iter_mut().find(|(k, _)| *k == key) {
456                g.1.push(y);
457            } else {
458                groups.push((key, vec![y]));
459            }
460        }
461        if groups.len() < 2 {
462            return self;
463        }
464        let step = if ymax > ymin {
465            (ymax - ymin) * 0.12
466        } else {
467            1.0
468        };
469
470        // One stacked bracket per resolvable comparison.
471        let (mut xmin_v, mut xmax_v, mut y_v, mut label_v) =
472            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
473        let mut placed = 0usize;
474        for (a, b) in comparisons {
475            let ga = groups.iter().find(|(k, _)| k == a).map(|g| &g.1);
476            let gb = groups.iter().find(|(k, _)| k == b).map(|g| &g.1);
477            let (ga, gb) = match (ga, gb) {
478                (Some(x), Some(y)) if x.len() >= 2 && y.len() >= 2 => (x, y),
479                _ => continue,
480            };
481            let p = match crate::stat::compare_means::pairwise_p(method, ga, gb) {
482                Some(p) => p,
483                None => continue,
484            };
485            xmin_v.push(Value::Str((*a).to_string()));
486            xmax_v.push(Value::Str((*b).to_string()));
487            y_v.push(Value::Float(ymax + step * (placed as f64 + 1.0)));
488            label_v.push(Value::Str(crate::stat::cor::format_p_value(p)));
489            placed += 1;
490        }
491        if xmin_v.is_empty() {
492            return self;
493        }
494
495        let data = vec![
496            ("xmin".to_string(), xmin_v),
497            ("xmax".to_string(), xmax_v),
498            ("y".to_string(), y_v),
499            ("label".to_string(), label_v),
500        ];
501        self.add_geom(crate::geom::bracket::GeomBracket::default())
502            .layer_data(data)
503            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
504    }
505
506    /// Draw a significance bracket over the plot (`ggpubr::geom_bracket`): a bar
507    /// spanning the categorical positions `xmin`..`xmax` at height `y`, captioned
508    /// with `label` (e.g. a p-value or significance stars). Pairs with a boxplot
509    /// and [`stat_compare_means`](GGPlot::stat_compare_means).
510    pub fn geom_bracket(self, xmin: &str, xmax: &str, y: f64, label: &str) -> Self {
511        self.geom_bracket_many(
512            crate::geom::bracket::GeomBracket::default(),
513            &[(xmin, xmax, y, label)],
514        )
515    }
516
517    /// Draw several significance brackets at once with a configured
518    /// [`GeomBracket`](crate::geom::bracket::GeomBracket). Each tuple is
519    /// `(xmin, xmax, y, label)`.
520    pub fn geom_bracket_many(
521        self,
522        geom: crate::geom::bracket::GeomBracket,
523        brackets: &[(&str, &str, f64, &str)],
524    ) -> Self {
525        let xmin = brackets
526            .iter()
527            .map(|b| Value::Str(b.0.to_string()))
528            .collect::<Vec<_>>();
529        let xmax = brackets
530            .iter()
531            .map(|b| Value::Str(b.1.to_string()))
532            .collect::<Vec<_>>();
533        let y = brackets
534            .iter()
535            .map(|b| Value::Float(b.2))
536            .collect::<Vec<_>>();
537        let label = brackets
538            .iter()
539            .map(|b| Value::Str(b.3.to_string()))
540            .collect::<Vec<_>>();
541        let data = vec![
542            ("xmin".to_string(), xmin),
543            ("xmax".to_string(), xmax),
544            ("y".to_string(), y),
545            ("label".to_string(), label),
546        ];
547        self.add_geom(geom)
548            .layer_data(data)
549            .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
550    }
551
552    /// Significance brackets from a precomputed test table (ggpubr's
553    /// `stat_pvalue_manual` / `geom_bracket(data = …)`) — e.g. the anofox
554    /// `test` contract output (`group1`, `group2`, `p_adj`/`p_value`, optional
555    /// `y_position`, `label`). No test is recomputed. See
556    /// [`BracketTable`](crate::geom::bracket::BracketTable) for the column
557    /// rules, label templates (`"p = {p_adj}"`, `"{p.signif}"`) and the
558    /// automatic stacking of rows without a `y_position`. Rows that cannot be
559    /// drawn are dropped with a build warning.
560    pub fn geom_bracket_table(
561        mut self,
562        table: impl GGData,
563        spec: crate::geom::bracket::BracketTable,
564    ) -> Self {
565        let table = table.into_dataframe();
566        let col_for = |a: crate::aes::Aesthetic| {
567            self.mapping
568                .mappings
569                .iter()
570                .find(|m| m.aesthetic == a)
571                .map(|m| m.column.clone())
572        };
573        // The plot's x categories (to reject unknown groups) and finite y
574        // range (to stack brackets above the data).
575        let x_levels: Vec<String> = col_for(crate::aes::Aesthetic::X)
576            .and_then(|c| self.data.column(&c))
577            .filter(|col| col.iter().any(|v| matches!(v, Value::Str(_))))
578            .map(|col| {
579                let mut seen = std::collections::HashSet::new();
580                col.iter()
581                    .filter(|v| !v.is_na())
582                    .map(|v| v.to_group_key())
583                    .filter(|k| seen.insert(k.clone()))
584                    .collect()
585            })
586            .unwrap_or_default();
587        let y_range = col_for(crate::aes::Aesthetic::Y)
588            .and_then(|c| self.data.column(&c))
589            .and_then(|col| {
590                let (lo, hi) = col
591                    .iter()
592                    .filter_map(|v| v.as_f64())
593                    .filter(|v| v.is_finite())
594                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
595                        (lo.min(v), hi.max(v))
596                    });
597                (lo <= hi).then_some((lo, hi))
598            });
599        let mut warnings = Vec::new();
600        let resolved = spec.resolve(&table, &x_levels, y_range, &mut warnings);
601        self.warnings.extend(warnings);
602        match resolved {
603            Some(data) => self
604                .add_geom(crate::geom::bracket::GeomBracket::from(spec.geom))
605                .layer_data(data)
606                .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label")),
607            None => self,
608        }
609    }
610
611    /// Text labels that repel each other and their points
612    /// (`ggrepel::geom_text_repel`) — deterministic (seeded) layout; see
613    /// [`GeomTextRepel`](crate::geom::repel::GeomTextRepel). Requires `x`,
614    /// `y` and `label`.
615    pub fn geom_text_repel(self) -> Self {
616        self.add_geom(crate::geom::repel::GeomTextRepel::default())
617    }
618
619    /// [`geom_text_repel`](Self::geom_text_repel) with a configured geom
620    /// (padding, nudge, `max_overlaps`, seed, …).
621    pub fn geom_text_repel_with(self, geom: crate::geom::repel::GeomTextRepel) -> Self {
622        self.add_geom_with(geom)
623    }
624
625    /// Boxed labels that repel each other and their points
626    /// (`ggrepel::geom_label_repel`).
627    pub fn geom_label_repel(self) -> Self {
628        self.add_geom(crate::geom::repel::GeomLabelRepel::default())
629    }
630
631    /// [`geom_label_repel`](Self::geom_label_repel) with a configured geom.
632    pub fn geom_label_repel_with(self, geom: crate::geom::repel::GeomLabelRepel) -> Self {
633        self.add_geom_with(geom)
634    }
635
636    pub fn geom_label(self) -> Self {
637        self.add_geom(GeomLabel::default())
638    }
639
640    pub fn geom_label_with(self, geom: GeomLabel) -> Self {
641        self.add_geom_with(geom)
642    }
643
644    pub fn geom_area(self) -> Self {
645        self.add_geom(GeomArea::default())
646    }
647
648    pub fn geom_area_with(self, geom: GeomArea) -> Self {
649        self.add_geom_with(geom)
650    }
651
652    pub fn geom_ribbon(self) -> Self {
653        self.add_geom(GeomRibbon::default())
654    }
655
656    pub fn geom_ribbon_with(self, geom: GeomRibbon) -> Self {
657        self.add_geom_with(geom)
658    }
659
660    pub fn geom_errorbar(self) -> Self {
661        self.add_geom(GeomErrorbar::default())
662    }
663
664    pub fn geom_errorbar_with(self, geom: GeomErrorbar) -> Self {
665        self.add_geom_with(geom)
666    }
667
668    pub fn geom_segment(self) -> Self {
669        self.add_geom(GeomSegment::default())
670    }
671
672    pub fn geom_segment_with(self, geom: GeomSegment) -> Self {
673        self.add_geom_with(geom)
674    }
675
676    pub fn geom_density(self) -> Self {
677        self.add_geom(GeomDensity::default())
678    }
679
680    pub fn geom_density_with(self, geom: GeomDensity) -> Self {
681        self.add_geom_with(geom)
682    }
683
684    pub fn geom_rug(self) -> Self {
685        self.add_geom(GeomRug::default())
686    }
687
688    pub fn geom_rug_with(self, geom: GeomRug) -> Self {
689        self.add_geom_with(geom)
690    }
691
692    pub fn geom_jitter(self) -> Self {
693        self.add_geom(GeomJitter::default())
694    }
695
696    pub fn geom_jitter_with(self, geom: GeomJitter) -> Self {
697        self.add_geom_with(geom)
698    }
699
700    pub fn geom_path(self) -> Self {
701        self.add_geom(GeomPath::default())
702    }
703
704    pub fn geom_path_with(self, geom: GeomPath) -> Self {
705        self.add_geom_with(geom)
706    }
707
708    /// Add a confidence-ellipse layer (default 95%) as a path per group.
709    pub fn stat_ellipse(self) -> Self {
710        self.geom_path()
711            .stat(crate::stat::ellipse::StatEllipse::default())
712    }
713
714    /// Add a confidence-ellipse layer at the given level (0, 1).
715    pub fn stat_ellipse_level(self, level: f64) -> Self {
716        self.geom_path()
717            .stat(crate::stat::ellipse::StatEllipse::new(level))
718    }
719
720    /// Add a quantile-regression line for each `tau` as a separate path layer
721    /// (R's `stat_quantile`). Backed by anofox-regression (feature `regression`).
722    #[cfg(feature = "regression")]
723    pub fn stat_quantile(mut self, taus: &[f64]) -> Self {
724        for &tau in taus {
725            self = self
726                .geom_path()
727                .stat(crate::stat::quantile::StatQuantile::new(tau));
728        }
729        self
730    }
731
732    /// Quantile-regression lines at the quartiles (0.25, 0.5, 0.75).
733    #[cfg(feature = "regression")]
734    pub fn geom_quantile(self) -> Self {
735        self.stat_quantile(&[0.25, 0.5, 0.75])
736    }
737
738    pub fn geom_step(self) -> Self {
739        self.add_geom(GeomStep::default())
740    }
741
742    pub fn geom_step_with(self, geom: GeomStep) -> Self {
743        self.add_geom_with(geom)
744    }
745
746    pub fn geom_freqpoly(self) -> Self {
747        self.add_geom(GeomFreqpoly::default())
748    }
749
750    pub fn geom_freqpoly_with(self, geom: GeomFreqpoly) -> Self {
751        self.add_geom_with(geom)
752    }
753
754    pub fn geom_linerange(self) -> Self {
755        self.add_geom(GeomLinerange::default())
756    }
757
758    pub fn geom_linerange_with(self, geom: GeomLinerange) -> Self {
759        self.add_geom_with(geom)
760    }
761
762    pub fn geom_pointrange(self) -> Self {
763        self.add_geom(GeomPointrange::default())
764    }
765
766    pub fn geom_pointrange_with(self, geom: GeomPointrange) -> Self {
767        self.add_geom_with(geom)
768    }
769
770    pub fn geom_crossbar(self) -> Self {
771        self.add_geom(GeomCrossbar::default())
772    }
773
774    pub fn geom_crossbar_with(self, geom: GeomCrossbar) -> Self {
775        self.add_geom_with(geom)
776    }
777
778    pub fn geom_spoke(self) -> Self {
779        self.add_geom(GeomSpoke::default())
780    }
781
782    pub fn geom_spoke_with(self, geom: GeomSpoke) -> Self {
783        self.add_geom_with(geom)
784    }
785
786    pub fn geom_rect(self) -> Self {
787        self.add_geom(GeomRect::default())
788    }
789
790    pub fn geom_rect_with(self, geom: GeomRect) -> Self {
791        self.add_geom_with(geom)
792    }
793
794    pub fn geom_tile(self) -> Self {
795        self.add_geom(GeomTile::default())
796    }
797
798    pub fn geom_tile_with(self, geom: GeomTile) -> Self {
799        self.add_geom_with(geom)
800    }
801
802    /// Dense regular grid of filled cells (heatmap/raster) from x, y, fill.
803    pub fn geom_raster(self) -> Self {
804        self.add_geom(crate::geom::raster::GeomRaster::default())
805    }
806
807    pub fn geom_raster_with(self, geom: crate::geom::raster::GeomRaster) -> Self {
808        self.add_geom_with(geom)
809    }
810
811    pub fn geom_polygon(self) -> Self {
812        self.add_geom(GeomPolygon::default())
813    }
814
815    pub fn geom_polygon_with(self, geom: GeomPolygon) -> Self {
816        self.add_geom_with(geom)
817    }
818
819    /// Render simple-features geometry from a WKT `geometry` column (feature `sf`).
820    #[cfg(feature = "sf")]
821    pub fn geom_sf(self) -> Self {
822        self.add_geom(crate::geom::sf::GeomSf::default())
823    }
824
825    #[cfg(feature = "sf")]
826    pub fn geom_sf_with(self, geom: crate::geom::sf::GeomSf) -> Self {
827        self.add_geom_with(geom)
828    }
829
830    pub fn geom_curve(self) -> Self {
831        self.add_geom(GeomCurve::default())
832    }
833
834    pub fn geom_curve_with(self, geom: GeomCurve) -> Self {
835        self.add_geom_with(geom)
836    }
837
838    pub fn geom_violin(self) -> Self {
839        self.add_geom(GeomViolin::default())
840    }
841
842    pub fn geom_violin_with(self, geom: GeomViolin) -> Self {
843        self.add_geom_with(geom)
844    }
845
846    pub fn geom_dotplot(self) -> Self {
847        self.add_geom(GeomDotplot::default())
848    }
849
850    pub fn geom_dotplot_with(self, geom: GeomDotplot) -> Self {
851        self.add_geom_with(geom)
852    }
853
854    pub fn geom_qq(self) -> Self {
855        self.add_geom(GeomQQ::default())
856    }
857
858    pub fn geom_qq_with(self, geom: GeomQQ) -> Self {
859        self.add_geom_with(geom)
860    }
861
862    pub fn geom_qq_line(self) -> Self {
863        self.add_geom(GeomQQLine::default())
864    }
865
866    pub fn geom_qq_line_with(self, geom: GeomQQLine) -> Self {
867        self.add_geom_with(geom)
868    }
869
870    pub fn geom_bin2d(self) -> Self {
871        self.add_geom(GeomBin2d::default())
872    }
873
874    pub fn geom_bin2d_with(self, geom: GeomBin2d) -> Self {
875        self.add_geom_with(geom)
876    }
877
878    pub fn geom_hex(self) -> Self {
879        self.add_geom(GeomHex::default())
880    }
881
882    pub fn geom_hex_with(self, geom: GeomHex) -> Self {
883        self.add_geom_with(geom)
884    }
885
886    pub fn geom_count(self) -> Self {
887        self.add_geom(GeomCount::default())
888    }
889
890    pub fn geom_count_with(self, geom: GeomCount) -> Self {
891        self.add_geom_with(geom)
892    }
893
894    pub fn geom_contour(self) -> Self {
895        self.add_geom(GeomContour::default())
896    }
897
898    pub fn geom_contour_with(self, geom: GeomContour) -> Self {
899        self.add_geom_with(geom)
900    }
901
902    /// Filled contour bands from gridded (x, y, z) data — draws polygons filled by
903    /// band level. Pair with a continuous fill scale (e.g. `scale_fill_viridis_c`).
904    pub fn geom_contour_filled(self) -> Self {
905        self.add_geom(GeomPolygon {
906            line_width: 0.0,
907            alpha: 1.0,
908            ..GeomPolygon::default()
909        })
910        .stat(crate::stat::contour_filled::StatContourFilled::default())
911    }
912
913    pub fn geom_density2d(self) -> Self {
914        self.add_geom(GeomDensity2d::default())
915    }
916
917    pub fn geom_density2d_with(self, geom: GeomDensity2d) -> Self {
918        self.add_geom_with(geom)
919    }
920
921    /// Candlestick chart: map `x` and `open`/`high`/`low`/`close`
922    /// (`Aes::new().x("date").open("o").high("h").low("l").close("c")`).
923    pub fn geom_candlestick(self) -> Self {
924        self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
925    }
926
927    pub fn geom_candlestick_with(self, geom: crate::geom::candlestick::GeomCandlestick) -> Self {
928        self.add_geom_with(geom)
929    }
930
931    /// OHLC bar chart (high–low bar with open/close ticks); same aesthetics as
932    /// [`geom_candlestick`](Self::geom_candlestick).
933    pub fn geom_ohlc(self) -> Self {
934        self.add_geom(crate::geom::candlestick::GeomOhlc::default())
935    }
936
937    pub fn geom_ohlc_with(self, geom: crate::geom::candlestick::GeomOhlc) -> Self {
938        self.add_geom_with(geom)
939    }
940
941    /// Calendar heatmap (GitHub/ECharts style): the plot's `x` (a date —
942    /// `DateTime`, epoch seconds or `"YYYY-MM-DD"`) is laid out as week
943    /// columns × weekday rows (Sunday on top) via [`StatCalendar`], coloured
944    /// by `fill`, with month labels along x, Mon/Wed/Fri along y, month
945    /// boundary outlines and square cells. Spans over
946    /// [`MAX_CALENDAR_YEARS`] are clipped to the most recent years (with a
947    /// build warning). Uses the plot-level data and `x` mapping.
948    ///
949    /// [`StatCalendar`]: crate::stat::calendar::StatCalendar
950    /// [`MAX_CALENDAR_YEARS`]: crate::stat::calendar::MAX_CALENDAR_YEARS
951    pub fn geom_calendar(self) -> Self {
952        self.geom_calendar_with(
953            GeomTile {
954                color: (255, 255, 255),
955                line_width: 1.5,
956                ..Default::default()
957            },
958            false,
959        )
960    }
961
962    /// [`geom_calendar`](Self::geom_calendar) with a custom cell style and
963    /// optionally Monday-first weeks.
964    pub fn geom_calendar_with(mut self, tile: GeomTile, monday_first: bool) -> Self {
965        use crate::stat::calendar::{
966            day_number, month_boundaries, month_breaks, month_breaks_localized, weekday_labels,
967            CalendarGrid, StatCalendar, MAX_CALENDAR_YEARS,
968        };
969        let grid = self
970            .mapping
971            .get_mapping(&crate::aes::Aesthetic::X)
972            .and_then(|c| self.data.column(c))
973            .and_then(|col| {
974                CalendarGrid::from_days(col.iter().filter_map(day_number), monday_first)
975            });
976        let Some((grid, clipped)) = grid else {
977            // No dates: an empty calendar layer (renders an empty panel).
978            return self.add_geom_with(tile).stat(StatCalendar {
979                grid: None,
980                monday_first,
981            });
982        };
983        if clipped {
984            self.warnings.push(format!(
985                "geom_calendar: dates more than {MAX_CALENDAR_YEARS} years before the newest were dropped"
986            ));
987        }
988        let (xb, _) = month_breaks(&grid);
989        // Rows: y = 6 - weekday; label Mon/Wed/Fri.
990        let yb = if monday_first {
991            vec![6.0, 4.0, 2.0]
992        } else {
993            vec![5.0, 3.0, 1.0]
994        };
995        let segs = month_boundaries(&grid);
996        let col = |f: fn(&(f64, f64, f64, f64)) -> f64| -> Vec<Value> {
997            segs.iter().map(|s| Value::Float(f(s))).collect()
998        };
999        let boundaries = vec![
1000            ("x".to_string(), col(|s| s.0)),
1001            ("y".to_string(), col(|s| s.1)),
1002            ("xend".to_string(), col(|s| s.2)),
1003            ("yend".to_string(), col(|s| s.3)),
1004        ];
1005        self.default_aspect_ratio = Some(7.0 / grid.n_weeks().max(1) as f64);
1006        let plot = self
1007            .add_geom_with(tile)
1008            .stat(StatCalendar {
1009                grid: Some(grid),
1010                monday_first,
1011            })
1012            .scale_x_continuous(
1013                ScaleContinuous::new()
1014                    .with_breaks(xb)
1015                    // Month / weekday names follow the plot locale.
1016                    .with_localized_labels(move |l| month_breaks_localized(&grid, l).1)
1017                    .with_expand(0.0, 0.0),
1018            )
1019            .scale_y_continuous(
1020                ScaleContinuous::new()
1021                    .with_breaks(yb)
1022                    .with_localized_labels(weekday_labels)
1023                    .with_expand(0.0, 0.0),
1024            );
1025        if segs.is_empty() {
1026            return plot;
1027        }
1028        // Styled by the theme's `calendar_month_border` at draw time.
1029        plot.add_geom_with(crate::geom::segment::GeomCalendarBorder)
1030            .layer_data(boundaries)
1031            .layer_aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
1032            .show_legend(false)
1033    }
1034
1035    pub fn geom_blank(self) -> Self {
1036        self.add_geom(GeomBlank)
1037    }
1038
1039    /// Add a geom configured explicitly by the caller: its colours win over
1040    /// the theme's `primary_color`.
1041    fn add_geom_with(self, geom: impl Geom + 'static) -> Self {
1042        let mut plot = self.add_geom(geom);
1043        if let Some(layer) = plot.layers.last_mut() {
1044            layer.explicit_style = true;
1045        }
1046        plot
1047    }
1048
1049    fn add_geom(mut self, geom: impl Geom + 'static) -> Self {
1050        let stat = geom.default_stat();
1051        let position = geom.default_position();
1052        let params = geom.default_params();
1053        self.layers.push(Layer {
1054            data: None,
1055            mapping: Aes::default(),
1056            geom: Box::new(geom),
1057            stat,
1058            position,
1059            params,
1060            show_legend: None,
1061            explicit_style: false,
1062            tooltip_template: None,
1063        });
1064        self
1065    }
1066
1067    // ─── Layer-level overrides ──────────────────────────────────
1068
1069    /// Override the stat for the most recently added layer.
1070    pub fn stat(mut self, stat: impl Stat + 'static) -> Self {
1071        if let Some(layer) = self.layers.last_mut() {
1072            layer.stat = Box::new(stat);
1073        }
1074        self
1075    }
1076
1077    /// Override the position for the most recently added layer.
1078    pub fn position(mut self, pos: impl Position + 'static) -> Self {
1079        if let Some(layer) = self.layers.last_mut() {
1080            layer.position = Box::new(pos);
1081        }
1082        self
1083    }
1084
1085    /// Override the data for the most recently added layer.
1086    pub fn layer_data(mut self, data: impl GGData) -> Self {
1087        if let Some(layer) = self.layers.last_mut() {
1088            layer.data = Some(data.into_dataframe());
1089        }
1090        self
1091    }
1092
1093    /// Override the aesthetic mapping for the most recently added layer.
1094    pub fn layer_aes(mut self, mapping: Aes) -> Self {
1095        self.warnings.extend(mapping.warnings.iter().cloned());
1096        if let Some(layer) = self.layers.last_mut() {
1097            layer.mapping = mapping;
1098        }
1099        self
1100    }
1101
1102    /// A `{column}` tooltip template for the most recently added layer
1103    /// (B2-5), replacing its default `<title>`. Each placeholder is filled
1104    /// from the *built* layer data (so it can reference a stat-computed
1105    /// column, e.g. a hex's `count`) at that row, formatted through the
1106    /// column's scale when it has one
1107    /// ([`Scale::format_value`](crate::scale::Scale::format_value)) — the same
1108    /// `data-fvalue` logic, but written into the tooltip text. A column
1109    /// that doesn't exist on this layer renders as empty, not literally
1110    /// `{column}`. `{{`/`}}` are literal braces. The result is escaped the
1111    /// same way any other tooltip is — this is plain text, not markup.
1112    pub fn tooltip(mut self, template: &str) -> Self {
1113        if let Some(layer) = self.layers.last_mut() {
1114            layer.tooltip_template = Some(template.to_string());
1115        }
1116        self
1117    }
1118
1119    /// Control whether the most recently added layer contributes to the legend.
1120    /// `true` = always show, `false` = always hide, default (None) = auto.
1121    pub fn show_legend(mut self, show: bool) -> Self {
1122        if let Some(layer) = self.layers.last_mut() {
1123            layer.show_legend = Some(show);
1124        }
1125        self
1126    }
1127
1128    // ─── Scales ──────────────────────────────────────────────────
1129
1130    pub fn scale_x_continuous(mut self, s: ScaleContinuous) -> Self {
1131        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1132        self.scales.push(Box::new(s));
1133        self
1134    }
1135
1136    pub fn scale_y_continuous(mut self, s: ScaleContinuous) -> Self {
1137        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1138        self.scales.push(Box::new(s));
1139        self
1140    }
1141
1142    pub fn scale_x_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
1143        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1144        self.scales.push(Box::new(s));
1145        self
1146    }
1147
1148    pub fn scale_y_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
1149        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1150        self.scales.push(Box::new(s));
1151        self
1152    }
1153
1154    pub fn scale_color(mut self, s: impl Scale + 'static) -> Self {
1155        self.scales.push(Box::new(s));
1156        self
1157    }
1158
1159    pub fn scale_fill(mut self, s: impl Scale + 'static) -> Self {
1160        self.scales.push(Box::new(s));
1161        self
1162    }
1163
1164    pub fn scale_color_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
1165        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Color, values);
1166        self.scale_color(s)
1167    }
1168
1169    pub fn scale_fill_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
1170        let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Fill, values);
1171        self.scale_fill(s)
1172    }
1173
1174    /// The `colour`/`color` column already holds `#RRGGBB`/`#RGB` hex
1175    /// strings, used as-is — no legend (R's `scale_colour_identity`).
1176    pub fn scale_colour_identity(self) -> Self {
1177        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Color);
1178        self.scale_color(s)
1179    }
1180
1181    /// American-spelling alias for [`scale_colour_identity`](Self::scale_colour_identity).
1182    pub fn scale_color_identity(self) -> Self {
1183        self.scale_colour_identity()
1184    }
1185
1186    /// The `fill` column already holds `#RRGGBB`/`#RGB` hex strings, used
1187    /// as-is — no legend (R's `scale_fill_identity`).
1188    pub fn scale_fill_identity(self) -> Self {
1189        let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Fill);
1190        self.scale_fill(s)
1191    }
1192
1193    pub fn scale_color_viridis(self) -> Self {
1194        use crate::scale::color::ScaleColorDiscrete;
1195        use crate::scale::palettes::PaletteName;
1196        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
1197            .with_named_palette(&PaletteName::Viridis);
1198        self.scale_color(s)
1199    }
1200
1201    pub fn scale_color_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
1202        use crate::scale::color::ScaleColorDiscrete;
1203        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).with_named_palette(&name);
1204        self.scale_color(s)
1205    }
1206
1207    pub fn scale_color_gradient(
1208        self,
1209        low: crate::scale::color::RGBAColor,
1210        high: crate::scale::color::RGBAColor,
1211    ) -> Self {
1212        use crate::scale::color::ScaleColorContinuous;
1213        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Color).with_colors(low, high);
1214        self.scale_color(s)
1215    }
1216
1217    pub fn scale_fill_gradient(
1218        self,
1219        low: crate::scale::color::RGBAColor,
1220        high: crate::scale::color::RGBAColor,
1221    ) -> Self {
1222        use crate::scale::color::ScaleColorContinuous;
1223        let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Fill).with_colors(low, high);
1224        self.scale_fill(s)
1225    }
1226
1227    pub fn scale_color_gradient2(
1228        self,
1229        low: crate::scale::color::RGBAColor,
1230        mid: crate::scale::color::RGBAColor,
1231        high: crate::scale::color::RGBAColor,
1232    ) -> Self {
1233        use crate::scale::gradient::ScaleColorGradient2;
1234        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Color).with_colors(low, mid, high);
1235        self.scale_color(s)
1236    }
1237
1238    pub fn scale_fill_gradient2(
1239        self,
1240        low: crate::scale::color::RGBAColor,
1241        mid: crate::scale::color::RGBAColor,
1242        high: crate::scale::color::RGBAColor,
1243    ) -> Self {
1244        use crate::scale::gradient::ScaleColorGradient2;
1245        let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Fill).with_colors(low, mid, high);
1246        self.scale_fill(s)
1247    }
1248
1249    pub fn scale_fill_viridis(self) -> Self {
1250        use crate::scale::color::ScaleColorDiscrete;
1251        use crate::scale::palettes::PaletteName;
1252        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
1253            .with_named_palette(&PaletteName::Viridis);
1254        self.scale_fill(s)
1255    }
1256
1257    /// Continuous viridis color scale (for numeric data).
1258    pub fn scale_color_viridis_c(self) -> Self {
1259        use crate::scale::gradient_n::ScaleColorGradientN;
1260        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Color);
1261        self.scale_color(s)
1262    }
1263
1264    /// Continuous viridis fill scale (for numeric data).
1265    pub fn scale_fill_viridis_c(self) -> Self {
1266        use crate::scale::gradient_n::ScaleColorGradientN;
1267        let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Fill);
1268        self.scale_fill(s)
1269    }
1270
1271    /// N-stop continuous color gradient.
1272    pub fn scale_color_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
1273        use crate::scale::gradient_n::ScaleColorGradientN;
1274        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Color, stops);
1275        self.scale_color(s)
1276    }
1277
1278    /// N-stop continuous fill gradient.
1279    pub fn scale_fill_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
1280        use crate::scale::gradient_n::ScaleColorGradientN;
1281        let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Fill, stops);
1282        self.scale_fill(s)
1283    }
1284
1285    /// Binned (stepped) two-colour continuous colour scale — buckets the mapped
1286    /// variable into `n_bins` bins, each a discrete colour, with a stepped legend.
1287    pub fn scale_color_steps(
1288        self,
1289        low: crate::scale::color::RGBAColor,
1290        high: crate::scale::color::RGBAColor,
1291        n_bins: usize,
1292    ) -> Self {
1293        let s = crate::scale::steps::ScaleColorSteps::two(
1294            crate::aes::Aesthetic::Color,
1295            (low.r, low.g, low.b),
1296            (high.r, high.g, high.b),
1297            n_bins,
1298        );
1299        self.scale_color(s)
1300    }
1301
1302    /// Binned N-stop continuous colour scale.
1303    pub fn scale_color_stepsn(
1304        self,
1305        stops: Vec<crate::scale::color::RGBAColor>,
1306        n_bins: usize,
1307    ) -> Self {
1308        let s = crate::scale::steps::ScaleColorSteps::new(
1309            crate::aes::Aesthetic::Color,
1310            stops.iter().map(|c| (c.r, c.g, c.b)).collect(),
1311            n_bins,
1312        );
1313        self.scale_color(s)
1314    }
1315
1316    /// Binned ColorBrewer colour scale (R's `scale_color_fermenter`).
1317    pub fn scale_color_fermenter(
1318        self,
1319        name: crate::scale::palettes::PaletteName,
1320        n_bins: usize,
1321    ) -> Self {
1322        let stops = crate::scale::palettes::palette(&name)
1323            .iter()
1324            .map(|c| (c.r, c.g, c.b))
1325            .collect();
1326        let s =
1327            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Color, stops, n_bins);
1328        self.scale_color(s)
1329    }
1330
1331    /// Binned (stepped) two-colour continuous fill scale.
1332    pub fn scale_fill_steps(
1333        self,
1334        low: crate::scale::color::RGBAColor,
1335        high: crate::scale::color::RGBAColor,
1336        n_bins: usize,
1337    ) -> Self {
1338        let s = crate::scale::steps::ScaleColorSteps::two(
1339            crate::aes::Aesthetic::Fill,
1340            (low.r, low.g, low.b),
1341            (high.r, high.g, high.b),
1342            n_bins,
1343        );
1344        self.scale_fill(s)
1345    }
1346
1347    /// Binned ColorBrewer fill scale.
1348    pub fn scale_fill_fermenter(
1349        self,
1350        name: crate::scale::palettes::PaletteName,
1351        n_bins: usize,
1352    ) -> Self {
1353        let stops = crate::scale::palettes::palette(&name)
1354            .iter()
1355            .map(|c| (c.r, c.g, c.b))
1356            .collect();
1357        let s =
1358            crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Fill, stops, n_bins);
1359        self.scale_fill(s)
1360    }
1361
1362    /// Default discrete fill palette with levels in sorted order, so a level
1363    /// keeps its colour across charts regardless of data order. For a custom
1364    /// palette: `scale_fill(ScaleColorDiscrete::new(Aesthetic::Fill)
1365    /// .with_palette(p).sorted())`.
1366    pub fn scale_fill_discrete_sorted(self) -> Self {
1367        use crate::scale::color::ScaleColorDiscrete;
1368        self.scale_fill(ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).sorted())
1369    }
1370
1371    /// Default discrete colour palette with levels in sorted order (see
1372    /// [`scale_fill_discrete_sorted`](Self::scale_fill_discrete_sorted)).
1373    pub fn scale_color_discrete_sorted(self) -> Self {
1374        use crate::scale::color::ScaleColorDiscrete;
1375        self.scale_color(ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).sorted())
1376    }
1377
1378    pub fn scale_fill_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
1379        use crate::scale::color::ScaleColorDiscrete;
1380        let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).with_named_palette(&name);
1381        self.scale_fill(s)
1382    }
1383
1384    pub fn scale_linetype_manual(
1385        self,
1386        values: Vec<(&str, crate::render::backend::Linetype)>,
1387    ) -> Self {
1388        let s = crate::scale::linetype_manual::ScaleLinetypeManual::new(values);
1389        self.scale_color(s)
1390    }
1391
1392    pub fn scale_shape_manual(
1393        self,
1394        values: Vec<(&str, crate::render::backend::PointShape)>,
1395    ) -> Self {
1396        let s = crate::scale::shape_manual::ScaleShapeManual::new(values);
1397        self.scale_color(s)
1398    }
1399
1400    pub fn scale_color_grey(self) -> Self {
1401        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Color);
1402        self.scale_color(s)
1403    }
1404
1405    pub fn scale_fill_grey(self) -> Self {
1406        let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Fill);
1407        self.scale_fill(s)
1408    }
1409
1410    pub fn scale_color_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
1411        self.scale_color(s)
1412    }
1413
1414    pub fn scale_fill_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
1415        self.scale_fill(s)
1416    }
1417
1418    pub fn scale_x_reverse(self) -> Self {
1419        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
1420    }
1421
1422    pub fn scale_y_reverse(self) -> Self {
1423        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
1424    }
1425
1426    pub fn scale_x_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
1427        let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1428        self.scales.push(Box::new(s));
1429        self
1430    }
1431
1432    pub fn scale_y_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
1433        let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1434        self.scales.push(Box::new(s));
1435        self
1436    }
1437
1438    pub fn scale_size(mut self, s: crate::scale::size::ScaleSizeContinuous) -> Self {
1439        self.scales.push(Box::new(s));
1440        self
1441    }
1442
1443    /// `scale_size_area(max_size)` (ggplot2, B3-6): size scale where
1444    /// *area*, not radius, is proportional to the value, and 0 maps to 0.
1445    /// See [`ScaleSizeContinuous::area`](crate::scale::size::ScaleSizeContinuous::area).
1446    pub fn scale_size_area(mut self, max_size: f64) -> Self {
1447        self.scales.push(Box::new(
1448            crate::scale::size::ScaleSizeContinuous::new().area(max_size),
1449        ));
1450        self
1451    }
1452
1453    pub fn scale_alpha(mut self, s: crate::scale::alpha::ScaleAlphaContinuous) -> Self {
1454        self.scales.push(Box::new(s));
1455        self
1456    }
1457
1458    /// Continuous linewidth scale for the `linewidth` aesthetic (segment,
1459    /// curve, path, line) — see
1460    /// [`ScaleLinewidthContinuous`](crate::scale::linewidth::ScaleLinewidthContinuous).
1461    pub fn scale_linewidth(mut self, s: crate::scale::linewidth::ScaleLinewidthContinuous) -> Self {
1462        self.scales.push(Box::new(s));
1463        self
1464    }
1465
1466    pub fn xlim(self, min: f64, max: f64) -> Self {
1467        self.scale_x_continuous(ScaleContinuous::new().with_limits(min, max))
1468    }
1469
1470    pub fn ylim(self, min: f64, max: f64) -> Self {
1471        self.scale_y_continuous(ScaleContinuous::new().with_limits(min, max))
1472    }
1473
1474    pub fn scale_x_log10(self) -> Self {
1475        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
1476    }
1477
1478    pub fn scale_y_log10(self) -> Self {
1479        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
1480    }
1481
1482    pub fn scale_x_sqrt(self) -> Self {
1483        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
1484    }
1485
1486    pub fn scale_y_sqrt(self) -> Self {
1487        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
1488    }
1489
1490    pub fn scale_x_log2(self) -> Self {
1491        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
1492    }
1493
1494    pub fn scale_y_log2(self) -> Self {
1495        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
1496    }
1497
1498    pub fn scale_x_ln(self) -> Self {
1499        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
1500    }
1501
1502    pub fn scale_y_ln(self) -> Self {
1503        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
1504    }
1505
1506    /// Logit-transformed x axis (for proportions in (0, 1)).
1507    pub fn scale_x_logit(self) -> Self {
1508        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
1509    }
1510
1511    pub fn scale_y_logit(self) -> Self {
1512        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
1513    }
1514
1515    /// Probit-transformed x axis (inverse normal CDF, for proportions in (0, 1)).
1516    pub fn scale_x_probit(self) -> Self {
1517        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
1518    }
1519
1520    pub fn scale_y_probit(self) -> Self {
1521        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
1522    }
1523
1524    /// Sign-preserving pseudo-log x axis (handles zero and negative values).
1525    pub fn scale_x_pseudo_log(self) -> Self {
1526        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
1527    }
1528
1529    pub fn scale_y_pseudo_log(self) -> Self {
1530        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
1531    }
1532
1533    /// Reciprocal (1/x) x axis.
1534    pub fn scale_x_reciprocal(self) -> Self {
1535        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
1536    }
1537
1538    pub fn scale_y_reciprocal(self) -> Self {
1539        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
1540    }
1541
1542    /// Exponential x axis (labels spaced logarithmically).
1543    pub fn scale_x_exp(self) -> Self {
1544        self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
1545    }
1546
1547    pub fn scale_y_exp(self) -> Self {
1548        self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
1549    }
1550
1551    /// Box–Cox x axis with the given lambda (x > 0).
1552    pub fn scale_x_boxcox(self, lambda: f64) -> Self {
1553        self.scale_x_continuous(
1554            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
1555        )
1556    }
1557
1558    pub fn scale_y_boxcox(self, lambda: f64) -> Self {
1559        self.scale_y_continuous(
1560            ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
1561        )
1562    }
1563
1564    // ─── Faceting ─────────────────────────────────────────────────
1565
1566    pub fn facet_wrap(mut self, var: &str, ncol: Option<usize>) -> Self {
1567        self.facet = Facet::Wrap {
1568            var: var.to_string(),
1569            ncol,
1570            scales: FacetScales::Fixed,
1571            labeller: FacetLabeller::default(),
1572        };
1573        self
1574    }
1575
1576    pub fn facet_wrap_free(mut self, var: &str, ncol: Option<usize>, scales: FacetScales) -> Self {
1577        self.facet = Facet::Wrap {
1578            var: var.to_string(),
1579            ncol,
1580            scales,
1581            labeller: FacetLabeller::default(),
1582        };
1583        self
1584    }
1585
1586    pub fn facet_wrap_labeller(
1587        mut self,
1588        var: &str,
1589        ncol: Option<usize>,
1590        labeller: FacetLabeller,
1591    ) -> Self {
1592        self.facet = Facet::Wrap {
1593            var: var.to_string(),
1594            ncol,
1595            scales: FacetScales::Fixed,
1596            labeller,
1597        };
1598        self
1599    }
1600
1601    pub fn facet_grid(mut self, row: Option<&str>, col: Option<&str>) -> Self {
1602        self.facet = Facet::Grid {
1603            row_var: row.map(String::from),
1604            col_var: col.map(String::from),
1605            scales: FacetScales::Fixed,
1606            labeller: FacetLabeller::default(),
1607            space: FacetSpace::Fixed,
1608        };
1609        self
1610    }
1611
1612    pub fn facet_grid_free(
1613        mut self,
1614        row: Option<&str>,
1615        col: Option<&str>,
1616        scales: FacetScales,
1617    ) -> Self {
1618        self.facet = Facet::Grid {
1619            row_var: row.map(String::from),
1620            col_var: col.map(String::from),
1621            scales,
1622            labeller: FacetLabeller::default(),
1623            space: FacetSpace::Fixed,
1624        };
1625        self
1626    }
1627
1628    /// `facet_grid` over **multiple** column variables (R's `rows ~ b + c`):
1629    /// the columns become the combination of the given variables' values.
1630    /// Also accepts free scales + proportional `space` for full parity.
1631    pub fn facet_grid_multi(
1632        mut self,
1633        row: Option<&str>,
1634        cols: &[&str],
1635        scales: FacetScales,
1636        space: FacetSpace,
1637    ) -> Self {
1638        let col_var = if cols.len() > 1 {
1639            // Build a synthetic column that is the interaction of the col vars.
1640            let n = self.data.nrows();
1641            let mut combined = Vec::with_capacity(n);
1642            for i in 0..n {
1643                let parts: Vec<String> = cols
1644                    .iter()
1645                    .map(|c| {
1646                        self.data
1647                            .column(c)
1648                            .and_then(|col| col.get(i))
1649                            .map(|v| v.to_group_key())
1650                            .unwrap_or_default()
1651                    })
1652                    .collect();
1653                combined.push(crate::data::Value::Str(parts.join(" . ")));
1654            }
1655            let name = "__facet_cols__".to_string();
1656            self.data.add_column(name.clone(), combined);
1657            Some(name)
1658        } else {
1659            cols.first().map(|s| s.to_string())
1660        };
1661        self.facet = Facet::Grid {
1662            row_var: row.map(String::from),
1663            col_var,
1664            scales,
1665            labeller: FacetLabeller::default(),
1666            space,
1667        };
1668        self
1669    }
1670
1671    /// `facet_grid` with proportional panel sizing (R's `space =`): panels are
1672    /// sized to their data range. Typically paired with free scales.
1673    pub fn facet_grid_space(
1674        mut self,
1675        row: Option<&str>,
1676        col: Option<&str>,
1677        scales: FacetScales,
1678        space: FacetSpace,
1679    ) -> Self {
1680        self.facet = Facet::Grid {
1681            row_var: row.map(String::from),
1682            col_var: col.map(String::from),
1683            scales,
1684            labeller: FacetLabeller::default(),
1685            space,
1686        };
1687        self
1688    }
1689
1690    pub fn facet_grid_labeller(
1691        mut self,
1692        row: Option<&str>,
1693        col: Option<&str>,
1694        labeller: FacetLabeller,
1695    ) -> Self {
1696        self.facet = Facet::Grid {
1697            row_var: row.map(String::from),
1698            col_var: col.map(String::from),
1699            scales: FacetScales::Fixed,
1700            labeller,
1701            space: FacetSpace::Fixed,
1702        };
1703        self
1704    }
1705
1706    // ─── Coordinates ─────────────────────────────────────────────
1707
1708    pub fn coord_flip(mut self) -> Self {
1709        self.coord = Box::new(CoordFlip);
1710        self
1711    }
1712
1713    pub fn coord_fixed(mut self, ratio: f64) -> Self {
1714        self.coord = Box::new(CoordFixed::new(ratio));
1715        self
1716    }
1717
1718    /// Spatial coordinate system (feature `sf`): equal aspect derived from the
1719    /// data extent, so projected geometry keeps its shape. Pair with a `geom_sf`
1720    /// projection (e.g. Mercator) for a conformal map.
1721    #[cfg(feature = "sf")]
1722    pub fn coord_sf(mut self) -> Self {
1723        self.coord = Box::new(crate::coord::sf::CoordSf::new());
1724        self
1725    }
1726
1727    /// Spatial coordinate system with explicit settings (`xlim`/`ylim`/
1728    /// `expand`) — see [`CoordSf`](crate::coord::sf::CoordSf). Used by
1729    /// consumers overlaying a fragment on their own projected basemap: a
1730    /// fixed pixel window via `xlim`/`ylim` and `expand(false)`.
1731    #[cfg(feature = "sf")]
1732    pub fn coord_sf_with(mut self, coord: crate::coord::sf::CoordSf) -> Self {
1733        self.coord = Box::new(coord);
1734        self
1735    }
1736
1737    /// Whether the rendered root `<svg>` carries `data-plot`/`data-domain`/
1738    /// `data-xdomain`/… (see [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
1739    /// Default `true`. A consumer that overlays a rendered fragment
1740    /// (`render_svg_native_at`) on its own basemap — which already has its
1741    /// own root attributes and window — turns this off so the fragment adds
1742    /// none of its own.
1743    pub fn svg_root_data(mut self, on: bool) -> Self {
1744        self.svg_root_data = on;
1745        self
1746    }
1747
1748    /// Add one extra attribute to the root `<svg>` element — a host
1749    /// identifier, an ARIA label, a CSS hook, and so on. Allowed names:
1750    /// `data-*`, `aria-*`, `role`, `id`, `class`, `lang`; anything else, or
1751    /// a name ggplot-rs already writes to the root (`data-plot`,
1752    /// `data-domain`, …, or `data-warnings` when
1753    /// [`svg_warnings_attr`](Self::svg_warnings_attr) is also on), is
1754    /// ignored with a build warning instead of being silently dropped or
1755    /// duplicated. Values are escaped on output. PlotGrid has the same API
1756    /// ([`PlotGrid::svg_attr`](crate::compose::PlotGrid::svg_attr)).
1757    pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1758        self.root_attrs.push((name.into(), value.into()));
1759        self
1760    }
1761
1762    /// [`svg_attr`](Self::svg_attr) for several attributes at once.
1763    pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
1764        self.root_attrs.extend(attrs);
1765        self
1766    }
1767
1768    /// Emit a `data-warnings` attribute on the root `<svg>` — a JSON array
1769    /// of the build warnings (rows dropped for non-finite positions, an
1770    /// `svg_attr` name rejected, …), `[]` when there are none. Default off,
1771    /// and omitted entirely when off (byte-identical to not calling this).
1772    pub fn svg_warnings_attr(mut self, on: bool) -> Self {
1773        self.svg_warnings_attr = on;
1774        self
1775    }
1776
1777    /// Emit `data-fvalue`/`data-fx` on marks: the value aesthetic's raw
1778    /// data value (y for most geoms, fill for hex/tile) and the x value,
1779    /// each formatted through its scale (currency/locale numbers, ISO or
1780    /// locale dates — [`Scale::format_value`](crate::scale::Scale::format_value))
1781    /// rather than the plain display string `data-value`/`data-x` already
1782    /// carry. `data-fx` is omitted when it would just duplicate `data-x`.
1783    /// Default off, and omitted entirely when off (byte-identical to not
1784    /// calling this).
1785    pub fn svg_formatted_values(mut self, on: bool) -> Self {
1786        self.svg_formatted_values = on;
1787        self
1788    }
1789
1790    /// Transform the coordinate space at draw time (R's `coord_trans`) — stats are
1791    /// computed on raw data but drawn on non-linear axes. Pass a per-axis
1792    /// [`ScaleTransform`] (e.g. `Some(ScaleTransform::Log10)`), `None` to leave an
1793    /// axis linear.
1794    pub fn coord_trans(mut self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
1795        self.coord = Box::new(crate::coord::trans::CoordTrans::new(x, y));
1796        self
1797    }
1798
1799    /// `coord_trans` on the y-axis only.
1800    pub fn coord_trans_y(self, y: ScaleTransform) -> Self {
1801        self.coord_trans(None, Some(y))
1802    }
1803
1804    /// `coord_trans` on the x-axis only.
1805    pub fn coord_trans_x(self, x: ScaleTransform) -> Self {
1806        self.coord_trans(Some(x), None)
1807    }
1808
1809    /// Zoom into a region without filtering data (unlike xlim/ylim which filter).
1810    pub fn coord_cartesian_zoom(
1811        mut self,
1812        xlim: Option<(f64, f64)>,
1813        ylim: Option<(f64, f64)>,
1814    ) -> Self {
1815        let mut c = CoordCartesian::new();
1816        if let Some((min, max)) = xlim {
1817            c = c.xlim(min, max);
1818        }
1819        if let Some((min, max)) = ylim {
1820            c = c.ylim(min, max);
1821        }
1822        self.coord = Box::new(c);
1823        self
1824    }
1825
1826    pub fn coord_polar(mut self) -> Self {
1827        self.coord = Box::new(CoordPolar::new());
1828        self
1829    }
1830
1831    /// Radar / spider chart coordinates: discrete `x` → spokes, `y` → distance
1832    /// from the centre, straight segments, ring/spoke guides. Pair with
1833    /// `geom_polygon` (closed series) and `geom_point`.
1834    pub fn coord_radar(mut self) -> Self {
1835        self.coord = Box::new(crate::coord::radar::CoordRadar::new());
1836        self
1837    }
1838
1839    pub fn coord_radar_with(mut self, coord: crate::coord::radar::CoordRadar) -> Self {
1840        self.coord = Box::new(coord);
1841        self
1842    }
1843
1844    pub fn coord_polar_with(mut self, coord: CoordPolar) -> Self {
1845        self.coord = Box::new(coord);
1846        self
1847    }
1848
1849    // ─── Theme ───────────────────────────────────────────────────
1850
1851    /// Replace the theme. A `primary_color` set earlier is kept unless the new
1852    /// theme sets its own, so preset/`primary_color` call order doesn't matter.
1853    pub fn theme(mut self, theme: Theme) -> Self {
1854        self.apply_preset(theme);
1855        self
1856    }
1857
1858    fn apply_preset(&mut self, theme: Theme) {
1859        let primary = self.theme.primary;
1860        self.theme = theme;
1861        if self.theme.primary.is_none() {
1862            self.theme.primary = primary;
1863        }
1864    }
1865
1866    /// Rotate the x-axis tick labels by `degrees` (R's
1867    /// `guides(x = guide_axis(angle = ...))` / `axis.text.x = element_text(angle)`).
1868    /// Useful for long category labels. Call after any `theme_*()` preset.
1869    pub fn axis_text_x_angle(mut self, degrees: f64) -> Self {
1870        self.theme.axis_text_x.angle = degrees;
1871        self
1872    }
1873
1874    /// Rotate the y-axis tick labels by `degrees`.
1875    pub fn axis_text_y_angle(mut self, degrees: f64) -> Self {
1876        self.theme.axis_text_y.angle = degrees;
1877        self
1878    }
1879
1880    /// Stagger x-axis tick labels across `n` rows to avoid overlap (R's
1881    /// `guides(x = guide_axis(n.dodge = n))`). `1` = no dodging.
1882    pub fn axis_text_x_dodge(mut self, n: usize) -> Self {
1883        self.theme.axis_text_x_dodge = n.max(1);
1884        self
1885    }
1886
1887    /// Fix the panel's height:width ratio (R's `aspect.ratio`). Call after any
1888    /// `theme_*()` preset.
1889    pub fn aspect_ratio(mut self, ratio: f64) -> Self {
1890        self.theme.aspect_ratio = Some(ratio);
1891        self
1892    }
1893
1894    /// Draw gridlines on top of the data layers (R's `panel.ontop`).
1895    pub fn panel_ontop(mut self) -> Self {
1896        self.theme.panel_ontop = true;
1897        self
1898    }
1899
1900    /// Draw minor tick marks between major ticks (R's `axis.minor.ticks`).
1901    pub fn axis_minor_ticks(mut self) -> Self {
1902        self.theme.axis_minor_ticks = true;
1903        self
1904    }
1905
1906    /// How an outer x-axis label that would cross the SVG edge is handled
1907    /// (B3-1, D6): [`AxisLabelFit::Reserve`](crate::theme::AxisLabelFit::Reserve) (default), `Shift`, or `Clip`
1908    /// (the 0.21 behaviour). Use `Shift` for panels that must stay
1909    /// pixel-aligned with other elements (e.g. a host's own aligned strip).
1910    pub fn axis_text_x_fit(mut self, fit: crate::theme::AxisLabelFit) -> Self {
1911        self.theme.axis_text_x_fit = fit;
1912        self
1913    }
1914
1915    /// Thin crowded x-axis labels in ggplot2's `check.overlap` priority
1916    /// order (B3-1, D5). Off by default.
1917    pub fn axis_text_x_check_overlap(mut self, on: bool) -> Self {
1918        self.theme.axis_text_x_check_overlap = on;
1919        self
1920    }
1921
1922    /// Align title/subtitle/caption to the panel or the whole plot width
1923    /// (R's `plot.title.position`).
1924    pub fn title_position(mut self, pos: crate::theme::TitlePosition) -> Self {
1925        self.theme.title_position = pos;
1926        self
1927    }
1928
1929    /// Corner for the `tag()` label (R's `plot.tag.position`).
1930    pub fn tag_position(mut self, pos: crate::theme::TagPosition) -> Self {
1931        self.theme.tag_position = pos;
1932        self
1933    }
1934
1935    /// Force the legend key layout direction (R's `legend.direction`).
1936    pub fn legend_direction(mut self, dir: crate::theme::LegendDirection) -> Self {
1937        self.theme.legend_direction = Some(dir);
1938        self
1939    }
1940
1941    /// Set the brand/primary color used as the default for single-series geoms
1942    /// that have no color/fill aesthetic mapped. Composes with any theme — one
1943    /// render process can serve different tenants' brands at render time.
1944    /// Place the legend inside the panel at panel-relative coordinates
1945    /// (0..1, 0..1) — `(0,0)` bottom-left, `(1,1)` top-right (R's
1946    /// `legend.position = c(x, y)`).
1947    pub fn legend_position_inside(mut self, x: f64, y: f64) -> Self {
1948        self.theme.legend_position = crate::theme::LegendPosition::Inside(x, y);
1949        self
1950    }
1951
1952    /// Set the legend position (R's `legend.position`, e.g. `Top`/`Bottom`).
1953    pub fn legend_position(mut self, pos: crate::theme::LegendPosition) -> Self {
1954        self.theme.legend_position = pos;
1955        self
1956    }
1957
1958    pub fn primary_color(mut self, color: (u8, u8, u8)) -> Self {
1959        self.theme.primary = Some(color);
1960        self
1961    }
1962
1963    pub fn theme_minimal(mut self) -> Self {
1964        self.apply_preset(crate::theme::presets::theme_minimal());
1965        self
1966    }
1967
1968    pub fn theme_bw(mut self) -> Self {
1969        self.apply_preset(crate::theme::presets::theme_bw());
1970        self
1971    }
1972
1973    pub fn theme_gray(mut self) -> Self {
1974        self.apply_preset(crate::theme::presets::theme_gray());
1975        self
1976    }
1977
1978    pub fn theme_classic(mut self) -> Self {
1979        self.apply_preset(crate::theme::presets::theme_classic());
1980        self
1981    }
1982
1983    /// Apply the publication-ready `theme_pubr()` (ggpubr style).
1984    pub fn theme_pubr(mut self) -> Self {
1985        self.apply_preset(crate::theme::presets::theme_pubr());
1986        self
1987    }
1988
1989    pub fn theme_linedraw(mut self) -> Self {
1990        self.apply_preset(crate::theme::presets::theme_linedraw());
1991        self
1992    }
1993
1994    pub fn theme_light(mut self) -> Self {
1995        self.apply_preset(crate::theme::presets::theme_light());
1996        self
1997    }
1998
1999    pub fn theme_dark(mut self) -> Self {
2000        self.apply_preset(crate::theme::presets::theme_dark());
2001        self
2002    }
2003
2004    pub fn theme_void(mut self) -> Self {
2005        self.apply_preset(crate::theme::presets::theme_void());
2006        self
2007    }
2008
2009    /// Apply incremental theme modifications on top of the current theme.
2010    /// Like R's `+ theme(axis.text.x = element_text(...))`.
2011    pub fn theme_update(mut self, update: crate::theme::ThemeUpdate) -> Self {
2012        self.theme = self.theme.update(update);
2013        self
2014    }
2015
2016    // ─── Guides ──────────────────────────────────────────────────
2017
2018    /// Configure legend guide (title, ncol, reverse).
2019    pub fn guides(mut self, guide: crate::guide::config::GuideLegend) -> Self {
2020        self.guide_legend = guide;
2021        self
2022    }
2023
2024    // ─── Labels ──────────────────────────────────────────────────
2025
2026    pub fn labs(mut self, labels: Labels) -> Self {
2027        if labels.title.is_some() {
2028            self.labels.title = labels.title;
2029        }
2030        if labels.subtitle.is_some() {
2031            self.labels.subtitle = labels.subtitle;
2032        }
2033        if labels.x.is_some() {
2034            self.labels.x = labels.x;
2035        }
2036        if labels.y.is_some() {
2037            self.labels.y = labels.y;
2038        }
2039        if labels.caption.is_some() {
2040            self.labels.caption = labels.caption;
2041        }
2042        if labels.tag.is_some() {
2043            self.labels.tag = labels.tag;
2044        }
2045        self
2046    }
2047
2048    pub fn title(mut self, title: &str) -> Self {
2049        self.labels.title = Some(title.to_string());
2050        self
2051    }
2052
2053    /// Corner tag label (R's `labs(tag = ...)`), drawn at the top-left — handy
2054    /// for labelling figure panels ("A", "B", …).
2055    pub fn tag(mut self, tag: &str) -> Self {
2056        self.labels.tag = Some(tag.to_string());
2057        self
2058    }
2059
2060    pub fn subtitle(mut self, subtitle: &str) -> Self {
2061        self.labels.subtitle = Some(subtitle.to_string());
2062        self
2063    }
2064
2065    pub fn xlab(mut self, label: &str) -> Self {
2066        self.labels.x = Some(label.to_string());
2067        self
2068    }
2069
2070    pub fn ylab(mut self, label: &str) -> Self {
2071        self.labels.y = Some(label.to_string());
2072        self
2073    }
2074
2075    pub fn caption(mut self, caption: &str) -> Self {
2076        self.labels.caption = Some(caption.to_string());
2077        self
2078    }
2079
2080    // ─── Annotations ──────────────────────────────────────────────
2081
2082    /// Add an annotation to the plot.
2083    pub fn annotate(mut self, annotation: Annotation) -> Self {
2084        self.annotations.push(annotation);
2085        self
2086    }
2087
2088    /// Add a text annotation at data coordinates.
2089    pub fn annotate_text(self, label: &str, x: f64, y: f64) -> Self {
2090        self.annotate(Annotation::text(label, x, y))
2091    }
2092
2093    /// Add a rectangle annotation at data coordinates.
2094    pub fn annotate_rect(self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
2095        self.annotate(Annotation::rect(xmin, xmax, ymin, ymax))
2096    }
2097
2098    /// Add a segment annotation between data coordinates.
2099    pub fn annotate_segment(self, x: f64, y: f64, xend: f64, yend: f64) -> Self {
2100        self.annotate(Annotation::segment(x, y, xend, yend))
2101    }
2102
2103    /// Default [`Locale`](crate::locale::Locale) for the plot's axis and
2104    /// legend labels: every continuous position / colour / size / alpha scale
2105    /// labels its default breaks with the locale's decimal and thousands marks
2106    /// (`1.000`, `2,5` in de-DE), and date/datetime scales use its month names
2107    /// and date formats (`Okt. 2026`, `15. Okt. 2026`). A scale's own
2108    /// `with_locale` and custom `label_*` formatters take precedence.
2109    /// Without this call labels are unchanged (`.` decimal mark, no grouping,
2110    /// ISO dates).
2111    ///
2112    /// ```
2113    /// use ggplot_rs::prelude::*;
2114    /// let svg = GGPlot::new(vec![
2115    ///         ("x".to_string(), vec![Value::Float(0.0), Value::Float(3000.0)]),
2116    ///         ("y".to_string(), vec![Value::Float(0.5), Value::Float(2.5)]),
2117    ///     ])
2118    ///     .aes(Aes::new().x("x").y("y"))
2119    ///     .geom_point()
2120    ///     .locale(Locale::from_tag("de-DE"))
2121    ///     .render_svg_native()
2122    ///     .unwrap();
2123    /// assert!(svg.contains(">1.000<") && svg.contains(">1,5<"));
2124    /// ```
2125    pub fn locale(mut self, locale: crate::locale::Locale) -> Self {
2126        self.locale = Some(locale);
2127        self
2128    }
2129
2130    // ─── Build and Render ────────────────────────────────────────
2131
2132    /// Build the plot without rendering, returning errors on validation failure.
2133    pub fn try_build(self) -> Result<crate::build::BuiltPlot, GGError> {
2134        PlotBuilder::build(self)
2135    }
2136
2137    /// Build the plot without rendering (analogous to R's ggplot_build()).
2138    /// Returns the fully computed BuiltPlot with layer data ready for inspection.
2139    /// Panics on validation errors — use `try_build()` for error handling.
2140    pub fn build(self) -> crate::build::BuiltPlot {
2141        self.try_build().expect("plot build failed")
2142    }
2143
2144    /// Build and save the plot to a file. Format determined by extension.
2145    /// (Requires the `plotters` feature, on by default; native only — wasm has
2146    /// no filesystem/plotters backend.)
2147    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2148    pub fn save(self, path: &str) -> Result<(), GGError> {
2149        self.save_with_size(path, 800, 600)
2150    }
2151
2152    /// Build and save with custom dimensions. (Feature `plotters`; native only.)
2153    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2154    pub fn save_with_size(self, path: &str, w: u32, h: u32) -> Result<(), GGError> {
2155        let (built, layout) = self.prepare(w, h)?;
2156
2157        // Determine backend from file extension
2158        let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
2159
2160        match ext.as_str() {
2161            "svg" => {
2162                let backend = plotters::prelude::SVGBackend::new(path, (w, h));
2163                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2164            }
2165            "png" | "bmp" | "gif" | "jpeg" | "jpg" | "tiff" => {
2166                let backend = plotters::prelude::BitMapBackend::new(path, (w, h));
2167                Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2168            }
2169            _ => {
2170                return Err(GGError::UnsupportedFormat(ext));
2171            }
2172        }
2173
2174        Ok(())
2175    }
2176
2177    /// Render the plot to an in-memory SVG document (default 800x600).
2178    ///
2179    /// Unlike [`save`](Self::save), this writes nothing to disk — handy for
2180    /// serving charts from a web/MCP service. Requires the `plotters` feature
2181    /// (on by default); without it use [`render_svg_native`](Self::render_svg_native).
2182    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2183    pub fn render_svg(self) -> Result<String, GGError> {
2184        self.render_svg_with_size(800, 600)
2185    }
2186
2187    /// Render the plot to an in-memory SVG document with custom dimensions.
2188    /// (Feature `plotters`; native only — on wasm or without `plotters` use
2189    /// [`render_svg_native_with_size`](Self::render_svg_native_with_size).)
2190    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2191    pub fn render_svg_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
2192        let (built, layout) = self.prepare(w, h)?;
2193        let mut buf = String::new();
2194        {
2195            let backend = plotters::prelude::SVGBackend::with_string(&mut buf, (w, h));
2196            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2197        }
2198        Ok(buf)
2199    }
2200
2201    /// Render to SVG through the self-contained [`SvgBackend`](crate::render::svg_backend::SvgBackend)
2202    /// — a plotters-free path that drives the same `PlotRenderer`, proving the
2203    /// `DrawBackend` abstraction (and needing no glyph rasterization).
2204    pub fn render_svg_native(self) -> Result<String, GGError> {
2205        self.render_svg_native_with_size(800, 600)
2206    }
2207
2208    /// [`render_svg_native`](Self::render_svg_native) with an explicit size.
2209    ///
2210    /// The root `<svg>` carries `data-plot="x y w h"` (the panel rect) and the
2211    /// trained position domains (`data-domain`, `data-xdomain`, `data-ydomain`,
2212    /// `data-xlevels`, `data-ylevels` — see
2213    /// [`root_data_attrs`](crate::render::svg_backend::root_data_attrs)).
2214    /// Hoverable marks carry `data-x`, `data-series` and `data-value`.
2215    pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
2216        Ok(self.render_native(w, h)?.0.finish())
2217    }
2218
2219    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
2220    /// but also returns the build warnings (rows dropped for non-finite
2221    /// positions, layers whose stat produced no data, …) — see
2222    /// [`BuiltPlot::warnings`](crate::build::BuiltPlot::warnings).
2223    pub fn render_svg_native_with_warnings(
2224        self,
2225        w: u32,
2226        h: u32,
2227    ) -> Result<(String, Vec<String>), GGError> {
2228        let (backend, warnings, _) = self.render_native(w, h)?;
2229        Ok((backend.finish(), warnings))
2230    }
2231
2232    /// Render a `w`×`h` chart as a *nested* `<svg x=.. y=.. width=.. height=..
2233    /// viewBox="0 0 w h">` fragment for composition into a larger SVG (a
2234    /// dashboard): no `xmlns` (inherited from the parent), positioned at
2235    /// `(x, y)` in the parent's user space. No string surgery needed:
2236    ///
2237    /// ```ignore
2238    /// let mut page = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg" width="900" height="400">"#);
2239    /// page += &plot_a.render_svg_native_at(0.0, 0.0, 450, 400)?;
2240    /// page += &plot_b.render_svg_native_at(450.0, 0.0, 450, 400)?;
2241    /// page += "</svg>";
2242    /// ```
2243    pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
2244        Ok(self.render_native(w, h)?.0.finish_fragment(x, y))
2245    }
2246
2247    /// Like [`render_svg_native_with_size`](Self::render_svg_native_with_size),
2248    /// but also returns the panel rect in pixels `[x, y, w, h]` — enough to
2249    /// overlay a WebGL/canvas layer that draws marks in data coordinates.
2250    pub fn render_svg_area_with_size(self, w: u32, h: u32) -> Result<(String, [f64; 4]), GGError> {
2251        let (backend, _, pa) = self.render_native(w, h)?;
2252        Ok((backend.finish(), [pa.x, pa.y, pa.width, pa.height]))
2253    }
2254
2255    /// Shared native-SVG pipeline: build, lay out, render into an
2256    /// [`SvgBackend`](crate::render::svg_backend::SvgBackend) (not yet
2257    /// finished), returning it with the build warnings and the panel rect.
2258    fn render_native(
2259        self,
2260        w: u32,
2261        h: u32,
2262    ) -> Result<
2263        (
2264            crate::render::svg_backend::SvgBackend,
2265            Vec<String>,
2266            crate::render::Rect,
2267        ),
2268        GGError,
2269    > {
2270        let svg_root_data = self.svg_root_data;
2271        let root_attrs = self.root_attrs.clone();
2272        let svg_warnings_attr = self.svg_warnings_attr;
2273        let svg_formatted_values = self.svg_formatted_values;
2274        let (built, layout) = self.prepare(w, h)?;
2275        let pa = layout.plot_area.clone();
2276        let mut backend = crate::render::svg_backend::SvgBackend::new(w, h, pa.clone());
2277        backend.set_formatted_values(svg_formatted_values);
2278        let existing_root_attrs = if svg_root_data {
2279            let attrs = crate::render::svg_backend::root_data_attrs(&built);
2280            backend.set_root_attrs(attrs.clone());
2281            // `data-plot` itself is a literal in `root_open`, not part of
2282            // `root_data_attrs`'s output, but it is written whenever
2283            // `svg_root_data` is on — reserve it too.
2284            let mut reserved = attrs;
2285            reserved.push(("data-plot".to_string(), String::new()));
2286            reserved
2287        } else {
2288            backend.without_plot_attr();
2289            Vec::new()
2290        };
2291        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2292        let mut warnings = built.warnings;
2293        warnings.extend(backend.take_warnings());
2294
2295        let mut reserved = existing_root_attrs;
2296        if svg_warnings_attr {
2297            reserved.push(("data-warnings".to_string(), String::new()));
2298        }
2299        let extra = crate::render::svg_backend::validate_root_attrs(
2300            &root_attrs,
2301            &reserved,
2302            "plot",
2303            &mut warnings,
2304        );
2305        backend.extend_root_attrs(extra);
2306        if svg_warnings_attr {
2307            backend.extend_root_attrs(vec![(
2308                "data-warnings".to_string(),
2309                crate::render::svg_backend::warnings_json(&warnings),
2310            )]);
2311        }
2312        Ok((backend, warnings, pa))
2313    }
2314
2315    /// Render to a raw RGBA pixel buffer via the self-contained raster
2316    /// [`PixelBackend`](crate::render::pixel_backend::PixelBackend) (feature
2317    /// `canvas`) — fast for large-N and wasm-compatible. Returns `(w, h, rgba)`,
2318    /// ready for a `<canvas>` `putImageData`.
2319    #[cfg(feature = "canvas")]
2320    pub fn render_rgba_with_size(self, w: u32, h: u32) -> Result<(u32, u32, Vec<u8>), GGError> {
2321        let (built, layout) = self.prepare(w, h)?;
2322        let mut backend =
2323            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
2324        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2325        let (ow, oh) = backend.dimensions();
2326        Ok((ow, oh, backend.into_rgba()))
2327    }
2328
2329    /// Like [`render_rgba_with_size`](Self::render_rgba_with_size), but also
2330    /// returns the panel rect in pixels `[x, y, w, h]` — enough to map a canvas
2331    /// pixel back to data coordinates for interactive hover.
2332    #[cfg(feature = "canvas")]
2333    pub fn render_rgba_area_with_size(
2334        self,
2335        w: u32,
2336        h: u32,
2337    ) -> Result<(Vec<u8>, [f64; 4]), GGError> {
2338        let (built, layout) = self.prepare(w, h)?;
2339        let pa = layout.plot_area.clone();
2340        let mut backend = crate::render::pixel_backend::PixelBackend::new(w, h, pa.clone());
2341        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2342        Ok((backend.into_rgba(), [pa.x, pa.y, pa.width, pa.height]))
2343    }
2344
2345    /// Render to PNG bytes via the raster [`PixelBackend`](crate::render::pixel_backend::PixelBackend)
2346    /// (feature `canvas`). Unlike [`render_png`](Self::render_png) this needs no
2347    /// plotters bitmap backend, so it also works on wasm.
2348    #[cfg(feature = "canvas")]
2349    pub fn render_png_raster_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
2350        let (built, layout) = self.prepare(w, h)?;
2351        let mut backend =
2352            crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
2353        PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2354        backend.into_png().map_err(GGError::Render)
2355    }
2356
2357    /// Render the plot to in-memory PNG bytes (default 800x600).
2358    ///
2359    /// Returns a fully-encoded PNG, ready to write to an HTTP response or
2360    /// embed as a data URI — no temp files involved. Requires the `plotters`
2361    /// feature (on by default); see also `render_png_raster_with_size`
2362    /// (feature `canvas`).
2363    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2364    pub fn render_png(self) -> Result<Vec<u8>, GGError> {
2365        self.render_png_with_size(800, 600)
2366    }
2367
2368    /// Render the plot to in-memory PNG bytes with custom dimensions. (Feature
2369    /// `plotters`; native only — PNG needs the plotters bitmap backend.)
2370    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2371    pub fn render_png_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
2372        let (built, layout) = self.prepare(w, h)?;
2373
2374        // plotters' BitMapBackend draws into a raw RGB buffer; we then encode
2375        // that buffer to PNG via the `image` crate.
2376        let mut rgb = vec![0u8; (w as usize) * (h as usize) * 3];
2377        {
2378            let backend = plotters::prelude::BitMapBackend::with_buffer(&mut rgb, (w, h));
2379            Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2380        }
2381
2382        let img = image::RgbImage::from_raw(w, h, rgb).ok_or_else(|| {
2383            GGError::Render(RenderError::BackendError(
2384                "PNG buffer size mismatch".to_string(),
2385            ))
2386        })?;
2387        let mut out = std::io::Cursor::new(Vec::new());
2388        img.write_to(&mut out, image::ImageOutputFormat::Png)
2389            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2390        Ok(out.into_inner())
2391    }
2392
2393    /// Shared pipeline: build the plot, apply label overrides, compute layout.
2394    pub(crate) fn prepare(
2395        self,
2396        w: u32,
2397        h: u32,
2398    ) -> Result<(crate::build::BuiltPlot, PlotLayout), GGError> {
2399        let (mut built, meta) = self.build_for_render()?;
2400        let layout = Self::layout_built(&mut built, &meta, w, h);
2401        Ok((built, layout))
2402    }
2403
2404    /// The size-independent half of [`prepare`](Self::prepare): build the plot,
2405    /// resolve theme inheritance and apply axis-label overrides.
2406    pub(crate) fn build_for_render(self) -> Result<(crate::build::BuiltPlot, RenderMeta), GGError> {
2407        let plot = self;
2408
2409        let has_title = plot.labels.title.is_some();
2410        let has_subtitle = plot.labels.subtitle.is_some();
2411        let has_caption = plot.labels.caption.is_some();
2412        let has_legend = plot.has_legend_mapping();
2413        let x_label = plot.labels.x.clone();
2414        let y_label = plot.labels.y.clone();
2415
2416        let mut built = PlotBuilder::build(plot)?;
2417
2418        // Resolve R-style theme inheritance (root `text` → child text elements).
2419        built.theme.resolve_inheritance();
2420
2421        // Apply user label overrides to scales
2422        if let Some(ref label) = x_label {
2423            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::X) {
2424                s.set_name(label);
2425            }
2426        }
2427        if let Some(ref label) = y_label {
2428            if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::Y) {
2429                s.set_name(label);
2430            }
2431        }
2432
2433        Ok((
2434            built,
2435            RenderMeta {
2436                has_title,
2437                has_subtitle,
2438                has_caption,
2439                has_legend,
2440            },
2441        ))
2442    }
2443
2444    /// The size-dependent half of [`prepare`](Self::prepare): auto-tune axis
2445    /// labels for `w`×`h` and compute the layout.
2446    pub(crate) fn layout_built(
2447        built: &mut crate::build::BuiltPlot,
2448        meta: &RenderMeta,
2449        w: u32,
2450        h: u32,
2451    ) -> PlotLayout {
2452        let RenderMeta {
2453            has_title,
2454            has_subtitle,
2455            has_caption,
2456            has_legend,
2457        } = *meta;
2458        let x_axis_top = built
2459            .scales
2460            .get(&crate::aes::Aesthetic::X)
2461            .map(|s| s.axis_position_opposite())
2462            .unwrap_or(false);
2463
2464        // Auto-tune categorical axis labels so they stay legible. A flip swaps
2465        // which trained scale sits on each visual axis: the bottom (x) axis reads
2466        // the Y scale when flipped, the left (y) axis reads the X scale.
2467        let flipped = built.coord.is_flipped();
2468        let h_aes = if flipped {
2469            crate::aes::Aesthetic::Y
2470        } else {
2471            crate::aes::Aesthetic::X
2472        };
2473        let v_aes = if flipped {
2474            crate::aes::Aesthetic::X
2475        } else {
2476            crate::aes::Aesthetic::Y
2477        };
2478
2479        // Crowded discrete bottom-axis labels overlap when drawn flat. Rotate
2480        // them — 45° if that de-collides, otherwise vertical (90°) — and reserve
2481        // the bottom space they actually need. Only when no explicit angle was set.
2482        let x_rot: Option<(f64, f64)> =
2483            if built.theme.axis_text_x.visible && built.theme.axis_text_x.angle.abs() < 1.0 {
2484                built.scales.get(&h_aes).and_then(|hs| {
2485                    if !hs.is_discrete() {
2486                        return None;
2487                    }
2488                    let breaks = hs.breaks();
2489                    let n = breaks.len().max(1) as f64;
2490                    let max_ch = breaks
2491                        .iter()
2492                        .map(|(_, l)| l.chars().count())
2493                        .max()
2494                        .unwrap_or(0) as f64;
2495                    let font = built.theme.axis_text_x.size;
2496                    let label_w = max_ch * font * 0.6; // horizontal extent, drawn flat
2497                    let spacing = 0.9 * w as f64 / n; // ~px between adjacent ticks
2498                    if label_w <= spacing {
2499                        return None; // fits flat — leave it
2500                    }
2501                    // 45° shrinks the horizontal footprint by cos45; if that fits,
2502                    // use it, else go vertical (270° = reads bottom-to-top, hanging
2503                    // below the axis like the y-axis title). Reserve the drop height.
2504                    let vertical = label_w * 0.707 > spacing;
2505                    let angle = if vertical { 270.0 } else { 45.0 };
2506                    let drop = if vertical { label_w } else { label_w * 0.707 };
2507                    Some((angle, drop + font + 4.0))
2508                })
2509            } else {
2510                None
2511            };
2512        let x_label_height = x_rot.map(|(_, drop)| drop);
2513        if let Some((angle, _)) = x_rot {
2514            built.theme.axis_text_x.angle = angle;
2515        }
2516
2517        // Reserve the left-axis width from the actual label lengths so long
2518        // category names (a flipped bar chart's rows) aren't clipped. Never
2519        // shrinks below the default; grows up to 35% of the width.
2520        let y_label_width = if built.theme.axis_text_y.visible {
2521            built.scales.get(&v_aes).map(|vs| {
2522                let max_ch = vs
2523                    .breaks()
2524                    .iter()
2525                    .map(|(_, l)| l.chars().count())
2526                    .max()
2527                    .unwrap_or(0);
2528                let measured = max_ch as f64 * built.theme.axis_text_y.size * 0.6 + 4.0;
2529                let default = built.theme.axis_text_y.size * 3.5 + 4.0;
2530                measured.max(default).min(0.35 * w as f64)
2531            })
2532        } else {
2533            None
2534        };
2535
2536        // B3-1 (D6): reserve just enough left/right panel margin to keep
2537        // the outer x-axis labels on-canvas under `AxisLabelFit::Reserve`,
2538        // for a single (non-faceted) panel on a coord that supports it
2539        // (not polar/radar/sf, where a label bbox doesn't map to a simple
2540        // panel margin). A faceted plot skips the layout-level reservation
2541        // and relies on `draw_x_axis`'s own draw-time shift instead — so
2542        // does `AxisLabelFit::Shift` (the panel must keep its size) and
2543        // `Clip` (the 0.21 behaviour, no correction at all). A plot whose
2544        // outer labels already fit never grows `extras`, so it stays
2545        // byte-identical.
2546        let mut extras = crate::render::layout::LayoutExtras::default();
2547        let can_reserve = built.facet.is_none()
2548            && built.theme.axis_text_x.visible
2549            && built.theme.axis_text_x_fit == crate::theme::AxisLabelFit::Reserve
2550            && !built.coord.is_polar()
2551            && built.coord.supports_axis_reserve();
2552        if can_reserve {
2553            if let Some(hs) = built.scales.get(&h_aes) {
2554                let breaks = hs.breaks();
2555                if let (Some(first), Some(last)) = (breaks.first(), breaks.last()) {
2556                    let angle = built.theme.axis_text_x.angle;
2557                    let anchor = if angle.abs() > 10.0 { 1.0 } else { 0.5 };
2558                    let size = built.theme.axis_text_x.size;
2559                    const EDGE: f64 = 1.0;
2560                    for _ in 0..2 {
2561                        let layout = PlotLayout::compute_with_extras(
2562                            w as f64,
2563                            h as f64,
2564                            &built.theme,
2565                            has_title,
2566                            has_subtitle,
2567                            has_caption,
2568                            has_legend,
2569                            x_axis_top,
2570                            y_label_width,
2571                            x_label_height,
2572                            extras,
2573                        );
2574                        let area = &layout.plot_area;
2575                        let edge_y = area.y + area.height;
2576                        let to_point = |pos: f64| if flipped { (0.0, pos) } else { (pos, 0.0) };
2577                        let px_first = built.coord.transform(to_point(first.0), area).0;
2578                        let px_last = built.coord.transform(to_point(last.0), area).0;
2579                        let bbox_first = crate::render::text::label_bbox(
2580                            &first.1, size, px_first, edge_y, angle, anchor,
2581                        );
2582                        let bbox_last = crate::render::text::label_bbox(
2583                            &last.1, size, px_last, edge_y, angle, anchor,
2584                        );
2585                        let deficit_left = (EDGE - bbox_first[0]).max(0.0);
2586                        let deficit_right = (bbox_last[2] - (w as f64 - EDGE)).max(0.0);
2587                        if deficit_left <= 0.0 && deficit_right <= 0.0 {
2588                            break;
2589                        }
2590                        // Growing the left margin by `eL` (holding `eR` fixed)
2591                        // shifts a label at normalized position `p` right by
2592                        // `eL·(1 − p)`; growing the right margin by `eR`
2593                        // shifts it left by `eR·p` (the panel maps [0, 1] to
2594                        // [plot_x + eL, plot_x + width − eR]). Review #158
2595                        // finding 1: the original code divided by `p_first`
2596                        // and `1 − p_last` — inverted, which over-reserved
2597                        // by about `1/p_last` (≈20× at a typical p_last≈0.95).
2598                        let (p_first, p_last) = (first.0, last.0);
2599                        if deficit_left > 0.0 && deficit_right > 0.0 {
2600                            // Both ends overflow: solve the 2×2 system so
2601                            // each margin accounts for its effect on *both*
2602                            // labels, rather than correcting them
2603                            // independently and overshooting.
2604                            let (a, b, c, d) = (1.0 - p_first, p_first, 1.0 - p_last, p_last);
2605                            let det = a * d - b * c;
2606                            if det.abs() > 0.01 {
2607                                extras.left +=
2608                                    ((deficit_left * d + deficit_right * b) / det).max(0.0);
2609                                extras.right +=
2610                                    ((deficit_right * a + deficit_left * c) / det).max(0.0);
2611                            } else {
2612                                // Degenerate (first and last break nearly
2613                                // coincide in normalized space): fall back
2614                                // to the independent, clamped formulas.
2615                                extras.left += deficit_left / (1.0 - p_first).max(0.05);
2616                                extras.right += deficit_right / p_last.max(0.05);
2617                            }
2618                        } else if deficit_left > 0.0 {
2619                            extras.left += deficit_left / (1.0 - p_first).max(0.05);
2620                        } else if deficit_right > 0.0 {
2621                            extras.right += deficit_right / p_last.max(0.05);
2622                        }
2623                        // Cap the total reservation so the panel can never
2624                        // start beyond the canvas or be squeezed past the
2625                        // same minimum width `compute_with_extras` already
2626                        // floors it to (review #158's second re-review,
2627                        // LOW): a single, centred break whose label is
2628                        // wider than the whole canvas has `p_first ==
2629                        // p_last == 0.5`, so both `eL` and `eR` grow by
2630                        // roughly the same (large) deficit independently,
2631                        // and together they could place `plot_x` past `w`
2632                        // entirely. Past this cap, Reserve simply stops
2633                        // growing and `draw_x_axis`'s own draw-time shift
2634                        // — which always runs for Reserve, the same as for
2635                        // `Shift` — takes over for whatever's still
2636                        // outside, exactly as D6 already documents.
2637                        const MIN_PANEL_WIDTH: f64 = 50.0;
2638                        let cap = (w as f64 - MIN_PANEL_WIDTH).max(0.0);
2639                        if extras.left + extras.right > cap {
2640                            let scale = if extras.left + extras.right > 0.0 {
2641                                cap / (extras.left + extras.right)
2642                            } else {
2643                                0.0
2644                            };
2645                            extras.left *= scale;
2646                            extras.right *= scale;
2647                        }
2648                    }
2649                }
2650            }
2651        }
2652
2653        // B3-2 (D7): a single discrete legend's `nrow`/`ncol` grid, or an
2654        // overflowing horizontal legend's auto-wrap, reserves extra legend
2655        // rows. Scoped to exactly one discrete guide, matching
2656        // `draw_legend_planned`'s own gate — several simultaneous guides
2657        // are a follow-up (sipemu/ggplot-rs#155).
2658        if has_legend
2659            && !matches!(
2660                built.theme.legend_position,
2661                crate::theme::LegendPosition::None
2662            )
2663        {
2664            let legend_aes =
2665                crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
2666            if legend_aes.len() == 1 {
2667                if let Some(scale) = built.scales.get(&legend_aes[0]) {
2668                    if scale.is_discrete() {
2669                        let breaks = scale.breaks();
2670                        let layout0 = PlotLayout::compute_with_extras(
2671                            w as f64,
2672                            h as f64,
2673                            &built.theme,
2674                            has_title,
2675                            has_subtitle,
2676                            has_caption,
2677                            has_legend,
2678                            x_axis_top,
2679                            y_label_width,
2680                            x_label_height,
2681                            extras,
2682                        );
2683                        let (legend_x0, _, mut is_horizontal) =
2684                            crate::guide::legend::legend_position(&built.theme, &layout0.plot_area);
2685                        if let Some(dir) = built.theme.legend_direction {
2686                            is_horizontal =
2687                                matches!(dir, crate::theme::LegendDirection::Horizontal);
2688                        }
2689                        let avail_width =
2690                            (layout0.plot_area.x + layout0.plot_area.width - legend_x0).max(0.0);
2691                        let mut legend_warnings = Vec::new();
2692                        let validated_guide = built
2693                            .guide_legend
2694                            .validated(breaks.len(), &mut legend_warnings);
2695                        let plan = crate::guide::legend::plan_legend(
2696                            &breaks,
2697                            &validated_guide,
2698                            &built.theme,
2699                            avail_width,
2700                            layout0.plot_area.height,
2701                            is_horizontal,
2702                        );
2703                        built.warnings.extend(legend_warnings);
2704                        if let Some(plan) = &plan {
2705                            extras.legend_extra_rows = plan.rows.saturating_sub(1);
2706                            // Review #158 finding 3: a vertical explicit
2707                            // grid with ncol > 1 needs extra legend band
2708                            // width for its later columns, or they run off
2709                            // the canvas (cols is always 1, col_pitch 0,
2710                            // for the horizontal auto-wrap path, so this is
2711                            // a no-op there).
2712                            extras.legend_extra_width =
2713                                plan.cols.saturating_sub(1) as f64 * plan.col_pitch;
2714                            // Review #158's second re-review, LOW: warn
2715                            // when a vertical multi-column grid still runs
2716                            // off the canvas even after reserving the
2717                            // extra width above — e.g. the grid is simply
2718                            // too wide for this chart (many columns, long
2719                            // labels, a narrow canvas). Measures each
2720                            // entry's own actual rendered right edge
2721                            // (swatch + spacing + that label's text width)
2722                            // rather than `cols * col_pitch` (the worst-
2723                            // case upper bound every column *could* need,
2724                            // which over-warns whenever the columns' real
2725                            // labels are shorter than the single widest
2726                            // one `col_pitch` is sized from).
2727                            if !is_horizontal && plan.cols > 1 {
2728                                let final_layout = PlotLayout::compute_with_extras(
2729                                    w as f64,
2730                                    h as f64,
2731                                    &built.theme,
2732                                    has_title,
2733                                    has_subtitle,
2734                                    has_caption,
2735                                    has_legend,
2736                                    x_axis_top,
2737                                    y_label_width,
2738                                    x_label_height,
2739                                    extras,
2740                                );
2741                                let (legend_x_final, _, _) = crate::guide::legend::legend_position(
2742                                    &built.theme,
2743                                    &final_layout.plot_area,
2744                                );
2745                                let swatch_and_gap =
2746                                    built.theme.legend_key_width + built.theme.legend_spacing;
2747                                let text_size = built.theme.legend_text.size;
2748                                let legend_right_edge = plan
2749                                    .entries
2750                                    .iter()
2751                                    .map(|e| {
2752                                        let label = &breaks[e.break_idx].1;
2753                                        legend_x_final
2754                                            + e.x_offset
2755                                            + swatch_and_gap
2756                                            + crate::render::text::text_width(label, text_size)
2757                                    })
2758                                    .fold(0.0_f64, f64::max);
2759                                if legend_right_edge > w as f64 {
2760                                    built.warnings.push(format!(
2761                                        "legend: the {}-column grid still doesn't fit the {w}px chart (needs about {} px)",
2762                                        plan.cols,
2763                                        legend_right_edge.ceil() as i64
2764                                    ));
2765                                }
2766                            }
2767                            if let Some(ov) = &plan.overflow {
2768                                let n = breaks.len();
2769                                let shown = n - ov.dropped;
2770                                built.warnings.push(format!(
2771                                    "legend: {} of {n} entries don't fit the chart; the legend shows {shown} and \"+{} more\"",
2772                                    ov.dropped, ov.dropped
2773                                ));
2774                            }
2775                        }
2776                        // Review #158 finding 2: store this exact plan so
2777                        // `draw_legend_planned` draws it verbatim instead of
2778                        // recomputing against the (shorter) post-reservation
2779                        // panel height, which could warn "+7 more" while
2780                        // drawing "+15 more".
2781                        built.legend_plan = plan;
2782                    }
2783                }
2784            }
2785        }
2786
2787        PlotLayout::compute_with_extras(
2788            w as f64,
2789            h as f64,
2790            &built.theme,
2791            has_title,
2792            has_subtitle,
2793            has_caption,
2794            has_legend,
2795            x_axis_top,
2796            y_label_width,
2797            x_label_height,
2798            extras,
2799        )
2800    }
2801
2802    /// Fill the background, render the built plot, and flush — for any plotters
2803    /// backend. (Native only.)
2804    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2805    fn render_into<DB>(
2806        area: plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
2807        built: &crate::build::BuiltPlot,
2808        layout: &PlotLayout,
2809    ) -> Result<(), GGError>
2810    where
2811        DB: plotters::prelude::DrawingBackend,
2812        DB::ErrorType: 'static,
2813    {
2814        area.fill(&plotters::prelude::WHITE)
2815            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2816        let mut adapter = PlottersAdapter::new(&area, layout.plot_area.clone());
2817        PlotRenderer::render(built, &mut adapter).map_err(GGError::Render)?;
2818        area.present()
2819            .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2820        Ok(())
2821    }
2822
2823    /// Save with physical dimensions (inches) and DPI. (Feature `plotters`;
2824    /// native only.)
2825    #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2826    pub fn ggsave(
2827        self,
2828        path: &str,
2829        width_inches: f64,
2830        height_inches: f64,
2831        dpi: f64,
2832    ) -> Result<(), GGError> {
2833        let w = (width_inches * dpi) as u32;
2834        let h = (height_inches * dpi) as u32;
2835        self.save_with_size(path, w, h)
2836    }
2837
2838    fn has_legend_mapping(&self) -> bool {
2839        self.mapping.mappings.iter().any(|m| {
2840            matches!(
2841                m.aesthetic,
2842                crate::aes::Aesthetic::Color
2843                    | crate::aes::Aesthetic::Fill
2844                    | crate::aes::Aesthetic::Shape
2845                    | crate::aes::Aesthetic::Linetype
2846                    | crate::aes::Aesthetic::Size
2847                    | crate::aes::Aesthetic::Alpha
2848            )
2849        })
2850    }
2851}
2852
2853/// Size-independent facts about a built plot that its layout needs.
2854#[derive(Clone, Copy, Debug)]
2855pub(crate) struct RenderMeta {
2856    pub(crate) has_title: bool,
2857    pub(crate) has_subtitle: bool,
2858    pub(crate) has_caption: bool,
2859    pub(crate) has_legend: bool,
2860}
2861
2862/// Top-level error type.
2863#[derive(Debug)]
2864pub enum GGError {
2865    Render(RenderError),
2866    UnsupportedFormat(String),
2867    Io(std::io::Error),
2868    ValidationError(String),
2869}
2870
2871impl std::fmt::Display for GGError {
2872    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2873        match self {
2874            GGError::Render(e) => write!(f, "Render error: {e}"),
2875            GGError::UnsupportedFormat(ext) => write!(f, "Unsupported output format: {ext}"),
2876            GGError::Io(e) => write!(f, "IO error: {e}"),
2877            GGError::ValidationError(msg) => write!(f, "Validation error: {msg}"),
2878        }
2879    }
2880}
2881
2882impl std::error::Error for GGError {}