Skip to main content

ggplot_rs/scale/
scale_set.rs

1use crate::aes::Aesthetic;
2use crate::data::{DataFrame, Value};
3use crate::render::backend::{Linetype, PointShape};
4use crate::scale::alpha::ScaleAlphaContinuous;
5use crate::scale::color::{ScaleColorContinuous, ScaleColorDiscrete};
6use crate::scale::continuous::ScaleContinuous;
7use crate::scale::datetime::ScaleDateTime;
8use crate::scale::discrete::ScaleDiscrete;
9use crate::scale::linetype::ScaleLinetypeDiscrete;
10use crate::scale::linewidth::ScaleLinewidthContinuous;
11use crate::scale::shape::ScaleShapeDiscrete;
12use crate::scale::size::ScaleSizeContinuous;
13
14use super::Scale;
15
16/// Registry of all scales for a plot. Handles auto-detection and training.
17pub struct ScaleSet {
18    scales: Vec<Box<dyn Scale>>,
19}
20
21impl ScaleSet {
22    pub fn new() -> Self {
23        ScaleSet { scales: Vec::new() }
24    }
25
26    /// Add a user-specified scale.
27    pub fn add(&mut self, scale: Box<dyn Scale>) {
28        // Replace existing scale for same aesthetic
29        let aes = scale.aesthetic();
30        self.scales.retain(|s| s.aesthetic() != aes);
31        self.scales.push(scale);
32    }
33
34    /// Give every scale the plot-level default locale (scales with their own
35    /// locale keep it; scales without numeric/date labels ignore it).
36    pub fn set_default_locale(&mut self, locale: &crate::locale::Locale) {
37        for s in &mut self.scales {
38            s.set_default_locale(locale);
39        }
40    }
41
42    /// Get a scale for a specific aesthetic.
43    pub fn get(&self, aes: &Aesthetic) -> Option<&dyn Scale> {
44        self.scales
45            .iter()
46            .find(|s| s.aesthetic() == *aes)
47            .map(|s| s.as_ref())
48    }
49
50    /// Get mutable scale for a specific aesthetic.
51    pub fn get_mut(&mut self, aes: &Aesthetic) -> Option<&mut Box<dyn Scale>> {
52        self.scales.iter_mut().find(|s| s.aesthetic() == *aes)
53    }
54
55    /// Ensure a scale exists for a given aesthetic. Auto-detect type from data.
56    pub fn ensure_scale(&mut self, aes: &Aesthetic, data: &DataFrame) {
57        if self.get(aes).is_some() {
58            return;
59        }
60        // OHLC values live on the y scale (via the geom's ymin/ymax extents);
61        // they get no scale of their own.
62        if matches!(
63            aes,
64            Aesthetic::Open
65                | Aesthetic::High
66                | Aesthetic::Low
67                | Aesthetic::Close
68                | Aesthetic::Slope
69                | Aesthetic::Intercept
70                // Reference-line intercepts live on the x / y scale; the
71                // build creates that scale from them only if no layer did
72                // (so a `geom_vline(0)` added first can't force a
73                // continuous scale onto a discrete axis).
74                | Aesthetic::Xintercept
75                | Aesthetic::Yintercept
76                // Interactive aesthetics carry their value straight through
77                // to the mark's attributes — no visual mapping, no legend.
78                | Aesthetic::Tooltip
79                | Aesthetic::DataAttr(_)
80                | Aesthetic::Class
81                | Aesthetic::GroupWrap(_)
82                // Boxplot stat="identity" hinges/outliers (B3-5) live on
83                // the y scale (via `column_aesthetic`/`Y_FAMILY`/the
84                // build's stat_aes training list), not a scale of their
85                // own.
86                | Aesthetic::Lower
87                | Aesthetic::Middle
88                | Aesthetic::Upper
89                | Aesthetic::Outliers
90        ) {
91            return;
92        }
93        let values = data.column(aes.col_name());
94
95        let is_discrete = match values {
96            Some(vals) => vals
97                .iter()
98                .any(|v| matches!(v, Value::Str(_) | Value::Bool(_))),
99            None => false,
100        };
101
102        let is_datetime = match values {
103            Some(vals) => vals.iter().any(|v| v.is_datetime()),
104            None => false,
105        };
106
107        match aes {
108            Aesthetic::Color | Aesthetic::Fill => {
109                if is_discrete {
110                    let scale = ScaleColorDiscrete::new(aes.clone());
111                    self.scales.push(Box::new(scale));
112                } else {
113                    let scale = ScaleColorContinuous::new(aes.clone());
114                    self.scales.push(Box::new(scale));
115                }
116            }
117            Aesthetic::Shape => {
118                let scale = ScaleShapeDiscrete::new();
119                self.scales.push(Box::new(scale));
120            }
121            Aesthetic::Linetype => {
122                let scale = ScaleLinetypeDiscrete::new();
123                self.scales.push(Box::new(scale));
124            }
125            Aesthetic::Size => {
126                let scale = ScaleSizeContinuous::new();
127                self.scales.push(Box::new(scale));
128            }
129            Aesthetic::Linewidth => {
130                let scale = ScaleLinewidthContinuous::new();
131                self.scales.push(Box::new(scale));
132            }
133            Aesthetic::Alpha => {
134                let scale = ScaleAlphaContinuous::new();
135                self.scales.push(Box::new(scale));
136            }
137            _ => {
138                if is_discrete {
139                    let scale = ScaleDiscrete::new().for_aesthetic(aes.clone());
140                    self.scales.push(Box::new(scale));
141                } else if is_datetime {
142                    let scale = ScaleDateTime::new().for_aesthetic(aes.clone());
143                    self.scales.push(Box::new(scale));
144                } else {
145                    let scale = ScaleContinuous::new().for_aesthetic(aes.clone());
146                    self.scales.push(Box::new(scale));
147                }
148            }
149        }
150    }
151
152    /// Train all scales on data from one layer.
153    pub fn train_layer(&mut self, data: &DataFrame) {
154        for scale in &mut self.scales {
155            let col_name = scale.aesthetic().col_name().to_string();
156            if let Some(values) = data.column(&col_name) {
157                scale.train(values);
158            }
159        }
160    }
161
162    /// Map a single value through the appropriate scale.
163    pub fn map_value(&self, aes: &Aesthetic, value: &Value) -> f64 {
164        self.get(aes).map(|s| s.map(value)).unwrap_or(0.0)
165    }
166
167    /// Map a value to an RGB color through the appropriate color/fill scale.
168    pub fn map_color(&self, aes: &Aesthetic, value: &Value) -> Option<(u8, u8, u8)> {
169        self.get(aes).and_then(|s| s.map_to_color(value))
170    }
171
172    /// The `aes` scale's configured na-pattern, if any (`ScaleFillBinned::
173    /// na_pattern`, #206) — a geom checks this for a row/key it would
174    /// otherwise draw with the scale's flat na colour, before falling
175    /// back to [`map_color`](Self::map_color)'s plain result.
176    pub fn na_fill_pattern(&self, aes: &Aesthetic) -> Option<crate::render::backend::FillPattern> {
177        self.get(aes).and_then(|s| s.na_fill_pattern())
178    }
179
180    /// Map a value to a point shape through the shape scale.
181    pub fn map_shape(&self, value: &Value) -> Option<PointShape> {
182        self.get(&Aesthetic::Shape)
183            .and_then(|s| s.map_to_shape(value))
184    }
185
186    /// Map a value to a linetype through the linetype scale.
187    pub fn map_linetype(&self, value: &Value) -> Option<Linetype> {
188        self.get(&Aesthetic::Linetype)
189            .and_then(|s| s.map_to_linetype(value))
190    }
191
192    /// Map a value to a point size through the size scale.
193    pub fn map_size(&self, value: &Value) -> Option<f64> {
194        self.get(&Aesthetic::Size)
195            .and_then(|s| s.map_to_size(value))
196    }
197
198    /// Map a value to an alpha (opacity) through the alpha scale.
199    pub fn map_alpha(&self, value: &Value) -> Option<f64> {
200        self.get(&Aesthetic::Alpha)
201            .and_then(|s| s.map_to_alpha(value))
202    }
203
204    /// Map a value to a stroke width through the linewidth scale.
205    pub fn map_linewidth(&self, value: &Value) -> Option<f64> {
206        self.get(&Aesthetic::Linewidth)
207            .and_then(|s| s.map_to_size(value))
208    }
209
210    /// Override the domain limits for a scale (used by coord_cartesian zoom).
211    pub fn set_limits(&mut self, aes: &Aesthetic, min: f64, max: f64) {
212        if let Some(scale) = self.get_mut(aes) {
213            scale.set_limits(min, max);
214        }
215    }
216
217    /// Get the secondary axis for an aesthetic, if one exists.
218    pub fn sec_axis(&self, aes: &Aesthetic) -> Option<&crate::scale::sec_axis::SecAxis> {
219        self.get(aes).and_then(|s| s.sec_axis())
220    }
221
222    /// Get all scales.
223    pub fn iter(&self) -> impl Iterator<Item = &dyn Scale> {
224        self.scales.iter().map(|s| s.as_ref())
225    }
226}
227
228impl Clone for ScaleSet {
229    fn clone(&self) -> Self {
230        ScaleSet {
231            scales: self.scales.iter().map(|s| s.clone_box()).collect(),
232        }
233    }
234}
235
236impl Default for ScaleSet {
237    fn default() -> Self {
238        Self::new()
239    }
240}