Skip to main content

ggplot_rs/scale/
continuous.rs

1use crate::aes::Aesthetic;
2use crate::data::Value;
3
4use super::format::LabelFormatter;
5use super::sec_axis::SecAxis;
6use super::transform::ScaleTransform;
7use super::util::{format_number, nice_step};
8use super::Scale;
9
10/// Continuous linear scale.
11#[derive(Clone)]
12pub struct ScaleContinuous {
13    aesthetic: Aesthetic,
14    name: String,
15    min: f64,
16    max: f64,
17    trained: bool,
18    filter_oob: bool,
19    expand: (f64, f64), // multiplicative and additive expansion
20    pub(crate) scale_transform: ScaleTransform,
21    custom_breaks: Option<Vec<f64>>,
22    custom_labels: Option<Vec<String>>,
23    pub(crate) sec_axis: Option<SecAxis>,
24    label_formatter: Option<LabelFormatter>,
25}
26
27impl ScaleContinuous {
28    pub fn new() -> Self {
29        ScaleContinuous {
30            aesthetic: Aesthetic::X,
31            name: String::new(),
32            min: f64::INFINITY,
33            max: f64::NEG_INFINITY,
34            trained: false,
35            filter_oob: false,
36            expand: (0.05, 0.0),
37            scale_transform: ScaleTransform::Identity,
38            custom_breaks: None,
39            custom_labels: None,
40            sec_axis: None,
41            label_formatter: None,
42        }
43    }
44
45    pub fn for_aesthetic(mut self, aes: Aesthetic) -> Self {
46        self.aesthetic = aes;
47        self
48    }
49
50    pub fn with_name(mut self, name: &str) -> Self {
51        self.name = name.to_string();
52        self
53    }
54
55    pub fn with_limits(mut self, min: f64, max: f64) -> Self {
56        self.min = min;
57        self.max = max;
58        self.trained = true;
59        self.filter_oob = true;
60        self
61    }
62
63    pub fn with_transform(mut self, transform: ScaleTransform) -> Self {
64        self.scale_transform = transform;
65        self
66    }
67
68    /// Set custom break positions (data values where ticks appear).
69    pub fn with_breaks(mut self, breaks: Vec<f64>) -> Self {
70        self.custom_breaks = Some(breaks);
71        self
72    }
73
74    /// Set custom labels for breaks. Must match the number of breaks.
75    pub fn with_labels(mut self, labels: Vec<String>) -> Self {
76        self.custom_labels = Some(labels);
77        self
78    }
79
80    /// Set the expansion multiplier and additive constant.
81    /// Like R's `expand = c(mult, add)`. Default is `(0.05, 0.0)`.
82    pub fn with_expand(mut self, mult: f64, add: f64) -> Self {
83        self.expand = (mult, add);
84        self
85    }
86
87    /// Set a label formatter function (e.g., `label_comma`, `label_percent`).
88    pub fn with_label_formatter(mut self, f: LabelFormatter) -> Self {
89        self.label_formatter = Some(f);
90        self
91    }
92
93    /// Add a secondary axis with a transformation function.
94    pub fn with_sec_axis(mut self, sec: SecAxis) -> Self {
95        self.sec_axis = Some(sec);
96        self
97    }
98
99    /// Get the secondary axis, if any.
100    pub fn sec_axis(&self) -> Option<&SecAxis> {
101        self.sec_axis.as_ref()
102    }
103
104    fn format_label(&self, v: f64) -> String {
105        if let Some(f) = self.label_formatter {
106            f(v)
107        } else {
108            format_number(v)
109        }
110    }
111
112    fn expanded_range(&self) -> (f64, f64) {
113        let range = self.max - self.min;
114        let mult = self.expand.0;
115        let add = self.expand.1;
116        (self.min - range * mult - add, self.max + range * mult + add)
117    }
118}
119
120impl Default for ScaleContinuous {
121    fn default() -> Self {
122        Self::new()
123    }
124}
125
126impl Scale for ScaleContinuous {
127    fn aesthetic(&self) -> Aesthetic {
128        self.aesthetic.clone()
129    }
130
131    fn train(&mut self, values: &[Value]) {
132        for v in values {
133            if let Some(f) = v.as_f64() {
134                if f.is_finite() {
135                    if f < self.min {
136                        self.min = f;
137                    }
138                    if f > self.max {
139                        self.max = f;
140                    }
141                }
142            }
143        }
144        self.trained = true;
145    }
146
147    fn map(&self, value: &Value) -> f64 {
148        let f = match value.as_f64() {
149            Some(f) => f,
150            None => return 0.0,
151        };
152        let (emin, emax) = self.expanded_range();
153        let range = emax - emin;
154        if range.abs() < f64::EPSILON {
155            0.5
156        } else {
157            (f - emin) / range
158        }
159    }
160
161    fn breaks(&self) -> Vec<(f64, String)> {
162        if !self.trained || self.min > self.max {
163            return vec![];
164        }
165
166        // Use custom breaks if provided
167        if let Some(ref custom) = self.custom_breaks {
168            return custom
169                .iter()
170                .enumerate()
171                .map(|(i, &v)| {
172                    let pos = self.map(&Value::Float(v));
173                    let label = if let Some(ref labels) = self.custom_labels {
174                        labels
175                            .get(i)
176                            .cloned()
177                            .unwrap_or_else(|| self.format_label(v))
178                    } else {
179                        self.format_label(self.scale_transform.inverse(v))
180                    };
181                    (pos, label)
182                })
183                .collect();
184        }
185
186        let range = self.max - self.min;
187        if range.abs() < f64::EPSILON {
188            let label = self.format_label(self.scale_transform.inverse(self.min));
189            return vec![(0.5, label)];
190        }
191
192        // Generate nice breaks across the expanded (visible) range
193        let (emin, emax) = self.expanded_range();
194        let n_breaks = 5;
195        let raw_step = range / n_breaks as f64;
196        let step = nice_step(raw_step);
197
198        let start = (emin / step).ceil() * step;
199        let mut breaks = Vec::new();
200        let mut v = start;
201        while v <= emax + step * 0.001 {
202            let pos = self.map(&Value::Float(v));
203            // Labels show the original (inverse-transformed) value
204            let label = self.format_label(self.scale_transform.inverse(v));
205            breaks.push((pos, label));
206            v += step;
207        }
208        breaks
209    }
210
211    fn name(&self) -> &str {
212        &self.name
213    }
214
215    fn set_name(&mut self, name: &str) {
216        self.name = name.to_string();
217    }
218
219    fn transform(&self, value: &Value) -> Value {
220        self.scale_transform.transform_value(value)
221    }
222
223    fn sec_axis(&self) -> Option<&SecAxis> {
224        self.sec_axis.as_ref()
225    }
226
227    fn set_limits(&mut self, min: f64, max: f64) {
228        self.min = min;
229        self.max = max;
230        self.trained = true;
231    }
232
233    fn filter_limits(&self) -> Option<(f64, f64)> {
234        if self.filter_oob && self.trained {
235            Some((self.min, self.max))
236        } else {
237            None
238        }
239    }
240
241    fn domain(&self) -> Option<(f64, f64)> {
242        if self.trained {
243            Some((self.min, self.max))
244        } else {
245            None
246        }
247    }
248
249    fn clone_box(&self) -> Box<dyn Scale> {
250        Box::new(self.clone())
251    }
252
253    fn reset_training(&mut self) {
254        self.min = f64::INFINITY;
255        self.max = f64::NEG_INFINITY;
256        self.trained = false;
257    }
258}