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