ggplot_rs/geom/
errorbar.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, LineStyle, Linetype};
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 GeomErrorbar {
17 pub color: (u8, u8, u8),
18 pub width: f64,
19 pub cap_width: f64,
20 pub alpha: f64,
21}
22
23impl Default for GeomErrorbar {
24 fn default() -> Self {
25 GeomErrorbar {
26 color: (0, 0, 0),
27 width: 1.0,
28 cap_width: 0.03,
29 alpha: 1.0,
30 }
31 }
32}
33
34impl Geom for GeomErrorbar {
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 ymin_col = data
47 .column("ymin")
48 .ok_or(RenderError::MissingAesthetic("ymin".into()))?;
49 let ymax_col = data
50 .column("ymax")
51 .ok_or(RenderError::MissingAesthetic("ymax".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 style = LineStyle {
58 color: self.color,
59 alpha: self.alpha,
60 width: self.width,
61 linetype: Linetype::Solid,
62 };
63
64 for i in 0..data.nrows() {
65 let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
66 let ny_min = y_scale.map(|s| s.map(&ymin_col[i])).unwrap_or(0.0);
67 let ny_max = y_scale.map(|s| s.map(&ymax_col[i])).unwrap_or(0.0);
68
69 let (cx, top) = coord.transform((nx, ny_max), &plot_area);
70 let (_, bottom) = coord.transform((nx, ny_min), &plot_area);
71
72 backend.draw_line(&[(cx, top), (cx, bottom)], &style)?;
74
75 let (cap_l, _) = coord.transform((nx - self.cap_width, ny_max), &plot_area);
77 let (cap_r, _) = coord.transform((nx + self.cap_width, ny_max), &plot_area);
78 backend.draw_line(&[(cap_l, top), (cap_r, top)], &style)?;
79
80 let (cap_l, _) = coord.transform((nx - self.cap_width, ny_min), &plot_area);
82 let (cap_r, _) = coord.transform((nx + self.cap_width, ny_min), &plot_area);
83 backend.draw_line(&[(cap_l, bottom), (cap_r, bottom)], &style)?;
84 }
85
86 Ok(())
87 }
88
89 fn required_aes(&self) -> Vec<Aesthetic> {
90 vec![Aesthetic::X, Aesthetic::Ymin, Aesthetic::Ymax]
91 }
92
93 fn default_stat(&self) -> Box<dyn Stat> {
94 Box::new(StatIdentity)
95 }
96 fn default_position(&self) -> Box<dyn Position> {
97 Box::new(PositionIdentity)
98 }
99 fn default_params(&self) -> GeomParams {
100 GeomParams::default()
101 }
102 fn name(&self) -> &str {
103 "errorbar"
104 }
105
106 fn set_series_color(&mut self, color: (u8, u8, u8)) {
107 self.color = color;
108 }
109}