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 y_scale = scales.get(&Aesthetic::Y);
55
56 let style = LineStyle {
57 color: self.color,
58 alpha: self.alpha,
59 width: self.width,
60 linetype: Linetype::Solid,
61 ..Default::default()
62 };
63
64 let xm = super::support::XMapper::new(data, scales);
65 let color_col = data.column("color");
66 for i in 0..data.nrows() {
67 let nx = xm.map(&x_col[i], i);
68 let ny_min = y_scale.map(|s| s.map(&ymin_col[i])).unwrap_or(0.0);
69 let ny_max = y_scale.map(|s| s.map(&ymax_col[i])).unwrap_or(0.0);
70 let color = color_col
71 .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[i]))
72 .unwrap_or(self.color);
73 let style = LineStyle {
74 color,
75 ..style.clone()
76 };
77
78 let c = self.cap_width;
81 let t = |p: (f64, f64)| coord.transform(p, &plot_area);
82 super::support::mark_interval(backend, data, i, &x_col[i], &ymin_col[i], &ymax_col[i]);
83 backend.draw_line(
84 &[
85 t((nx - c, ny_max)),
86 t((nx + c, ny_max)),
87 t((nx, ny_max)),
88 t((nx, ny_min)),
89 t((nx - c, ny_min)),
90 t((nx + c, ny_min)),
91 ],
92 &style,
93 )?;
94 }
95 super::clear_mark(backend);
96
97 Ok(())
98 }
99
100 fn required_aes(&self) -> Vec<Aesthetic> {
101 vec![Aesthetic::X, Aesthetic::Ymin, Aesthetic::Ymax]
102 }
103
104 fn default_stat(&self) -> Box<dyn Stat> {
105 Box::new(StatIdentity)
106 }
107 fn default_position(&self) -> Box<dyn Position> {
108 Box::new(PositionIdentity)
109 }
110 fn default_params(&self) -> GeomParams {
111 GeomParams::default()
112 }
113 fn name(&self) -> &str {
114 "errorbar"
115 }
116
117 fn set_series_color(&mut self, color: (u8, u8, u8)) {
118 self.color = color;
119 }
120}