Skip to main content

ggplot_rs/geom/
contour.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::contour::StatContour;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15/// Contour geometry — draws contour lines from gridded data.
16pub struct GeomContour {
17    pub color: (u8, u8, u8),
18    pub alpha: f64,
19    pub width: f64,
20    pub bins: usize,
21    pub n_levels: usize,
22}
23
24impl Default for GeomContour {
25    fn default() -> Self {
26        GeomContour {
27            color: (50, 50, 50),
28            alpha: 1.0,
29            width: 1.0,
30            bins: 50,
31            n_levels: 10,
32        }
33    }
34}
35
36impl Geom for GeomContour {
37    fn draw(
38        &self,
39        data: &DataFrame,
40        coord: &dyn Coord,
41        scales: &ScaleSet,
42        _theme: &Theme,
43        backend: &mut dyn DrawBackend,
44    ) -> Result<(), RenderError> {
45        let x_col = match data.column("x") {
46            Some(c) => c,
47            None => return Ok(()),
48        };
49        let y_col = match data.column("y") {
50            Some(c) => c,
51            None => return Ok(()),
52        };
53        let group_col = data.column("group");
54        let level_col = data.column("level");
55
56        let plot_area = backend.plot_area();
57        let x_scale = scales.get(&Aesthetic::X);
58        let y_scale = scales.get(&Aesthetic::Y);
59
60        // Draw segment pairs grouped by group column
61        // Each group is a line segment (2 points)
62        let nrows = data.nrows();
63        let mut i = 0;
64        while i + 1 < nrows {
65            // Check if these two points belong to the same group
66            let same_group = match group_col {
67                Some(gc) => gc[i].to_group_key() == gc[i + 1].to_group_key(),
68                None => true,
69            };
70
71            if same_group {
72                let nx0 = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
73                let ny0 = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
74                let nx1 = x_scale.map(|s| s.map(&x_col[i + 1])).unwrap_or(0.0);
75                let ny1 = y_scale.map(|s| s.map(&y_col[i + 1])).unwrap_or(0.0);
76
77                let p0 = coord.transform((nx0, ny0), &plot_area);
78                let p1 = coord.transform((nx1, ny1), &plot_area);
79
80                // Color by level if color scale is available
81                let color = if let Some(lc) = level_col {
82                    scales
83                        .map_color(&Aesthetic::Color, &lc[i])
84                        .unwrap_or(self.color)
85                } else {
86                    self.color
87                };
88
89                backend.draw_line(
90                    &[p0, p1],
91                    &LineStyle {
92                        color,
93                        alpha: self.alpha,
94                        width: self.width,
95                        linetype: Linetype::Solid,
96                    },
97                )?;
98
99                i += 2; // Skip the pair
100            } else {
101                i += 1;
102            }
103        }
104
105        Ok(())
106    }
107
108    fn required_aes(&self) -> Vec<Aesthetic> {
109        vec![Aesthetic::X, Aesthetic::Y]
110    }
111
112    fn default_stat(&self) -> Box<dyn Stat> {
113        Box::new(StatContour {
114            bins: self.bins,
115            n_levels: self.n_levels,
116        })
117    }
118
119    fn default_position(&self) -> Box<dyn Position> {
120        Box::new(PositionIdentity)
121    }
122
123    fn default_params(&self) -> GeomParams {
124        GeomParams::default()
125    }
126
127    fn name(&self) -> &str {
128        "contour"
129    }
130}