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