Skip to main content

ggplot_rs/geom/
refline.rs

1//! Reference lines: `geom_hline`, `geom_vline`, `geom_abline`.
2//!
3//! Each geom draws one line per row of its layer data when the matching
4//! aesthetic column is present (`yintercept`, `xintercept`, or
5//! `slope`/`intercept` — ggplot2's data-mapped form, which also honours
6//! per-row `color` / `linetype` / `alpha` and facet panels), and otherwise
7//! falls back to the constant stored in the geom. As in ggplot2:
8//!
9//! - `xintercept` / `yintercept` train the x / y position scale (the line is
10//!   always inside the panel); `slope` / `intercept` train nothing;
11//! - reference lines do not inherit the plot-level mapping (`inherit.aes =
12//!   FALSE`);
13//! - `geom_abline` lives in data space (in the scales' transformed space for
14//!   e.g. `scale_x_log10`), clipped to the panel.
15
16use crate::aes::Aesthetic;
17use crate::coord::Coord;
18use crate::data::{DataFrame, Value};
19use crate::position::identity::PositionIdentity;
20use crate::position::Position;
21use crate::render::backend::{DrawBackend, LineStyle, Linetype};
22use crate::render::RenderError;
23use crate::scale::ScaleSet;
24use crate::stat::identity::StatIdentity;
25use crate::stat::Stat;
26use crate::theme::Theme;
27
28use super::support::{clip_polyline_unit, map_position};
29use super::{Geom, GeomParams};
30
31/// Per-row line style: mapped `color`/`linetype`/`alpha`, else the defaults.
32fn row_style(
33    data: &DataFrame,
34    i: usize,
35    scales: &ScaleSet,
36    color: (u8, u8, u8),
37    width: f64,
38    linetype: Linetype,
39    alpha: f64,
40) -> LineStyle {
41    let color = data
42        .column("color")
43        .and_then(|c| c.get(i))
44        .and_then(|v| scales.map_color(&Aesthetic::Color, v))
45        .unwrap_or(color);
46    let linetype = data
47        .column("linetype")
48        .and_then(|c| c.get(i))
49        .and_then(|v| scales.map_linetype(v))
50        .unwrap_or(linetype);
51    let alpha = data
52        .column("alpha")
53        .and_then(|c| c.get(i))
54        .and_then(|v| scales.map_alpha(v).or_else(|| v.as_f64()))
55        .filter(|a| a.is_finite())
56        .unwrap_or(alpha);
57    LineStyle {
58        color,
59        alpha,
60        width,
61        linetype,
62        ..Default::default()
63    }
64}
65
66/// Hover metadata for one reference line: `data-series` (the row's colour /
67/// group level) and `data-value` (the intercept), with a `"<series>: y = v"`
68/// tooltip.
69///
70/// B2-4: with `svg_formatted_values` on, the value is formatted through the
71/// matching position scale (`what == "x"` → the x scale, else y) instead of
72/// the plain numeric display — in the tooltip, and (for a vline, which is
73/// the only caller that passes an `axis`) in `data-x` itself: a raw
74/// epoch-seconds number is not materially useful even un-formatted, so this
75/// one replaces rather than just adding `data-fx` alongside it.
76fn mark_line(
77    backend: &mut dyn DrawBackend,
78    scales: &ScaleSet,
79    data: &DataFrame,
80    i: Option<usize>,
81    what: &str,
82    value: &Value,
83    axis: Option<String>,
84) {
85    let series = i.and_then(|i| super::series_key(data, i));
86    let raw = super::raw_value(value);
87    let aes = if what == "x" {
88        Aesthetic::X
89    } else {
90        Aesthetic::Y
91    };
92    let formatted = if backend.wants_formatted_values() {
93        scales.get(&aes).and_then(|s| s.format_value(value))
94    } else {
95        None
96    };
97    let shown = formatted.clone().unwrap_or_else(|| super::tip_value(value));
98    let tip = raw.as_ref().map(|_| match &series {
99        Some(s) => format!("{s}: {what} = {shown}"),
100        None => format!("{what} = {shown}"),
101    });
102    let axis = axis.map(|_| formatted.unwrap_or(shown));
103    super::set_mark(backend, tip, axis, series, raw);
104    super::set_mark_formatted(
105        backend,
106        scales,
107        (what == "x").then_some(value),
108        &Aesthetic::Y,
109        (what == "y").then_some(value),
110    );
111}
112
113/// The rows to draw: one per row of `col` (finite values only), or the
114/// constant when the column is absent.
115fn line_rows(data: &DataFrame, col: &str, constant: f64) -> Vec<(Option<usize>, Value)> {
116    match data.column(col) {
117        Some(c) => c
118            .iter()
119            .enumerate()
120            .filter(|(_, v)| v.as_f64().is_some_and(f64::is_finite))
121            .map(|(i, v)| (Some(i), v.clone()))
122            .collect(),
123        None if constant.is_finite() => vec![(None, Value::Float(constant))],
124        None => vec![],
125    }
126}
127
128/// Horizontal reference line spanning the panel width.
129pub struct GeomHline {
130    pub yintercept: f64,
131    pub color: (u8, u8, u8),
132    pub width: f64,
133    pub linetype: Linetype,
134    pub alpha: f64,
135}
136
137impl GeomHline {
138    pub fn new(yintercept: f64) -> Self {
139        GeomHline {
140            yintercept,
141            color: (0, 0, 0),
142            width: 1.0,
143            linetype: Linetype::Dashed,
144            alpha: 1.0,
145        }
146    }
147
148    /// A data-mapped hline: draws one line per row of the `yintercept`
149    /// aesthetic (see [`GGPlot::geom_hline_aes`](crate::plot::GGPlot::geom_hline_aes)).
150    pub fn mapped() -> Self {
151        Self::new(f64::NAN)
152    }
153}
154
155impl Geom for GeomHline {
156    fn draw(
157        &self,
158        data: &DataFrame,
159        coord: &dyn Coord,
160        scales: &ScaleSet,
161        _theme: &Theme,
162        backend: &mut dyn DrawBackend,
163    ) -> Result<(), RenderError> {
164        let plot_area = backend.plot_area();
165        let y_scale = scales.get(&Aesthetic::Y);
166        for (row, value) in line_rows(data, "yintercept", self.yintercept) {
167            let ny = map_position(y_scale, &value).unwrap_or(0.5);
168            if !ny.is_finite() {
169                continue;
170            }
171            let style = match row {
172                Some(i) => row_style(
173                    data,
174                    i,
175                    scales,
176                    self.color,
177                    self.width,
178                    self.linetype,
179                    self.alpha,
180                ),
181                None => LineStyle {
182                    color: self.color,
183                    alpha: self.alpha,
184                    width: self.width,
185                    linetype: self.linetype,
186                    ..Default::default()
187                },
188            };
189            mark_line(backend, scales, data, row, "y", &value, None);
190            let pts = sample_segment(coord, &plot_area, (0.0, ny), (1.0, ny));
191            backend.draw_line(&pts, &style)?;
192        }
193        super::clear_mark(backend);
194        Ok(())
195    }
196
197    fn required_aes(&self) -> Vec<Aesthetic> {
198        vec![]
199    }
200    fn default_stat(&self) -> Box<dyn Stat> {
201        Box::new(StatIdentity)
202    }
203    fn default_position(&self) -> Box<dyn Position> {
204        Box::new(PositionIdentity)
205    }
206    fn default_params(&self) -> GeomParams {
207        GeomParams::default()
208    }
209    fn name(&self) -> &str {
210        "hline"
211    }
212    fn inherit_aes(&self) -> bool {
213        false
214    }
215}
216
217/// Vertical reference line spanning the panel height.
218pub struct GeomVline {
219    pub xintercept: f64,
220    pub color: (u8, u8, u8),
221    pub width: f64,
222    pub linetype: Linetype,
223    pub alpha: f64,
224}
225
226impl GeomVline {
227    pub fn new(xintercept: f64) -> Self {
228        GeomVline {
229            xintercept,
230            color: (0, 0, 0),
231            width: 1.0,
232            linetype: Linetype::Dashed,
233            alpha: 1.0,
234        }
235    }
236
237    /// A data-mapped vline: one line per row of the `xintercept` aesthetic.
238    pub fn mapped() -> Self {
239        Self::new(f64::NAN)
240    }
241}
242
243impl Geom for GeomVline {
244    fn draw(
245        &self,
246        data: &DataFrame,
247        coord: &dyn Coord,
248        scales: &ScaleSet,
249        _theme: &Theme,
250        backend: &mut dyn DrawBackend,
251    ) -> Result<(), RenderError> {
252        let plot_area = backend.plot_area();
253        let x_scale = scales.get(&Aesthetic::X);
254        for (row, value) in line_rows(data, "xintercept", self.xintercept) {
255            let nx = map_position(x_scale, &value).unwrap_or(0.5);
256            if !nx.is_finite() {
257                continue;
258            }
259            let style = match row {
260                Some(i) => row_style(
261                    data,
262                    i,
263                    scales,
264                    self.color,
265                    self.width,
266                    self.linetype,
267                    self.alpha,
268                ),
269                None => LineStyle {
270                    color: self.color,
271                    alpha: self.alpha,
272                    width: self.width,
273                    linetype: self.linetype,
274                    ..Default::default()
275                },
276            };
277            let axis = Some(super::tip_value(&value));
278            mark_line(backend, scales, data, row, "x", &value, axis);
279            let pts = sample_segment(coord, &plot_area, (nx, 0.0), (nx, 1.0));
280            backend.draw_line(&pts, &style)?;
281        }
282        super::clear_mark(backend);
283        Ok(())
284    }
285
286    fn required_aes(&self) -> Vec<Aesthetic> {
287        vec![]
288    }
289    fn default_stat(&self) -> Box<dyn Stat> {
290        Box::new(StatIdentity)
291    }
292    fn default_position(&self) -> Box<dyn Position> {
293        Box::new(PositionIdentity)
294    }
295    fn default_params(&self) -> GeomParams {
296        GeomParams::default()
297    }
298    fn name(&self) -> &str {
299        "vline"
300    }
301    fn inherit_aes(&self) -> bool {
302        false
303    }
304}
305
306/// Line `y = intercept + slope · x` in data space, spanning the panel and
307/// clipped to it.
308pub struct GeomAbline {
309    pub slope: f64,
310    pub intercept: f64,
311    pub color: (u8, u8, u8),
312    pub width: f64,
313    pub linetype: Linetype,
314    pub alpha: f64,
315}
316
317impl GeomAbline {
318    pub fn new(slope: f64, intercept: f64) -> Self {
319        GeomAbline {
320            slope,
321            intercept,
322            color: (0, 0, 0),
323            width: 1.0,
324            linetype: Linetype::Dashed,
325            alpha: 1.0,
326        }
327    }
328
329    /// A data-mapped abline: one line per row of the `slope` / `intercept`
330    /// aesthetics (a missing one defaults to slope 1 / intercept 0).
331    pub fn mapped() -> Self {
332        Self::new(1.0, 0.0)
333    }
334}
335
336/// The data-space x range spanned by the panel (normalized 0 → 1).
337fn panel_x_range(scales: &ScaleSet) -> (f64, f64) {
338    match scales.get(&Aesthetic::X) {
339        Some(s) if s.is_discrete() => (0.5, s.breaks().len().max(1) as f64 + 0.5),
340        Some(s) => s.expanded_domain().unwrap_or((0.0, 1.0)),
341        None => (0.0, 1.0),
342    }
343}
344
345/// The normalized (panel) polyline of `y = a + b·x` across the panel,
346/// clipped to the unit square. Empty when the line misses the panel.
347pub(crate) fn abline_runs(scales: &ScaleSet, slope: f64, intercept: f64) -> Vec<Vec<(f64, f64)>> {
348    if !(slope.is_finite() && intercept.is_finite()) {
349        return vec![];
350    }
351    let (x0, x1) = panel_x_range(scales);
352    let y_scale = scales.get(&Aesthetic::Y);
353    let ny = |x: f64| {
354        let y = intercept + slope * x;
355        match y_scale {
356            Some(_) => map_position(y_scale, &Value::Float(y)).unwrap_or(f64::NAN),
357            None => y,
358        }
359    };
360    clip_polyline_unit(&[(0.0, ny(x0)), (1.0, ny(x1))])
361}
362
363/// Transform a normalized segment to pixels — densely sampled under polar /
364/// radar coordinates (where a straight data line is curved), else its two
365/// endpoints.
366fn sample_segment(
367    coord: &dyn Coord,
368    plot_area: &crate::render::Rect,
369    a: (f64, f64),
370    b: (f64, f64),
371) -> Vec<(f64, f64)> {
372    let n = if coord.is_polar() || coord.is_radar() {
373        64
374    } else {
375        1
376    };
377    (0..=n)
378        .map(|k| {
379            let t = k as f64 / n as f64;
380            coord.transform((a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)), plot_area)
381        })
382        .collect()
383}
384
385impl Geom for GeomAbline {
386    fn draw(
387        &self,
388        data: &DataFrame,
389        coord: &dyn Coord,
390        scales: &ScaleSet,
391        _theme: &Theme,
392        backend: &mut dyn DrawBackend,
393    ) -> Result<(), RenderError> {
394        let plot_area = backend.plot_area();
395        let slope_col = data.column("slope");
396        let icpt_col = data.column("intercept");
397        let rows: Vec<(Option<usize>, f64, f64)> = if slope_col.is_some() || icpt_col.is_some() {
398            (0..data.nrows())
399                .map(|i| {
400                    let get = |c: Option<&[Value]>, d: f64| {
401                        c.map_or(Some(d), |c| c.get(i).and_then(|v| v.as_f64()))
402                    };
403                    (i, get(slope_col, 1.0), get(icpt_col, 0.0))
404                })
405                .filter_map(|(i, s, a)| Some((Some(i), s?, a?)))
406                .collect()
407        } else {
408            vec![(None, self.slope, self.intercept)]
409        };
410        for (row, slope, intercept) in rows {
411            let style = match row {
412                Some(i) => row_style(
413                    data,
414                    i,
415                    scales,
416                    self.color,
417                    self.width,
418                    self.linetype,
419                    self.alpha,
420                ),
421                None => LineStyle {
422                    color: self.color,
423                    alpha: self.alpha,
424                    width: self.width,
425                    linetype: self.linetype,
426                    ..Default::default()
427                },
428            };
429            let series = row.and_then(|i| super::series_key(data, i));
430            let label = format!(
431                "y = {} + {}·x",
432                super::tip_value(&Value::Float(intercept)),
433                super::tip_value(&Value::Float(slope))
434            );
435            let tip = Some(match &series {
436                Some(s) => format!("{s}: {label}"),
437                None => label,
438            });
439            super::set_mark(
440                backend,
441                tip,
442                None,
443                series,
444                super::raw_value(&Value::Float(slope)),
445            );
446            // Slope/intercept aren't on either position scale — reset only.
447            super::set_mark_formatted(backend, scales, None, &Aesthetic::Y, None);
448            for run in abline_runs(scales, slope, intercept) {
449                let mut pts = Vec::new();
450                for w in run.windows(2) {
451                    let seg = sample_segment(coord, &plot_area, w[0], w[1]);
452                    if !pts.is_empty() {
453                        pts.pop();
454                    }
455                    pts.extend(seg);
456                }
457                backend.draw_line(&pts, &style)?;
458            }
459        }
460        super::clear_mark(backend);
461        Ok(())
462    }
463
464    fn required_aes(&self) -> Vec<Aesthetic> {
465        vec![]
466    }
467    fn default_stat(&self) -> Box<dyn Stat> {
468        Box::new(StatIdentity)
469    }
470    fn default_position(&self) -> Box<dyn Position> {
471        Box::new(PositionIdentity)
472    }
473    fn default_params(&self) -> GeomParams {
474        GeomParams::default()
475    }
476    fn name(&self) -> &str {
477        "abline"
478    }
479    fn inherit_aes(&self) -> bool {
480        false
481    }
482}
483
484#[cfg(test)]
485mod fixed_value_tests {
486    use crate::data::Value;
487    use crate::prelude::*;
488
489    /// A plain `geom_hline`/`geom_vline`/`geom_abline` with a fixed value
490    /// (no per-row data mapping) takes the "no row" branch of `row_style`'s
491    /// match — just the geom's own configured colour/width/linetype/alpha,
492    /// not a per-row override.
493    #[test]
494    fn fixed_value_reflines_render_without_a_data_mapping() {
495        let svg = GGPlot::new(vec![
496            ("x".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
497            ("y".into(), vec![Value::Float(0.0), Value::Float(1.0)]),
498        ])
499        .aes(Aes::new().x("x").y("y"))
500        .geom_point()
501        .geom_hline(0.5)
502        .geom_vline(0.5)
503        .geom_abline(1.0, 0.0)
504        .render_svg_native_with_size(200, 200)
505        .unwrap();
506
507        assert!(!svg.contains("NaN"));
508        // 3 reference lines + the data polyline-less point layer: at least
509        // 3 extra polylines beyond gridlines/axes exist.
510        assert!(svg.matches("<polyline").count() >= 3);
511    }
512}