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            let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
59            let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
60            let (px, py) = coord.transform((nx, ny), &plot_area);
61
62            // Hover tooltip: an explicit `label`, else "(x, y)" prefixed by group.
63            let tip = label_col
64                .map(|c| super::tip_value(&c[i]))
65                .filter(|s| !s.is_empty())
66                .or_else(|| {
67                    let xy = format!(
68                        "({}, {})",
69                        super::tip_value(&x_col[i]),
70                        super::tip_value(&y_col[i])
71                    );
72                    match color_col
73                        .map(|c| super::tip_value(&c[i]))
74                        .filter(|s| !s.is_empty())
75                    {
76                        Some(gr) => Some(format!("{gr}: {xy}")),
77                        None => Some(xy),
78                    }
79                });
80            backend.set_tooltip(tip);
81
82            let (r, g, b) = if let Some(cc) = color_col {
83                scales
84                    .map_color(&Aesthetic::Color, &cc[i])
85                    .unwrap_or(self.color)
86            } else {
87                self.color
88            };
89
90            let alpha = alpha_col
91                .and_then(|c| scales.map_alpha(&c[i]))
92                .or_else(|| alpha_col.and_then(|c| c[i].as_f64()))
93                .unwrap_or(self.alpha);
94
95            let size = size_col
96                .and_then(|c| scales.map_size(&c[i]))
97                .or_else(|| size_col.and_then(|c| c[i].as_f64()))
98                .unwrap_or(self.size);
99
100            let shape = shape_col
101                .and_then(|c| scales.map_shape(&c[i]))
102                .unwrap_or(PointShape::Circle);
103
104            backend.draw_shape(
105                (px, py),
106                size,
107                &PointStyle {
108                    color: (r, g, b),
109                    alpha,
110                    filled: true,
111                    shape,
112                },
113            )?;
114        }
115        backend.set_tooltip(None);
116
117        Ok(())
118    }
119
120    fn required_aes(&self) -> Vec<Aesthetic> {
121        vec![Aesthetic::X, Aesthetic::Y]
122    }
123
124    fn default_stat(&self) -> Box<dyn Stat> {
125        Box::new(StatIdentity)
126    }
127
128    fn default_position(&self) -> Box<dyn Position> {
129        Box::new(PositionIdentity)
130    }
131
132    fn default_params(&self) -> GeomParams {
133        GeomParams::default()
134    }
135
136    fn name(&self) -> &str {
137        "point"
138    }
139
140    fn set_series_color(&mut self, color: (u8, u8, u8)) {
141        self.color = color;
142    }
143}