Skip to main content

ggplot_rs/geom/
line.rs

1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::position::identity::PositionIdentity;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, LineStyle, Linetype};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::identity::StatIdentity;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Line geometry — connects points sorted by x.
16pub struct GeomLine {
17    pub color: (u8, u8, u8),
18    pub width: f64,
19    pub alpha: f64,
20}
21
22impl Default for GeomLine {
23    fn default() -> Self {
24        GeomLine {
25            color: (0, 0, 0),
26            width: 1.5,
27            alpha: 1.0,
28        }
29    }
30}
31
32impl Geom for GeomLine {
33    fn draw(
34        &self,
35        data: &DataFrame,
36        coord: &dyn Coord,
37        scales: &ScaleSet,
38        _theme: &Theme,
39        backend: &mut dyn DrawBackend,
40    ) -> Result<(), RenderError> {
41        let x_col = data
42            .column("x")
43            .ok_or(RenderError::MissingAesthetic("x".into()))?;
44        let y_col = data
45            .column("y")
46            .ok_or(RenderError::MissingAesthetic("y".into()))?;
47        let color_col = data.column("color");
48        let linetype_col = data.column("linetype");
49
50        let plot_area = backend.plot_area();
51        let x_scale = scales.get(&Aesthetic::X);
52        let y_scale = scales.get(&Aesthetic::Y);
53
54        // If there's a color/group aesthetic, draw separate lines per group
55        if let Some(cc) = color_col {
56            let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
57            for (i, v) in cc.iter().enumerate() {
58                let key = v.to_group_key();
59                if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
60                    entry.1.push(i);
61                } else {
62                    groups.push((key, vec![i]));
63                }
64            }
65
66            for (_, indices) in &groups {
67                let first_idx = indices[0];
68                let line_color = scales
69                    .map_color(&Aesthetic::Color, &cc[first_idx])
70                    .unwrap_or(self.color);
71                // Tag each line with its series (for hover + linked highlighting).
72                let series = Some(super::tip_value(&cc[first_idx]));
73                super::set_mark(backend, series.clone(), None, series, None);
74
75                let lt = linetype_col
76                    .and_then(|lc| scales.map_linetype(&lc[first_idx]))
77                    .unwrap_or(Linetype::Solid);
78
79                // Sort indices by x value
80                let mut sorted = indices.clone();
81                sorted.sort_by(|&a, &b| {
82                    let xa = x_scale.map(|s| s.map(&x_col[a])).unwrap_or(0.0);
83                    let xb = x_scale.map(|s| s.map(&x_col[b])).unwrap_or(0.0);
84                    xa.total_cmp(&xb)
85                });
86
87                let mut points: Vec<(f64, f64)> = sorted
88                    .iter()
89                    .map(|&i| {
90                        let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
91                        let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
92                        coord.transform((nx, ny), &plot_area)
93                    })
94                    .collect();
95                close_for_radar(coord, &mut points);
96
97                if points.len() >= 2 {
98                    backend.draw_line(
99                        &points,
100                        &LineStyle {
101                            color: line_color,
102                            alpha: self.alpha,
103                            width: self.width,
104                            linetype: lt,
105                        },
106                    )?;
107                }
108            }
109            super::clear_mark(backend);
110        } else {
111            let lt = linetype_col
112                .and_then(|lc| {
113                    if lc.is_empty() {
114                        None
115                    } else {
116                        scales.map_linetype(&lc[0])
117                    }
118                })
119                .unwrap_or(Linetype::Solid);
120
121            // Sort by x value
122            let mut sorted_indices: Vec<usize> = (0..data.nrows()).collect();
123            sorted_indices.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_indices
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            close_for_radar(coord, &mut points);
138
139            if points.len() >= 2 {
140                backend.draw_line(
141                    &points,
142                    &LineStyle {
143                        color: self.color,
144                        alpha: self.alpha,
145                        width: self.width,
146                        linetype: lt,
147                    },
148                )?;
149            }
150        }
151
152        Ok(())
153    }
154
155    fn required_aes(&self) -> Vec<Aesthetic> {
156        vec![Aesthetic::X, Aesthetic::Y]
157    }
158
159    fn default_stat(&self) -> Box<dyn Stat> {
160        Box::new(StatIdentity)
161    }
162
163    fn default_position(&self) -> Box<dyn Position> {
164        Box::new(PositionIdentity)
165    }
166
167    fn default_params(&self) -> GeomParams {
168        GeomParams::default()
169    }
170
171    fn name(&self) -> &str {
172        "line"
173    }
174
175    fn set_series_color(&mut self, color: (u8, u8, u8)) {
176        self.color = color;
177    }
178}
179
180/// Under `coord_radar` a series is a closed loop around the spokes.
181fn close_for_radar(coord: &dyn Coord, points: &mut Vec<(f64, f64)>) {
182    if coord.is_radar() && points.len() >= 3 {
183        let first = points[0];
184        points.push(first);
185    }
186}