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                backend.set_tooltip(Some(super::tip_value(&cc[first_idx])));
73
74                let lt = linetype_col
75                    .and_then(|lc| scales.map_linetype(&lc[first_idx]))
76                    .unwrap_or(Linetype::Solid);
77
78                // Sort indices by x value
79                let mut sorted = indices.clone();
80                sorted.sort_by(|&a, &b| {
81                    let xa = x_col[a].as_f64().unwrap_or(0.0);
82                    let xb = x_col[b].as_f64().unwrap_or(0.0);
83                    xa.partial_cmp(&xb).unwrap_or(std::cmp::Ordering::Equal)
84                });
85
86                let points: Vec<(f64, f64)> = sorted
87                    .iter()
88                    .map(|&i| {
89                        let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
90                        let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
91                        coord.transform((nx, ny), &plot_area)
92                    })
93                    .collect();
94
95                if points.len() >= 2 {
96                    backend.draw_line(
97                        &points,
98                        &LineStyle {
99                            color: line_color,
100                            alpha: self.alpha,
101                            width: self.width,
102                            linetype: lt,
103                        },
104                    )?;
105                }
106            }
107            backend.set_tooltip(None);
108        } else {
109            let lt = linetype_col
110                .and_then(|lc| {
111                    if lc.is_empty() {
112                        None
113                    } else {
114                        scales.map_linetype(&lc[0])
115                    }
116                })
117                .unwrap_or(Linetype::Solid);
118
119            // Sort by x value
120            let mut sorted_indices: Vec<usize> = (0..data.nrows()).collect();
121            sorted_indices.sort_by(|&a, &b| {
122                let xa = x_col[a].as_f64().unwrap_or(0.0);
123                let xb = x_col[b].as_f64().unwrap_or(0.0);
124                xa.partial_cmp(&xb).unwrap_or(std::cmp::Ordering::Equal)
125            });
126
127            let points: Vec<(f64, f64)> = sorted_indices
128                .iter()
129                .map(|&i| {
130                    let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
131                    let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
132                    coord.transform((nx, ny), &plot_area)
133                })
134                .collect();
135
136            if points.len() >= 2 {
137                backend.draw_line(
138                    &points,
139                    &LineStyle {
140                        color: self.color,
141                        alpha: self.alpha,
142                        width: self.width,
143                        linetype: lt,
144                    },
145                )?;
146            }
147        }
148
149        Ok(())
150    }
151
152    fn required_aes(&self) -> Vec<Aesthetic> {
153        vec![Aesthetic::X, Aesthetic::Y]
154    }
155
156    fn default_stat(&self) -> Box<dyn Stat> {
157        Box::new(StatIdentity)
158    }
159
160    fn default_position(&self) -> Box<dyn Position> {
161        Box::new(PositionIdentity)
162    }
163
164    fn default_params(&self) -> GeomParams {
165        GeomParams::default()
166    }
167
168    fn name(&self) -> &str {
169        "line"
170    }
171
172    fn set_series_color(&mut self, color: (u8, u8, u8)) {
173        self.color = color;
174    }
175}