Skip to main content

ggplot_rs/geom/
path.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/// Path geometry — connects points in row order (no x-sort).
17pub struct GeomPath {
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 GeomPath {
29    fn default() -> Self {
30        GeomPath {
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 GeomPath {
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 GeomPath {
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        // One polyline per group/colour/linetype level — a mapped
96        // `linetype` alone splits the rows too, as in ggplot2 (#220).
97        if color_col.is_some() || linetype_col.is_some() {
98            let groups = super::support::row_groups(data);
99            for indices in &groups {
100                let first_idx = indices[0];
101                let line_color = color_col
102                    .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[first_idx]))
103                    .unwrap_or(self.color);
104
105                let lt = linetype_col
106                    .and_then(|lc| scales.map_linetype(&lc[first_idx]))
107                    .unwrap_or(Linetype::Solid);
108
109                let points: Vec<(f64, f64)> = indices
110                    .iter()
111                    .map(|&i| {
112                        let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
113                        let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
114                        coord.transform((nx, ny), &plot_area)
115                    })
116                    .collect();
117                let widths: Vec<f64> = indices
118                    .iter()
119                    .map(|&i| {
120                        linewidth_col
121                            .and_then(|lc| scales.map_linewidth(&lc[i]))
122                            .unwrap_or(self.width)
123                    })
124                    .collect();
125
126                super::set_row_extras(backend, data, first_idx);
127                draw_polyline_with_linewidth(
128                    backend,
129                    &points,
130                    &widths,
131                    line_color,
132                    self.alpha,
133                    lt,
134                    self.lineend,
135                    self.arrow.as_ref(),
136                    self.width,
137                )?;
138            }
139        } else {
140            let lt = linetype_col
141                .and_then(|lc| {
142                    if lc.is_empty() {
143                        None
144                    } else {
145                        scales.map_linetype(&lc[0])
146                    }
147                })
148                .unwrap_or(Linetype::Solid);
149
150            let points: Vec<(f64, f64)> = (0..data.nrows())
151                .map(|i| {
152                    let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
153                    let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
154                    coord.transform((nx, ny), &plot_area)
155                })
156                .collect();
157            let widths: Vec<f64> = (0..data.nrows())
158                .map(|i| {
159                    linewidth_col
160                        .and_then(|lc| scales.map_linewidth(&lc[i]))
161                        .unwrap_or(self.width)
162                })
163                .collect();
164
165            if data.nrows() > 0 {
166                super::set_row_extras(backend, data, 0);
167            }
168            draw_polyline_with_linewidth(
169                backend,
170                &points,
171                &widths,
172                self.color,
173                self.alpha,
174                lt,
175                self.lineend,
176                self.arrow.as_ref(),
177                self.width,
178            )?;
179        }
180        super::clear_mark(backend);
181        super::clear_row_extras(backend);
182
183        Ok(())
184    }
185
186    fn required_aes(&self) -> Vec<Aesthetic> {
187        vec![Aesthetic::X, Aesthetic::Y]
188    }
189
190    fn default_stat(&self) -> Box<dyn Stat> {
191        Box::new(StatIdentity)
192    }
193
194    fn default_position(&self) -> Box<dyn Position> {
195        Box::new(PositionIdentity)
196    }
197
198    fn default_params(&self) -> GeomParams {
199        GeomParams::default()
200    }
201
202    fn name(&self) -> &str {
203        "path"
204    }
205
206    fn consumes_tooltips(&self) -> bool {
207        true
208    }
209
210    fn keeps_na_as_break(&self) -> bool {
211        true
212    }
213
214    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
215        if let (true, Some(ink)) = (self.color == (0, 0, 0), el.ink) {
216            self.color = ink;
217        }
218    }
219
220    fn set_series_color(&mut self, color: (u8, u8, u8)) {
221        self.color = color;
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use crate::data::Value;
228    use crate::geom::arrow::arrow;
229    use crate::prelude::*;
230
231    fn plot() -> GGPlot {
232        let n = 6;
233        let x: Vec<Value> = (0..n).map(|i| Value::Float(i as f64)).collect();
234        let y: Vec<Value> = (0..n)
235            .map(|i| Value::Float((i as f64 * 0.37).sin()))
236            .collect();
237        GGPlot::new(vec![("x".into(), x), ("y".into(), y)]).aes(Aes::new().x("x").y("y"))
238    }
239
240    /// Byte-identical default output: an exact polyline string recorded
241    /// before adding `arrow`/`lineend` to `GeomPath`.
242    #[test]
243    fn default_path_output_is_unchanged() {
244        let svg = plot()
245            .geom_path_with(GeomPath::default())
246            .render_svg_native_with_size(100, 60)
247            .unwrap();
248        let points = svg
249            .split("<polyline")
250            .filter_map(|p| p.split("points=\"").nth(1))
251            .filter_map(|p| p.split('"').next())
252            .find(|p| p.split(' ').count() == 6)
253            .expect("the 6-point data polyline");
254        assert_eq!(
255            points,
256            "64.32,53.23 73.41,36.72 82.50,22.45 91.60,12.35 100.69,7.77 109.78,9.35"
257        );
258        assert!(!svg.contains("stroke-linecap"));
259        assert!(!svg.contains("data-part"));
260    }
261
262    #[test]
263    fn path_with_arrow_tags_one_head_for_the_single_polyline() {
264        let svg = plot()
265            .geom_path_with(GeomPath::default().arrow(arrow().closed()))
266            .render_svg_native_with_size(100, 60)
267            .unwrap();
268        assert_eq!(svg.matches("data-part=\"arrow\"").count(), 1);
269    }
270
271    /// `.color()`/`.alpha()`/`.linewidth()` builders actually change the
272    /// rendered stroke (the ungrouped — no `color` aesthetic mapped — path).
273    #[test]
274    fn color_alpha_and_linewidth_builders_change_the_rendered_stroke() {
275        let svg = plot()
276            .geom_path_with(
277                GeomPath::default()
278                    .color((10, 20, 30))
279                    .alpha(0.4)
280                    .linewidth(5.0),
281            )
282            .render_svg_native_with_size(100, 60)
283            .unwrap();
284        assert!(svg.contains("stroke=\"#0A141E\""));
285        assert!(svg.contains("stroke-opacity=\"0.400\""));
286        assert!(svg.contains("stroke-width=\"5.00\""));
287    }
288
289    /// The grouped branch (a `color` aesthetic mapped): one polyline per
290    /// group, each with its own mapped colour.
291    #[test]
292    fn grouped_path_draws_one_polyline_per_colour_group() {
293        let svg = GGPlot::new(vec![
294            (
295                "x".into(),
296                vec![
297                    Value::Float(0.0),
298                    Value::Float(1.0),
299                    Value::Float(0.0),
300                    Value::Float(1.0),
301                ],
302            ),
303            (
304                "y".into(),
305                vec![
306                    Value::Float(0.0),
307                    Value::Float(1.0),
308                    Value::Float(1.0),
309                    Value::Float(0.0),
310                ],
311            ),
312            (
313                "g".into(),
314                vec![
315                    Value::Str("a".into()),
316                    Value::Str("a".into()),
317                    Value::Str("b".into()),
318                    Value::Str("b".into()),
319                ],
320            ),
321        ])
322        .aes(Aes::new().x("x").y("y").color("g"))
323        .geom_path_with(GeomPath::default().lineend(crate::render::backend::LineEnd::Round))
324        .render_svg_native_with_size(100, 100)
325        .unwrap();
326
327        // Two groups ("a", "b") -> two data polylines, each with the
328        // round linecap (only our data uses it; gridlines stay Butt, which
329        // omits the attribute entirely).
330        assert_eq!(svg.matches("stroke-linecap=\"round\"").count(), 2);
331    }
332}