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