Skip to main content

ggplot_rs/geom/
line.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::geom::arrow::Arrow;
5use crate::position::identity::PositionIdentity;
6use crate::position::Position;
7use crate::render::backend::{DrawBackend, LineEnd, Linetype};
8use crate::render::RenderError;
9use crate::scale::ScaleSet;
10use crate::stat::identity::StatIdentity;
11use crate::stat::Stat;
12use crate::theme::Theme;
13
14use super::{draw_polyline_with_linewidth, Geom, GeomParams};
15
16/// Line geometry — connects points sorted by x.
17pub struct GeomLine {
18    pub color: (u8, u8, u8),
19    pub width: f64,
20    pub alpha: f64,
21    /// An optional arrowhead drawn at the end(s) of each drawn polyline
22    /// (one head set per group).
23    pub arrow: Option<Arrow>,
24    /// Line cap style (R grid's `lineend`).
25    pub lineend: LineEnd,
26    /// How consecutive points are joined (straight by default; a smooth
27    /// spline through the points with
28    /// [`Interpolate::MonotoneCubic`](super::support::Interpolate::MonotoneCubic)).
29    pub interpolate: super::support::Interpolate,
30}
31
32impl Default for GeomLine {
33    fn default() -> Self {
34        GeomLine {
35            color: (0, 0, 0),
36            width: 1.5,
37            alpha: 1.0,
38            arrow: None,
39            lineend: LineEnd::Butt,
40            interpolate: super::support::Interpolate::Linear,
41        }
42    }
43}
44
45impl GeomLine {
46    /// Fixed stroke colour, used when no `color` aesthetic is mapped.
47    pub fn color(mut self, color: (u8, u8, u8)) -> Self {
48        self.color = color;
49        self
50    }
51
52    /// Sets `width` (the stroke width in pixels).
53    pub fn linewidth(mut self, width: f64) -> Self {
54        self.width = width;
55        self
56    }
57
58    /// Fixed opacity, used when no `alpha` aesthetic is mapped.
59    pub fn alpha(mut self, alpha: f64) -> Self {
60        self.alpha = alpha;
61        self
62    }
63
64    /// Draw an arrowhead at the end(s) — see [`arrow()`](crate::geom::arrow::arrow).
65    pub fn arrow(mut self, arrow: Arrow) -> Self {
66        self.arrow = Some(arrow);
67        self
68    }
69
70    /// Line cap style (R grid's `lineend`).
71    pub fn lineend(mut self, lineend: LineEnd) -> Self {
72        self.lineend = lineend;
73        self
74    }
75}
76
77impl Geom for GeomLine {
78    fn draw(
79        &self,
80        data: &DataFrame,
81        coord: &dyn Coord,
82        scales: &ScaleSet,
83        _theme: &Theme,
84        backend: &mut dyn DrawBackend,
85    ) -> Result<(), RenderError> {
86        let x_col = data
87            .column("x")
88            .ok_or(RenderError::MissingAesthetic("x".into()))?;
89        let y_col = data
90            .column("y")
91            .ok_or(RenderError::MissingAesthetic("y".into()))?;
92        let color_col = data.column("color");
93        let linetype_col = data.column("linetype");
94        let linewidth_col = data.column("linewidth");
95
96        let plot_area = backend.plot_area();
97        let x_scale = scales.get(&Aesthetic::X);
98        let y_scale = scales.get(&Aesthetic::Y);
99
100        // One polyline per group/colour/linetype level — a mapped
101        // `linetype` alone splits the rows too, as in ggplot2 (#220).
102        // a mapped `group` alone splits them too, as in ggplot2 (#507)
103        if color_col.is_some() || linetype_col.is_some() || data.column("group").is_some() {
104            let groups = super::support::row_groups(data);
105            for indices in &groups {
106                let first_idx = indices[0];
107                let line_color = color_col
108                    .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[first_idx]))
109                    .unwrap_or(self.color);
110                // Tag each line with its series (for hover + linked highlighting).
111                let series = color_col
112                    .or(linetype_col)
113                    .map(|c| super::tip_value(&c[first_idx]));
114                super::set_mark(backend, series.clone(), None, series, None);
115                super::set_mark_formatted(backend, scales, None, &Aesthetic::Y, None);
116                super::set_row_extras(backend, data, first_idx);
117
118                let lt = linetype_col
119                    .and_then(|lc| scales.map_linetype(&lc[first_idx]))
120                    .unwrap_or(Linetype::Solid);
121
122                // Sort indices by x value
123                let mut sorted = indices.clone();
124                sorted.sort_by(|&a, &b| {
125                    let xa = x_scale.map(|s| s.map(&x_col[a])).unwrap_or(0.0);
126                    let xb = x_scale.map(|s| s.map(&x_col[b])).unwrap_or(0.0);
127                    xa.total_cmp(&xb)
128                });
129
130                let raw: Vec<(f64, f64)> = sorted
131                    .iter()
132                    .map(|&i| {
133                        let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
134                        let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
135                        (nx, ny)
136                    })
137                    .collect();
138                let (raw, origin) = super::support::interpolate(&raw, self.interpolate);
139                let mut points: Vec<(f64, f64)> = raw
140                    .into_iter()
141                    .map(|p| coord.transform(p, &plot_area))
142                    .collect();
143                let mut widths: Vec<f64> = origin
144                    .iter()
145                    .map(|&k| {
146                        linewidth_col
147                            .and_then(|lc| scales.map_linewidth(&lc[sorted[k]]))
148                            .unwrap_or(self.width)
149                    })
150                    .collect();
151                close_for_radar(coord, &mut points);
152                if points.len() > widths.len() {
153                    widths.push(widths[0]);
154                }
155
156                draw_polyline_with_linewidth(
157                    backend,
158                    &points,
159                    &widths,
160                    line_color,
161                    self.alpha,
162                    lt,
163                    self.lineend,
164                    self.arrow.as_ref(),
165                    self.width,
166                )?;
167            }
168            super::clear_mark(backend);
169            super::clear_row_extras(backend);
170        } else {
171            let lt = linetype_col
172                .and_then(|lc| {
173                    if lc.is_empty() {
174                        None
175                    } else {
176                        scales.map_linetype(&lc[0])
177                    }
178                })
179                .unwrap_or(Linetype::Solid);
180
181            // Sort by x value
182            let mut sorted_indices: Vec<usize> = (0..data.nrows()).collect();
183            sorted_indices.sort_by(|&a, &b| {
184                let xa = x_scale.map(|s| s.map(&x_col[a])).unwrap_or(0.0);
185                let xb = x_scale.map(|s| s.map(&x_col[b])).unwrap_or(0.0);
186                xa.total_cmp(&xb)
187            });
188
189            let raw: Vec<(f64, f64)> = sorted_indices
190                .iter()
191                .map(|&i| {
192                    let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
193                    let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
194                    (nx, ny)
195                })
196                .collect();
197            let (raw, origin) = super::support::interpolate(&raw, self.interpolate);
198            let mut points: Vec<(f64, f64)> = raw
199                .into_iter()
200                .map(|p| coord.transform(p, &plot_area))
201                .collect();
202            let mut widths: Vec<f64> = origin
203                .iter()
204                .map(|&k| {
205                    linewidth_col
206                        .and_then(|lc| scales.map_linewidth(&lc[sorted_indices[k]]))
207                        .unwrap_or(self.width)
208                })
209                .collect();
210            close_for_radar(coord, &mut points);
211            if points.len() > widths.len() {
212                widths.push(widths[0]);
213            }
214
215            if data.nrows() > 0 {
216                super::set_row_extras(backend, data, 0);
217            }
218            draw_polyline_with_linewidth(
219                backend,
220                &points,
221                &widths,
222                self.color,
223                self.alpha,
224                lt,
225                self.lineend,
226                self.arrow.as_ref(),
227                self.width,
228            )?;
229            super::clear_row_extras(backend);
230        }
231
232        Ok(())
233    }
234
235    fn required_aes(&self) -> Vec<Aesthetic> {
236        vec![Aesthetic::X, Aesthetic::Y]
237    }
238
239    fn default_stat(&self) -> Box<dyn Stat> {
240        Box::new(StatIdentity)
241    }
242
243    fn default_position(&self) -> Box<dyn Position> {
244        Box::new(PositionIdentity)
245    }
246
247    fn default_params(&self) -> GeomParams {
248        GeomParams::default()
249    }
250
251    fn name(&self) -> &str {
252        "line"
253    }
254
255    fn consumes_tooltips(&self) -> bool {
256        true
257    }
258
259    fn keeps_na_as_break(&self) -> bool {
260        true
261    }
262
263    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
264        if let (true, Some(ink)) = (self.color == (0, 0, 0), el.ink) {
265            self.color = ink;
266        }
267        // #413: `element_geom(linewidth =)` for the built-in default only.
268        if let (true, Some(w)) = (self.width == GeomLine::default().width, el.linewidth) {
269            self.width = w;
270        }
271    }
272
273    fn set_series_color(&mut self, color: (u8, u8, u8)) {
274        self.color = color;
275    }
276}
277
278/// Under `coord_radar` a series is a closed loop around the spokes.
279fn close_for_radar(coord: &dyn Coord, points: &mut Vec<(f64, f64)>) {
280    if coord.is_radar() && points.len() >= 3 {
281        let first = points[0];
282        points.push(first);
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use crate::data::Value;
289    use crate::geom::arrow::arrow;
290    use crate::prelude::*;
291
292    fn plot() -> GGPlot {
293        let n = 6;
294        let x: Vec<Value> = (0..n).map(|i| Value::Float(i as f64)).collect();
295        let y: Vec<Value> = (0..n)
296            .map(|i| Value::Float((i as f64 * 0.37).sin()))
297            .collect();
298        GGPlot::new(vec![("x".into(), x), ("y".into(), y)]).aes(Aes::new().x("x").y("y"))
299    }
300
301    #[test]
302    fn default_line_output_has_no_linecap_or_arrow_marks() {
303        let svg = plot()
304            .geom_line_with(GeomLine::default())
305            .render_svg_native_with_size(100, 60)
306            .unwrap();
307        assert!(!svg.contains("stroke-linecap"));
308        assert!(!svg.contains("data-part"));
309    }
310
311    #[test]
312    fn line_with_arrow_tags_one_head_for_the_single_polyline() {
313        let svg = plot()
314            .geom_line_with(GeomLine::default().arrow(arrow().closed()))
315            .render_svg_native_with_size(100, 60)
316            .unwrap();
317        assert_eq!(svg.matches("data-part=\"arrow\"").count(), 1);
318    }
319
320    #[test]
321    fn lineend_round_gives_stroke_linecap_round() {
322        let svg = plot()
323            .geom_line_with(GeomLine::default().lineend(crate::render::backend::LineEnd::Round))
324            .render_svg_native_with_size(100, 60)
325            .unwrap();
326        assert!(svg.contains("stroke-linecap=\"round\""));
327    }
328
329    /// `.color()`/`.alpha()`/`.linewidth()` builders actually change the
330    /// rendered stroke (the ungrouped — no `color` aesthetic mapped — line).
331    #[test]
332    fn color_alpha_and_linewidth_builders_change_the_rendered_stroke() {
333        let svg = plot()
334            .geom_line_with(
335                GeomLine::default()
336                    .color((10, 20, 30))
337                    .alpha(0.4)
338                    .linewidth(5.0),
339            )
340            .render_svg_native_with_size(100, 60)
341            .unwrap();
342        assert!(svg.contains("stroke=\"#0A141E\""));
343        assert!(svg.contains("stroke-opacity=\"0.400\""));
344        assert!(svg.contains("stroke-width=\"5.00\""));
345    }
346
347    /// The grouped branch (a `color` aesthetic mapped): one polyline per
348    /// group, each tagged with its series for hover grouping.
349    #[test]
350    fn grouped_line_draws_one_polyline_per_colour_group_with_series_tags() {
351        let svg = GGPlot::new(vec![
352            (
353                "x".into(),
354                vec![
355                    Value::Float(0.0),
356                    Value::Float(1.0),
357                    Value::Float(0.0),
358                    Value::Float(1.0),
359                ],
360            ),
361            (
362                "y".into(),
363                vec![
364                    Value::Float(0.0),
365                    Value::Float(1.0),
366                    Value::Float(1.0),
367                    Value::Float(0.0),
368                ],
369            ),
370            (
371                "g".into(),
372                vec![
373                    Value::Str("a".into()),
374                    Value::Str("a".into()),
375                    Value::Str("b".into()),
376                    Value::Str("b".into()),
377                ],
378            ),
379        ])
380        .aes(Aes::new().x("x").y("y").color("g"))
381        .geom_line_with(GeomLine::default().lineend(crate::render::backend::LineEnd::Round))
382        .render_svg_native_with_size(100, 100)
383        .unwrap();
384
385        assert_eq!(svg.matches("stroke-linecap=\"round\"").count(), 2);
386        assert!(svg.contains("data-series=\"a\""));
387        assert!(svg.contains("data-series=\"b\""));
388    }
389
390    /// `draw_polyline_with_linewidth` (B1-4): when the mapped `linewidth`
391    /// varies within a group, a single stroked polyline can't represent
392    /// that — it falls back to drawing segment-by-segment, one
393    /// `<polyline>` per consecutive point pair, each at its own width.
394    #[test]
395    fn varying_linewidth_within_a_group_draws_segment_by_segment() {
396        let svg = GGPlot::new(vec![
397            (
398                "x".into(),
399                vec![Value::Float(0.0), Value::Float(1.0), Value::Float(2.0)],
400            ),
401            (
402                "y".into(),
403                vec![Value::Float(0.0), Value::Float(1.0), Value::Float(0.0)],
404            ),
405            (
406                "w".into(),
407                vec![Value::Float(1.0), Value::Float(5.0), Value::Float(9.0)],
408            ),
409        ])
410        .aes(Aes::new().x("x").y("y").linewidth("w"))
411        .geom_line()
412        .scale_linewidth(ScaleLinewidthContinuous::new().with_range(2.0, 9.0))
413        .render_svg_native_with_size(100, 100)
414        .unwrap();
415
416        // 3 points -> 2 segments, each its own 2-point polyline at the
417        // width mapped for its *starting* point (1.0 -> width 1, 5.0 ->
418        // width 5) — not one 3-point polyline at a single width.
419        assert_eq!(svg.matches("stroke-width=\"2.00\"").count(), 1);
420        assert_eq!(svg.matches("stroke-width=\"5.50\"").count(), 1);
421        // The last point's mapped width (9) is never used as a stroke
422        // width here — there's no arrow to resolve it for.
423        assert!(!svg.contains("stroke-width=\"9.00\""));
424    }
425}