ggplot_rs/geom/
dotplot.rs1use 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::bindot::StatBindot;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomDotplot {
17 pub size: f64,
18 pub color: (u8, u8, u8),
19 pub fill: (u8, u8, u8),
20 pub alpha: f64,
21}
22
23impl Default for GeomDotplot {
24 fn default() -> Self {
25 GeomDotplot {
26 size: 3.0,
27 color: (0, 0, 0),
28 fill: (97, 156, 255),
29 alpha: 1.0,
30 }
31 }
32}
33
34impl Geom for GeomDotplot {
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 fill_col = data.column("fill");
50
51 let plot_area = backend.plot_area();
52 let x_scale = scales.get(&Aesthetic::X);
53 let y_scale = scales.get(&Aesthetic::Y);
54 let x_mapper = super::support::XMapper::new(data, scales);
56
57 for i in 0..data.nrows() {
58 let nx = if x_scale.is_some() {
59 x_mapper.map(&x_col[i], i)
60 } else {
61 0.0
62 };
63 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
64 let (px, py) = coord.transform((nx, ny), &plot_area);
65
66 let dot_color = fill_col
67 .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[i]))
68 .unwrap_or(self.fill);
69
70 backend.draw_shape(
71 (px, py),
72 self.size,
73 &PointStyle {
74 color: dot_color,
75 alpha: self.alpha,
76 filled: true,
77 shape: PointShape::Circle,
78 },
79 )?;
80 }
81
82 Ok(())
83 }
84
85 fn required_aes(&self) -> Vec<Aesthetic> {
86 vec![Aesthetic::X]
87 }
88
89 fn default_stat(&self) -> Box<dyn Stat> {
90 Box::new(StatBindot::default())
91 }
92
93 fn default_position(&self) -> Box<dyn Position> {
94 Box::new(PositionIdentity)
95 }
96
97 fn default_params(&self) -> GeomParams {
98 GeomParams::default()
99 }
100
101 fn name(&self) -> &str {
102 "dotplot"
103 }
104
105 fn set_series_color(&mut self, color: (u8, u8, u8)) {
110 self.fill = color;
111 }
112}