Skip to main content

ggplot_rs/geom/
point.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, PointShape, PointStyle};
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/// Scatter plot points.
16pub struct GeomPoint {
17    pub size: f64,
18    pub color: (u8, u8, u8),
19    pub alpha: f64,
20}
21
22impl Default for GeomPoint {
23    fn default() -> Self {
24        GeomPoint {
25            size: 3.0,
26            color: (0, 0, 0),
27            alpha: 1.0,
28        }
29    }
30}
31
32impl Geom for GeomPoint {
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 size_col = data.column("size");
49        let alpha_col = data.column("alpha");
50        let shape_col = data.column("shape");
51        let label_col = data.column("label");
52
53        let plot_area = backend.plot_area();
54        let x_scale = scales.get(&Aesthetic::X);
55        let y_scale = scales.get(&Aesthetic::Y);
56
57        for i in 0..data.nrows() {
58            // Drop missing values (ggplot2 removes rows with NA x/y). Without this
59            // an NA maps to 0.0 and paints a spurious point at the panel baseline.
60            if matches!(x_col[i], crate::data::Value::Na)
61                || matches!(y_col[i], crate::data::Value::Na)
62            {
63                continue;
64            }
65            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
66            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
67            let (px, py) = coord.transform((nx, ny), &plot_area);
68
69            // Hover tooltip: an explicit `label` with its y value ("series: 22"),
70            // else "(x, y)" prefixed by group.
71            let tip = match label_col
72                .map(|c| super::tip_value(&c[i]))
73                .filter(|s| !s.is_empty())
74            {
75                Some(l) => Some(format!("{l}: {}", super::tip_value(&y_col[i]))),
76                None => {
77                    let xy = format!(
78                        "({}, {})",
79                        super::tip_value(&x_col[i]),
80                        super::tip_value(&y_col[i])
81                    );
82                    match color_col
83                        .map(|c| super::tip_value(&c[i]))
84                        .filter(|s| !s.is_empty())
85                    {
86                        Some(gr) => Some(format!("{gr}: {xy}")),
87                        None => Some(xy),
88                    }
89                }
90            };
91            backend.set_tooltip(tip);
92            backend.set_mark_axis(Some(super::tip_value(&x_col[i])));
93
94            let (r, g, b) = if let Some(cc) = color_col {
95                scales
96                    .map_color(&Aesthetic::Color, &cc[i])
97                    .unwrap_or(self.color)
98            } else {
99                self.color
100            };
101
102            let alpha = alpha_col
103                .and_then(|c| scales.map_alpha(&c[i]))
104                .or_else(|| alpha_col.and_then(|c| c[i].as_f64()))
105                .unwrap_or(self.alpha);
106
107            let size = size_col
108                .and_then(|c| scales.map_size(&c[i]))
109                .or_else(|| size_col.and_then(|c| c[i].as_f64()))
110                .unwrap_or(self.size);
111
112            let shape = shape_col
113                .and_then(|c| scales.map_shape(&c[i]))
114                .unwrap_or(PointShape::Circle);
115
116            backend.draw_shape(
117                (px, py),
118                size,
119                &PointStyle {
120                    color: (r, g, b),
121                    alpha,
122                    filled: true,
123                    shape,
124                },
125            )?;
126        }
127        backend.set_tooltip(None);
128        backend.set_mark_axis(None);
129
130        Ok(())
131    }
132
133    fn required_aes(&self) -> Vec<Aesthetic> {
134        vec![Aesthetic::X, Aesthetic::Y]
135    }
136
137    fn default_stat(&self) -> Box<dyn Stat> {
138        Box::new(StatIdentity)
139    }
140
141    fn default_position(&self) -> Box<dyn Position> {
142        Box::new(PositionIdentity)
143    }
144
145    fn default_params(&self) -> GeomParams {
146        GeomParams::default()
147    }
148
149    fn name(&self) -> &str {
150        "point"
151    }
152
153    fn set_series_color(&mut self, color: (u8, u8, u8)) {
154        self.color = color;
155    }
156}