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