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::sum::StatSum;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomCount {
17 pub color: (u8, u8, u8),
18 pub alpha: f64,
19 pub min_size: f64,
20 pub max_size: f64,
21}
22
23impl Default for GeomCount {
24 fn default() -> Self {
25 GeomCount {
26 color: (50, 50, 50),
27 alpha: 0.7,
28 min_size: 2.0,
29 max_size: 12.0,
30 }
31 }
32}
33
34impl Geom for GeomCount {
35 fn draw(
36 &self,
37 data: &DataFrame,
38 coord: &dyn Coord,
39 scales: &ScaleSet,
40 _theme: &Theme,
41 backend: &mut dyn DrawBackend,
42 ) -> Result<(), RenderError> {
43 let x_col = data
44 .column("x")
45 .ok_or(RenderError::MissingAesthetic("x".into()))?;
46 let y_col = data
47 .column("y")
48 .ok_or(RenderError::MissingAesthetic("y".into()))?;
49 let n_col = data
50 .column("n")
51 .ok_or(RenderError::MissingAesthetic("n".into()))?;
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 let n_values: Vec<f64> = n_col.iter().filter_map(|v| v.as_f64()).collect();
59 let n_min = n_values.iter().cloned().fold(f64::INFINITY, f64::min);
60 let n_max = n_values.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
61 let n_range = n_max - n_min;
62
63 for i in 0..data.nrows() {
64 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
65 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
66 let (px, py) = coord.transform((nx, ny), &plot_area);
67
68 let n = n_col[i].as_f64().unwrap_or(1.0);
69 let size = if n_range > 0.0 {
70 self.min_size + (n - n_min) / n_range * (self.max_size - self.min_size)
71 } else {
72 (self.min_size + self.max_size) / 2.0
73 };
74
75 let color = scales
76 .map_color(&Aesthetic::Color, &x_col[i])
77 .unwrap_or(self.color);
78
79 backend.draw_shape(
80 (px, py),
81 size,
82 &PointStyle {
83 color,
84 alpha: self.alpha,
85 filled: true,
86 shape: PointShape::Circle,
87 },
88 )?;
89 }
90
91 Ok(())
92 }
93
94 fn required_aes(&self) -> Vec<Aesthetic> {
95 vec![Aesthetic::X, Aesthetic::Y]
96 }
97
98 fn default_stat(&self) -> Box<dyn Stat> {
99 Box::new(StatSum)
100 }
101
102 fn default_position(&self) -> Box<dyn Position> {
103 Box::new(PositionIdentity)
104 }
105
106 fn default_params(&self) -> GeomParams {
107 GeomParams::default()
108 }
109
110 fn name(&self) -> &str {
111 "count"
112 }
113
114 fn set_series_color(&mut self, color: (u8, u8, u8)) {
115 self.color = color;
116 }
117}