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