ggplot_rs/geom/mod.rs
1pub mod area;
2pub mod arrow;
3pub mod bar;
4pub mod bin2d;
5pub mod blank;
6pub mod boxplot;
7pub mod bracket;
8pub mod candlestick;
9pub mod censor;
10pub mod col;
11pub mod contour;
12pub mod cooks;
13pub mod count;
14pub mod crossbar;
15pub mod curve;
16pub(crate) mod decorative;
17pub mod density;
18pub mod density2d;
19pub mod dotplot;
20pub mod errorbar;
21pub mod errorbarh;
22pub mod freqpoly;
23pub mod hex;
24pub mod histogram;
25pub mod jitter;
26pub mod line;
27pub mod linerange;
28pub mod path;
29pub mod point;
30pub mod pointrange;
31pub mod polygon;
32pub mod qq;
33pub mod raster;
34pub mod rect;
35pub mod refline;
36pub mod repel;
37pub mod ribbon;
38pub mod rug;
39pub mod segment;
40#[cfg(feature = "sf")]
41pub mod sf;
42pub mod smooth;
43pub mod spoke;
44pub mod step;
45pub(crate) mod support;
46pub mod text;
47pub mod tile;
48pub mod violin;
49
50use std::collections::HashMap;
51
52use crate::aes::Aesthetic;
53use crate::coord::Coord;
54use crate::data::DataFrame;
55use crate::position::Position;
56use crate::render::backend::DrawBackend;
57use crate::render::RenderError;
58use crate::scale::ScaleSet;
59use crate::stat::Stat;
60use crate::theme::Theme;
61
62/// Fixed (non-mapped) visual parameters for a geom.
63#[derive(Clone, Debug, Default)]
64pub struct GeomParams {
65 pub values: HashMap<String, f64>,
66 pub color: Option<(u8, u8, u8)>,
67 pub fill: Option<(u8, u8, u8)>,
68 pub alpha: Option<f64>,
69}
70
71/// Trait for geometric objects that draw data on the plot.
72pub trait Geom: Send + Sync {
73 /// Draw this geometry.
74 fn draw(
75 &self,
76 data: &DataFrame,
77 coord: &dyn Coord,
78 scales: &ScaleSet,
79 theme: &Theme,
80 backend: &mut dyn DrawBackend,
81 ) -> Result<(), RenderError>;
82
83 /// Required aesthetics.
84 fn required_aes(&self) -> Vec<Aesthetic>;
85
86 /// Default stat for this geom.
87 fn default_stat(&self) -> Box<dyn Stat>;
88
89 /// Default position adjustment.
90 fn default_position(&self) -> Box<dyn Position>;
91
92 /// Non-mapped visual defaults.
93 fn default_params(&self) -> GeomParams;
94
95 /// Name for debug/display.
96 fn name(&self) -> &str;
97
98 /// Apply a brand/primary color to this geom's single-series default (its
99 /// `color` or `fill`). The build pipeline calls this only when the layer has
100 /// no color/fill aesthetic mapped, so an explicit mapping always wins. The
101 /// default is a no-op; series geoms override it.
102 fn set_series_color(&mut self, _color: (u8, u8, u8)) {}
103
104 /// Recolour this geom's *built-in default* colour/fill from the theme's
105 /// ink/paper/accent palette (B2-7's `element_geom`), called once per
106 /// layer before [`set_series_color`](Self::set_series_color) — and only
107 /// when the layer was *not* configured explicitly (`geom_*_with(...)`;
108 /// the build pipeline gates the call on the same `explicit_style` flag
109 /// `set_series_color`'s brand-colour application is gated on). That
110 /// gate, not a field-value comparison, is what keeps an explicit colour
111 /// untouched: a geom that honours this replaces a field still at its
112 /// own hard-coded default (black/`(50, 50, 50)` → `ink`, white →
113 /// `paper`) by comparing its *value*, which cannot by itself tell an
114 /// explicitly-set colour that happens to equal that default (e.g.
115 /// `GeomPoint { color: (0, 0, 0), .. }` under `geom_point_with`) apart
116 /// from one that was simply never touched — only skipping the call
117 /// entirely for an explicitly-configured layer closes that gap (review
118 /// PR#141 finding 4). Default no-op; `None` fields of `ElementGeom`
119 /// change nothing, so the default theme (no ink/paper/accent set)
120 /// stays byte-identical.
121 fn apply_element_geom(&mut self, _el: &crate::theme::elements::ElementGeom) {}
122
123 /// Whether this geom draws from a 0 baseline, so the Y scale should include
124 /// 0 even when `y` is explicitly mapped (bars/columns/area/histograms — as
125 /// in ggplot2). Default false.
126 fn include_zero_baseline(&self) -> bool {
127 false
128 }
129
130 /// Whether `-Inf`/`Inf` position values are meaningful for this geom
131 /// (ggplot2: "extend to the panel edge"). Rows with infinite positions are
132 /// otherwise dropped with a warning before stats run. `NaN` is always
133 /// dropped — unless [`Geom::keeps_na_as_break`] says otherwise. Default
134 /// false; `geom_rect` returns true.
135 fn allows_infinite(&self) -> bool {
136 false
137 }
138
139 /// Whether a row with a non-finite position is a *break* rather than a
140 /// removal (ggplot2's `GeomPath`/`GeomLine` NA handling): the row still
141 /// counts toward the "removed N rows" warning, but it is **not** deleted
142 /// from the built `DataFrame`, so the geom's own per-group point list
143 /// still contains it — as a non-finite pixel position after the scale
144 /// and coordinate transform, which [`crate::render::backend::DrawBackend::draw_line`]
145 /// splits on into separate polylines (ggplot2's NA-break semantics)
146 /// instead of silently joining the finite points across the gap.
147 /// Default false (the row is dropped, as for every other geom);
148 /// line/path/step return true.
149 fn keeps_na_as_break(&self) -> bool {
150 false
151 }
152
153 /// Whether this geom calls [`set_row_extras`] (so it reads
154 /// [`Aes::tooltip`](crate::aes::Aes::tooltip) and
155 /// [`Aes::data_attr`](crate::aes::Aes::data_attr), and a
156 /// [`GGPlot::tooltip`](crate::plot::GGPlot::tooltip) template on it has
157 /// a visible effect). Default false; the build pipeline warns when a
158 /// `tooltip()` template is set on a layer whose geom returns false
159 /// here (review PR#141 finding 6, LOW: a template silently did nothing
160 /// on e.g. `geom_area`/`geom_boxplot`/`geom_ribbon`). Point, segment,
161 /// curve, path, line, hex, polygon, sf, rect/tile and col/bar/
162 /// histogram return true.
163 fn consumes_tooltips(&self) -> bool {
164 false
165 }
166
167 /// Geom-specific data preparation after the stat and position steps but
168 /// before scale training (ggplot2's `GeomX$setup_data`) — e.g. a tile adds
169 /// its `xmin`/`xmax`/`ymin`/`ymax` extents so continuous scales train on
170 /// them. `warnings` is the layer's own build-warnings sink (B3-5: added
171 /// so `GeomBoxplot` can warn on an unparsable outlier value here, the
172 /// same channel every other build warning uses — never `eprintln!`).
173 /// Default: no-op.
174 fn setup_data(&self, _data: &mut DataFrame, _warnings: &mut Vec<String>) {}
175
176 /// Whether the layer inherits the plot-level aesthetic mapping (ggplot2's
177 /// `inherit.aes`). Reference-line geoms return false, as in ggplot2, so a
178 /// plot-level `color`/`x`/`y` mapping does not leak into a `geom_hline`.
179 /// Default true.
180 fn inherit_aes(&self) -> bool {
181 true
182 }
183
184 /// Canonical column names this geom only reads when the user actually
185 /// mapped the corresponding aesthetic (D3, B3-5) — never from a raw
186 /// column that merely happens to share the name (e.g. a SQL alias
187 /// literally called `lower`). `build_layer` drops any of these columns
188 /// right after `resolve_mappings` unless the aesthetic was mapped.
189 /// Default empty; `GeomBoxplot` returns `["lower", "middle", "upper",
190 /// "outliers"]`.
191 fn mapped_only_columns(&self) -> &'static [&'static str] {
192 &[]
193 }
194
195 /// Stat-dependent layer validation beyond [`required_aes`](Self::required_aes)
196 /// (B3-5): called once per layer with the resolved (pre-stat, post-D3-drop)
197 /// column names and the layer's stat name, before the stat runs. Default
198 /// no-op. `GeomBoxplot` requires `lower`/`middle`/`upper` to be mapped
199 /// under `stat="identity"`, else `y`.
200 fn validate_layer(&self, _pre_stat_columns: &[String], _stat_name: &str) -> Result<(), String> {
201 Ok(())
202 }
203}
204
205/// Format a value for a hover tooltip — strings verbatim, numbers rounded short,
206/// `Na` empty.
207pub(crate) fn tip_value(v: &crate::data::Value) -> String {
208 crate::format::format_value(v)
209}
210
211/// Half-width (normalized panel units) for bars on a continuous / date x axis:
212/// `width` × the smallest gap between distinct mapped x positions, like
213/// ggplot2's `resolution(x)`. A fixed fraction would make 60 daily bars overlap
214/// and 3 bars look like slivers. Falls back to `fallback` with < 2 distinct xs.
215pub(crate) fn continuous_bar_half_width(
216 mapped_xs: impl Iterator<Item = f64>,
217 width: f64,
218 fallback: f64,
219) -> f64 {
220 let mut xs: Vec<f64> = mapped_xs.filter(|x| x.is_finite()).collect();
221 xs.sort_by(|a, b| a.total_cmp(b));
222 xs.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
223 let gap = xs
224 .windows(2)
225 .map(|w| w[1] - w[0])
226 .fold(f64::INFINITY, f64::min);
227 if gap.is_finite() && gap > 0.0 {
228 gap * width / 2.0
229 } else {
230 fallback
231 }
232}
233
234/// Raw (unformatted) value for a `data-value` attribute: numbers in shortest
235/// round-trip form, date-times as epoch seconds, strings verbatim. `None` for
236/// missing / non-finite values.
237pub(crate) fn raw_value(v: &crate::data::Value) -> Option<String> {
238 use crate::data::Value;
239 match v {
240 Value::Float(f) if f.is_finite() => Some(format!("{f}")),
241 Value::Float(_) | Value::Na => None,
242 Value::Integer(i) => Some(i.to_string()),
243 Value::DateTime(s) => Some(s.to_string()),
244 Value::Str(s) => Some(s.clone()),
245 Value::Bool(b) => Some(b.to_string()),
246 }
247}
248
249/// The series key of row `i` — its colour, else fill, else group level — for
250/// a `data-series` attribute.
251pub(crate) fn series_key(data: &DataFrame, i: usize) -> Option<String> {
252 ["color", "fill", "group"].iter().find_map(|c| {
253 data.column(c)
254 .and_then(|col| col.get(i))
255 .filter(|v| !v.is_na())
256 .map(tip_value)
257 .filter(|s| !s.is_empty())
258 })
259}
260
261/// The raw measured y of row `i`. Stacked/filled positions overwrite `y` with
262/// the cumulative top, so prefer the pre-position value they preserve.
263pub(crate) fn measured_value(data: &DataFrame, i: usize) -> Option<String> {
264 measured_raw(data, i).and_then(raw_value)
265}
266
267/// [`measured_value`], but the raw `Value` itself (for `Scale::format_value`,
268/// B2-4) instead of its display string.
269pub(crate) fn measured_raw(data: &DataFrame, i: usize) -> Option<&crate::data::Value> {
270 data.column(crate::position::RAW_Y_COL)
271 .or_else(|| data.column("y"))
272 .and_then(|c| c.get(i))
273}
274
275/// Set all per-mark metadata (tooltip, `data-x`, `data-series`, `data-value`)
276/// for the next drawn mark(s).
277pub(crate) fn set_mark(
278 backend: &mut dyn DrawBackend,
279 tooltip: Option<String>,
280 x: Option<String>,
281 series: Option<String>,
282 value: Option<String>,
283) {
284 backend.set_tooltip(tooltip);
285 backend.set_mark_axis(x);
286 backend.set_mark_series(series);
287 backend.set_mark_value(value);
288}
289
290/// Resolve the font family for a text-drawing geom (text, label, repel,
291/// bracket, annotations) — B2-6/B2-7's three-tier order: `geom_family`
292/// (the geom's own `fontfamily`, e.g. `GeomText::with_fontfamily`) when
293/// set, else `theme.geom.family` (B2-7's `element_geom`), else
294/// `theme.text.family` (read after `Theme::resolve_inheritance`, so an
295/// inherited value is already resolved), else `None` (the SVG backend's
296/// own `"sans-serif"` default). `ElementText::family` defaults to
297/// `"sans-serif"` itself and `theme.geom.family` defaults to `None`, so
298/// with nothing configured anywhere this already returns
299/// `Some("sans-serif")` — the same string the backend would have defaulted
300/// to, so default output stays byte-identical.
301pub(crate) fn resolve_font_family(geom_family: &str, theme: &Theme) -> Option<String> {
302 if !geom_family.is_empty() {
303 Some(geom_family.to_string())
304 } else if let Some(family) = &theme.geom.family {
305 Some(family.clone())
306 } else if theme.text.family.is_empty() {
307 None
308 } else {
309 Some(theme.text.family.clone())
310 }
311}
312
313/// Clear all per-mark metadata after a geom has drawn its marks.
314pub(crate) fn clear_mark(backend: &mut dyn DrawBackend) {
315 set_mark(backend, None, None, None, None);
316 backend.set_mark_fvalue(None);
317 backend.set_mark_fx(None);
318}
319
320/// Set `data-fvalue`/`data-fx` (B2-4) for the mark `set_mark` just
321/// configured, formatted through the relevant scale — `value_aes`'s (Y for
322/// most geoms, Fill for hex/tile) for `data-fvalue`, X for `data-fx`.
323/// Always sets both (even to `None`), so a row without a formattable value
324/// doesn't inherit an earlier row's — the same per-row reset discipline as
325/// [`set_row_extras`]. A no-op query (`wants_formatted_values`) short-
326/// circuits the scale lookups entirely when
327/// [`crate::plot::GGPlot::svg_formatted_values`] is off (the default), so
328/// this costs nothing and changes nothing when never turned on.
329pub(crate) fn set_mark_formatted(
330 backend: &mut dyn DrawBackend,
331 scales: &crate::scale::ScaleSet,
332 x_raw: Option<&crate::data::Value>,
333 value_aes: &Aesthetic,
334 value_raw: Option<&crate::data::Value>,
335) {
336 if !backend.wants_formatted_values() {
337 backend.set_mark_fvalue(None);
338 backend.set_mark_fx(None);
339 return;
340 }
341 let fvalue = value_raw
342 .filter(|v| !v.is_na())
343 .and_then(|v| scales.get(value_aes).and_then(|s| s.format_value(v)));
344 backend.set_mark_fvalue(fvalue);
345 let fx = x_raw
346 .filter(|v| !v.is_na())
347 .and_then(|v| scales.get(&Aesthetic::X).and_then(|s| s.format_value(v)));
348 backend.set_mark_fx(fx);
349}
350
351/// Apply one row's interactive aesthetics (B1-7: `Aes::tooltip`,
352/// `Aes::data_attr`) to the backend.
353///
354/// A validated `Aes::tooltip` mapping replaces the geom's own `<title>`
355/// (call the geom's own `set_mark(...)` *before* this, so a custom tooltip
356/// wins) for *every* row — including when this row's value is NA, which
357/// explicitly resets the tooltip to `None` (no `<title>` at all, even if
358/// the geom has its own default): once `Aes::tooltip` is mapped, it owns
359/// the tooltip for the whole layer, the same row-by-row way `color` or
360/// `size` would. It never inherits an earlier row's. It's read from
361/// [`crate::aes::TOOLTIP_INTERNAL_NAME`], not a plain `"tooltip"` column
362/// name, so an unrelated raw source column literally called `"tooltip"`
363/// can never drive every mark's hover title (the same class of bug fixed
364/// for `data_attr` below). `set_tooltip` is only called at all when that
365/// internal column exists, so layers that never map `Aes::tooltip` don't
366/// touch whatever the geom already set.
367///
368/// Every validated `data_attr` column becomes a `data-<name>` attribute.
369/// These are stored under [`crate::aes::DATA_ATTR_INTERNAL_PREFIX`] rather
370/// than scanned by a `"data-"` name prefix: a raw source column that merely
371/// happens to be named like a data attribute (e.g. a SQL alias) was never
372/// validated and must never reach `push_mark` (see
373/// `aes::validated_data_attr_internal_name`, and `aes::mapping`'s defensive
374/// drop of any raw column that could forge an internal name).
375/// `set_mark_attrs` is *always* called, even with an empty list, so a row
376/// with no attrs doesn't inherit an earlier row's.
377pub(crate) fn set_row_extras(backend: &mut dyn DrawBackend, data: &DataFrame, row: usize) {
378 if let Some(col) = data.column(crate::aes::TOOLTIP_INTERNAL_NAME) {
379 let tip = col.get(row).filter(|v| !v.is_na()).map(tip_value);
380 backend.set_tooltip(tip);
381 }
382 let mut attrs = Vec::new();
383 for name in data.column_names() {
384 if let Some(target) = name.strip_prefix(crate::aes::DATA_ATTR_INTERNAL_PREFIX) {
385 if let Some(v) = data.column(name).and_then(|c| c.get(row)) {
386 if !v.is_na() {
387 attrs.push((target.to_string(), tip_value(v)));
388 }
389 }
390 }
391 }
392 backend.set_mark_attrs(attrs);
393}
394
395/// Clear interactive-aesthetic attributes *and* the tooltip after a layer
396/// finishes drawing, so neither leaks into a later layer, an annotation, or
397/// the legend's own background/key marks (which share the same backend
398/// instance for the rest of the render).
399pub(crate) fn clear_row_extras(backend: &mut dyn DrawBackend) {
400 backend.set_tooltip(None);
401 backend.set_mark_attrs(Vec::new());
402}
403
404/// Draw one group's polyline (path/line), honouring a per-point `linewidth`.
405/// A constant width draws one polyline (byte-identical to the pre-linewidth
406/// behaviour); a varying width falls back to drawing segment-by-segment,
407/// since a single stroked polyline can't vary its width along its length.
408/// An optional arrowhead is drawn once per polyline, using the width at its
409/// last point (closest to where a default `ends(Last)` head sits).
410#[allow(clippy::too_many_arguments)]
411pub(crate) fn draw_polyline_with_linewidth(
412 backend: &mut dyn DrawBackend,
413 points: &[(f64, f64)],
414 widths: &[f64],
415 color: (u8, u8, u8),
416 alpha: f64,
417 linetype: crate::render::backend::Linetype,
418 lineend: crate::render::backend::LineEnd,
419 arrow: Option<&crate::geom::arrow::Arrow>,
420 fallback_width: f64,
421) -> Result<(), RenderError> {
422 if points.len() < 2 {
423 return Ok(());
424 }
425 let w0 = widths.first().copied().unwrap_or(fallback_width);
426 let varies = widths.len() == points.len() && widths.iter().any(|&w| (w - w0).abs() > 1e-9);
427 if varies {
428 for i in 0..points.len() - 1 {
429 backend.draw_line(
430 &points[i..=i + 1],
431 &crate::render::backend::LineStyle {
432 color,
433 alpha,
434 width: widths[i],
435 linetype,
436 lineend,
437 },
438 )?;
439 }
440 } else {
441 backend.draw_line(
442 points,
443 &crate::render::backend::LineStyle {
444 color,
445 alpha,
446 width: w0,
447 linetype,
448 lineend,
449 },
450 )?;
451 }
452 if let Some(arrow) = arrow {
453 let resolved_width = widths.last().copied().unwrap_or(fallback_width);
454 let hs = crate::geom::arrow::heads(points, arrow, resolved_width);
455 crate::geom::arrow::draw_heads(backend, &hs, arrow, color, alpha, resolved_width)?;
456 }
457 Ok(())
458}