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
15pub 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
52 let plot_area = backend.plot_area();
53 let x_scale = scales.get(&Aesthetic::X);
54 let y_scale = scales.get(&Aesthetic::Y);
55
56 for i in 0..data.nrows() {
57 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
58 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
59 let (px, py) = coord.transform((nx, ny), &plot_area);
60
61 let (r, g, b) = if let Some(cc) = color_col {
62 scales
63 .map_color(&Aesthetic::Color, &cc[i])
64 .unwrap_or(self.color)
65 } else {
66 self.color
67 };
68
69 let alpha = alpha_col
70 .and_then(|c| scales.map_alpha(&c[i]))
71 .or_else(|| alpha_col.and_then(|c| c[i].as_f64()))
72 .unwrap_or(self.alpha);
73
74 let size = size_col
75 .and_then(|c| scales.map_size(&c[i]))
76 .or_else(|| size_col.and_then(|c| c[i].as_f64()))
77 .unwrap_or(self.size);
78
79 let shape = shape_col
80 .and_then(|c| scales.map_shape(&c[i]))
81 .unwrap_or(PointShape::Circle);
82
83 backend.draw_shape(
84 (px, py),
85 size,
86 &PointStyle {
87 color: (r, g, b),
88 alpha,
89 filled: true,
90 shape,
91 },
92 )?;
93 }
94
95 Ok(())
96 }
97
98 fn required_aes(&self) -> Vec<Aesthetic> {
99 vec![Aesthetic::X, Aesthetic::Y]
100 }
101
102 fn default_stat(&self) -> Box<dyn Stat> {
103 Box::new(StatIdentity)
104 }
105
106 fn default_position(&self) -> Box<dyn Position> {
107 Box::new(PositionIdentity)
108 }
109
110 fn default_params(&self) -> GeomParams {
111 GeomParams::default()
112 }
113
114 fn name(&self) -> &str {
115 "point"
116 }
117
118 fn set_series_color(&mut self, color: (u8, u8, u8)) {
119 self.color = color;
120 }
121}