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