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        draw_points(
42            data,
43            coord,
44            scales,
45            backend,
46            PointDefaults {
47                size: self.size,
48                color: self.color,
49                alpha: self.alpha,
50                shape: PointShape::Circle,
51            },
52        )
53    }
54
55    fn required_aes(&self) -> Vec<Aesthetic> {
56        vec![Aesthetic::X, Aesthetic::Y]
57    }
58
59    fn default_stat(&self) -> Box<dyn Stat> {
60        Box::new(StatIdentity)
61    }
62
63    fn default_position(&self) -> Box<dyn Position> {
64        Box::new(PositionIdentity)
65    }
66
67    fn default_params(&self) -> GeomParams {
68        GeomParams::default()
69    }
70
71    fn name(&self) -> &str {
72        "point"
73    }
74
75    fn set_series_color(&mut self, color: (u8, u8, u8)) {
76        self.color = color;
77    }
78}
79
80/// Unmapped defaults for [`draw_points`].
81pub(crate) struct PointDefaults {
82    pub size: f64,
83    pub color: (u8, u8, u8),
84    pub alpha: f64,
85    pub shape: PointShape,
86}
87
88/// Draw one point per row (shared by `geom_point` and censor marks):
89/// mapped `color`/`size`/`alpha`/`shape` win over `defaults`; the x position
90/// honours a dodge offset; every point carries hover metadata.
91pub(crate) fn draw_points(
92    data: &DataFrame,
93    coord: &dyn Coord,
94    scales: &ScaleSet,
95    backend: &mut dyn DrawBackend,
96    defaults: PointDefaults,
97) -> Result<(), RenderError> {
98    let x_col = data
99        .column("x")
100        .ok_or(RenderError::MissingAesthetic("x".into()))?;
101    let y_col = data
102        .column("y")
103        .ok_or(RenderError::MissingAesthetic("y".into()))?;
104    let color_col = data.column("color");
105    let size_col = data.column("size");
106    let alpha_col = data.column("alpha");
107    let shape_col = data.column("shape");
108    let label_col = data.column("label");
109
110    let plot_area = backend.plot_area();
111    let xm = super::support::XMapper::new(data, scales);
112    let y_scale = scales.get(&Aesthetic::Y);
113
114    for i in 0..data.nrows() {
115        // Drop missing values (ggplot2 removes rows with NA x/y). Without this
116        // an NA maps to 0.0 and paints a spurious point at the panel baseline.
117        if matches!(x_col[i], crate::data::Value::Na) || matches!(y_col[i], crate::data::Value::Na)
118        {
119            continue;
120        }
121        let nx = xm.map(&x_col[i], i);
122        let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
123        let (px, py) = coord.transform((nx, ny), &plot_area);
124
125        // Hover tooltip: an explicit `label` with its y value ("series: 22"),
126        // else "(x, y)" prefixed by group.
127        let tip = match label_col
128            .map(|c| super::tip_value(&c[i]))
129            .filter(|s| !s.is_empty())
130        {
131            Some(l) => Some(format!("{l}: {}", super::tip_value(&y_col[i]))),
132            None => {
133                let xy = format!(
134                    "({}, {})",
135                    super::tip_value(&x_col[i]),
136                    super::tip_value(&y_col[i])
137                );
138                match color_col
139                    .map(|c| super::tip_value(&c[i]))
140                    .filter(|s| !s.is_empty())
141                {
142                    Some(gr) => Some(format!("{gr}: {xy}")),
143                    None => Some(xy),
144                }
145            }
146        };
147        super::set_mark(
148            backend,
149            tip,
150            Some(super::tip_value(&x_col[i])),
151            super::series_key(data, i),
152            super::measured_value(data, i),
153        );
154
155        let (r, g, b) = if let Some(cc) = color_col {
156            scales
157                .map_color(&Aesthetic::Color, &cc[i])
158                .unwrap_or(defaults.color)
159        } else {
160            defaults.color
161        };
162
163        let alpha = alpha_col
164            .and_then(|c| scales.map_alpha(&c[i]))
165            .or_else(|| alpha_col.and_then(|c| c[i].as_f64()))
166            .unwrap_or(defaults.alpha);
167
168        let size = size_col
169            .and_then(|c| scales.map_size(&c[i]))
170            .or_else(|| size_col.and_then(|c| c[i].as_f64()))
171            .unwrap_or(defaults.size);
172
173        let shape = shape_col
174            .and_then(|c| scales.map_shape(&c[i]))
175            .unwrap_or(defaults.shape);
176
177        backend.draw_shape(
178            (px, py),
179            size,
180            &PointStyle {
181                color: (r, g, b),
182                alpha,
183                filled: true,
184                shape,
185            },
186        )?;
187    }
188    super::clear_mark(backend);
189
190    Ok(())
191}