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            super::set_mark(
92                backend,
93                tip,
94                Some(super::tip_value(&x_col[i])),
95                super::series_key(data, i),
96                super::measured_value(data, i),
97            );
98
99            let (r, g, b) = if let Some(cc) = color_col {
100                scales
101                    .map_color(&Aesthetic::Color, &cc[i])
102                    .unwrap_or(self.color)
103            } else {
104                self.color
105            };
106
107            let alpha = alpha_col
108                .and_then(|c| scales.map_alpha(&c[i]))
109                .or_else(|| alpha_col.and_then(|c| c[i].as_f64()))
110                .unwrap_or(self.alpha);
111
112            let size = size_col
113                .and_then(|c| scales.map_size(&c[i]))
114                .or_else(|| size_col.and_then(|c| c[i].as_f64()))
115                .unwrap_or(self.size);
116
117            let shape = shape_col
118                .and_then(|c| scales.map_shape(&c[i]))
119                .unwrap_or(PointShape::Circle);
120
121            backend.draw_shape(
122                (px, py),
123                size,
124                &PointStyle {
125                    color: (r, g, b),
126                    alpha,
127                    filled: true,
128                    shape,
129                },
130            )?;
131        }
132        super::clear_mark(backend);
133
134        Ok(())
135    }
136
137    fn required_aes(&self) -> Vec<Aesthetic> {
138        vec![Aesthetic::X, Aesthetic::Y]
139    }
140
141    fn default_stat(&self) -> Box<dyn Stat> {
142        Box::new(StatIdentity)
143    }
144
145    fn default_position(&self) -> Box<dyn Position> {
146        Box::new(PositionIdentity)
147    }
148
149    fn default_params(&self) -> GeomParams {
150        GeomParams::default()
151    }
152
153    fn name(&self) -> &str {
154        "point"
155    }
156
157    fn set_series_color(&mut self, color: (u8, u8, u8)) {
158        self.color = color;
159    }
160}