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 set_series_color(&mut self, color: (u8, u8, u8)) {
214        self.color = color;
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use crate::data::Value;
221    use crate::geom::arrow::arrow;
222    use crate::prelude::*;
223
224    fn plot() -> GGPlot {
225        let n = 6;
226        let x: Vec<Value> = (0..n).map(|i| Value::Float(i as f64)).collect();
227        let y: Vec<Value> = (0..n)
228            .map(|i| Value::Float((i as f64 * 0.37).sin()))
229            .collect();
230        GGPlot::new(vec![("x".into(), x), ("y".into(), y)]).aes(Aes::new().x("x").y("y"))
231    }
232
233    /// Byte-identical default output: an exact polyline string recorded
234    /// before adding `arrow`/`lineend` to `GeomPath`.
235    #[test]
236    fn default_path_output_is_unchanged() {
237        let svg = plot()
238            .geom_path_with(GeomPath::default())
239            .render_svg_native_with_size(100, 60)
240            .unwrap();
241        let points = svg
242            .split("<polyline")
243            .filter_map(|p| p.split("points=\"").nth(1))
244            .filter_map(|p| p.split('"').next())
245            .find(|p| p.split(' ').count() == 6)
246            .expect("the 6-point data polyline");
247        assert_eq!(
248            points,
249            "64.32,53.23 73.41,36.72 82.50,22.45 91.60,12.35 100.69,7.77 109.78,9.35"
250        );
251        assert!(!svg.contains("stroke-linecap"));
252        assert!(!svg.contains("data-part"));
253    }
254
255    #[test]
256    fn path_with_arrow_tags_one_head_for_the_single_polyline() {
257        let svg = plot()
258            .geom_path_with(GeomPath::default().arrow(arrow().closed()))
259            .render_svg_native_with_size(100, 60)
260            .unwrap();
261        assert_eq!(svg.matches("data-part=\"arrow\"").count(), 1);
262    }
263
264    /// `.color()`/`.alpha()`/`.linewidth()` builders actually change the
265    /// rendered stroke (the ungrouped — no `color` aesthetic mapped — path).
266    #[test]
267    fn color_alpha_and_linewidth_builders_change_the_rendered_stroke() {
268        let svg = plot()
269            .geom_path_with(
270                GeomPath::default()
271                    .color((10, 20, 30))
272                    .alpha(0.4)
273                    .linewidth(5.0),
274            )
275            .render_svg_native_with_size(100, 60)
276            .unwrap();
277        assert!(svg.contains("stroke=\"#0A141E\""));
278        assert!(svg.contains("stroke-opacity=\"0.400\""));
279        assert!(svg.contains("stroke-width=\"5.00\""));
280    }
281
282    /// The grouped branch (a `color` aesthetic mapped): one polyline per
283    /// group, each with its own mapped colour.
284    #[test]
285    fn grouped_path_draws_one_polyline_per_colour_group() {
286        let svg = GGPlot::new(vec![
287            (
288                "x".into(),
289                vec![
290                    Value::Float(0.0),
291                    Value::Float(1.0),
292                    Value::Float(0.0),
293                    Value::Float(1.0),
294                ],
295            ),
296            (
297                "y".into(),
298                vec![
299                    Value::Float(0.0),
300                    Value::Float(1.0),
301                    Value::Float(1.0),
302                    Value::Float(0.0),
303                ],
304            ),
305            (
306                "g".into(),
307                vec![
308                    Value::Str("a".into()),
309                    Value::Str("a".into()),
310                    Value::Str("b".into()),
311                    Value::Str("b".into()),
312                ],
313            ),
314        ])
315        .aes(Aes::new().x("x").y("y").color("g"))
316        .geom_path_with(GeomPath::default().lineend(crate::render::backend::LineEnd::Round))
317        .render_svg_native_with_size(100, 100)
318        .unwrap();
319
320        // Two groups ("a", "b") -> two data polylines, each with the
321        // round linecap (only our data uses it; gridlines stay Butt, which
322        // omits the attribute entirely).
323        assert_eq!(svg.matches("stroke-linecap=\"round\"").count(), 2);
324    }
325}