1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::DataFrame;
4use crate::position::jitter::PositionJitter;
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 GeomJitter {
17 pub size: f64,
18 pub color: (u8, u8, u8),
19 pub alpha: f64,
20 pub width: Option<f64>,
22 pub height: Option<f64>,
24}
25
26impl Default for GeomJitter {
27 fn default() -> Self {
28 GeomJitter {
29 size: 3.0,
30 color: (0, 0, 0),
31 alpha: 1.0,
32 width: None,
33 height: None,
34 }
35 }
36}
37
38impl Geom for GeomJitter {
39 fn draw(
40 &self,
41 data: &DataFrame,
42 coord: &dyn Coord,
43 scales: &ScaleSet,
44 _theme: &Theme,
45 backend: &mut dyn DrawBackend,
46 ) -> Result<(), RenderError> {
47 let x_col = data
48 .column("x")
49 .ok_or(RenderError::MissingAesthetic("x".into()))?;
50 let y_col = data
51 .column("y")
52 .ok_or(RenderError::MissingAesthetic("y".into()))?;
53 let color_col = data.column("color");
54 let size_col = data.column("size");
55 let alpha_col = data.column("alpha");
56 let shape_col = data.column("shape");
57
58 let plot_area = backend.plot_area();
59 let x_scale = scales.get(&Aesthetic::X);
60 let y_scale = scales.get(&Aesthetic::Y);
61
62 for i in 0..data.nrows() {
63 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
64 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
65 let (px, py) = coord.transform((nx, ny), &plot_area);
66
67 let (r, g, b) = if let Some(cc) = color_col {
68 scales
69 .map_color(&Aesthetic::Color, &cc[i])
70 .unwrap_or(self.color)
71 } else {
72 self.color
73 };
74
75 let alpha = alpha_col.and_then(|c| c[i].as_f64()).unwrap_or(self.alpha);
76 let size = size_col.and_then(|c| c[i].as_f64()).unwrap_or(self.size);
77 let shape = shape_col
78 .and_then(|c| scales.map_shape(&c[i]))
79 .unwrap_or(PointShape::Circle);
80
81 backend.draw_shape(
82 (px, py),
83 size,
84 &PointStyle {
85 color: (r, g, b),
86 alpha,
87 filled: true,
88 shape,
89 },
90 )?;
91 }
92
93 Ok(())
94 }
95
96 fn required_aes(&self) -> Vec<Aesthetic> {
97 vec![Aesthetic::X, Aesthetic::Y]
98 }
99
100 fn default_stat(&self) -> Box<dyn Stat> {
101 Box::new(StatIdentity)
102 }
103
104 fn default_position(&self) -> Box<dyn Position> {
105 Box::new(PositionJitter {
106 width: self.width,
107 height: self.height,
108 ..PositionJitter::default()
109 })
110 }
111
112 fn default_params(&self) -> GeomParams {
113 GeomParams::default()
114 }
115
116 fn name(&self) -> &str {
117 "jitter"
118 }
119
120 fn set_series_color(&mut self, color: (u8, u8, u8)) {
121 self.color = color;
122 }
123}