ggplot_rs/geom/
segment.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 GeomSegment {
17 pub color: (u8, u8, u8),
18 pub width: f64,
19 pub alpha: f64,
20}
21
22impl Default for GeomSegment {
23 fn default() -> Self {
24 GeomSegment {
25 color: (0, 0, 0),
26 width: 1.0,
27 alpha: 1.0,
28 }
29 }
30}
31
32impl Geom for GeomSegment {
33 fn draw(
34 &self,
35 data: &DataFrame,
36 coord: &dyn Coord,
37 scales: &ScaleSet,
38 _theme: &Theme,
39 backend: &mut dyn DrawBackend,
40 ) -> Result<(), RenderError> {
41 let x_col = data
42 .column("x")
43 .ok_or(RenderError::MissingAesthetic("x".into()))?;
44 let y_col = data
45 .column("y")
46 .ok_or(RenderError::MissingAesthetic("y".into()))?;
47 let xend_col = data
48 .column("xend")
49 .ok_or(RenderError::MissingAesthetic("xend".into()))?;
50 let yend_col = data
51 .column("yend")
52 .ok_or(RenderError::MissingAesthetic("yend".into()))?;
53 let color_col = data.column("color");
54
55 let plot_area = backend.plot_area();
56 let x_scale = scales.get(&Aesthetic::X);
57 let y_scale = scales.get(&Aesthetic::Y);
58
59 for i in 0..data.nrows() {
60 let nx1 = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
61 let ny1 = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
62 let nx2 = x_scale.map(|s| s.map(&xend_col[i])).unwrap_or(0.0);
63 let ny2 = y_scale.map(|s| s.map(¥d_col[i])).unwrap_or(0.0);
64
65 let (px1, py1) = coord.transform((nx1, ny1), &plot_area);
66 let (px2, py2) = coord.transform((nx2, ny2), &plot_area);
67
68 let line_color = color_col
69 .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[i]))
70 .unwrap_or(self.color);
71
72 backend.draw_line(
73 &[(px1, py1), (px2, py2)],
74 &LineStyle {
75 color: line_color,
76 alpha: self.alpha,
77 width: self.width,
78 linetype: Linetype::Solid,
79 },
80 )?;
81 }
82
83 Ok(())
84 }
85
86 fn required_aes(&self) -> Vec<Aesthetic> {
87 vec![Aesthetic::X, Aesthetic::Y, Aesthetic::Xend, Aesthetic::Yend]
88 }
89
90 fn default_stat(&self) -> Box<dyn Stat> {
91 Box::new(StatIdentity)
92 }
93 fn default_position(&self) -> Box<dyn Position> {
94 Box::new(PositionIdentity)
95 }
96 fn default_params(&self) -> GeomParams {
97 GeomParams::default()
98 }
99 fn name(&self) -> &str {
100 "segment"
101 }
102
103 fn set_series_color(&mut self, color: (u8, u8, u8)) {
104 self.color = color;
105 }
106}