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