1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::sync::Arc;
use crate::aes::Aesthetic;
use crate::data::Value;
use super::format::LabelFormatter;
use super::sec_axis::SecAxis;
use super::transform::ScaleTransform;
use super::util::extended_breaks;
use super::Scale;
/// Locale-dependent break labels ([`ScaleContinuous::with_localized_labels`]).
pub type LocalizedLabels = Arc<dyn Fn(Option<&crate::locale::Locale>) -> Vec<String> + Send + Sync>;
/// Continuous linear scale.
#[derive(Clone)]
pub struct ScaleContinuous {
aesthetic: Aesthetic,
name: String,
min: f64,
max: f64,
trained: bool,
filter_oob: bool,
// Per-side expansion: (mult_lower, add_lower, mult_upper, add_upper).
expand: (f64, f64, f64, f64),
// Axis position: false = default (bottom for x, left for y), true = opposite
// side (top for x, right for y).
position_opposite: bool,
pub(crate) scale_transform: ScaleTransform,
custom_breaks: Option<Vec<f64>>,
custom_labels: Option<Vec<String>>,
/// Labels for `custom_breaks` resolved against the scale's locale.
localized_labels: Option<LocalizedLabels>,
pub(crate) sec_axis: Option<SecAxis>,
label_formatter: Option<LabelFormatter>,
/// Locale for the default labels (`None` = default marks).
locale: Option<crate::locale::Locale>,
/// Formatter for `format_value` (B2-4: `data-fvalue`/tooltip templates),
/// distinct from `label_formatter` — e.g. a full currency string where
/// the axis itself shows an abbreviated break.
value_formatter: Option<LabelFormatter>,
}
impl ScaleContinuous {
pub fn new() -> Self {
ScaleContinuous {
aesthetic: Aesthetic::X,
name: String::new(),
min: f64::INFINITY,
max: f64::NEG_INFINITY,
trained: false,
filter_oob: false,
expand: (0.05, 0.0, 0.05, 0.0),
position_opposite: false,
scale_transform: ScaleTransform::Identity,
custom_breaks: None,
custom_labels: None,
localized_labels: None,
sec_axis: None,
label_formatter: None,
locale: None,
value_formatter: None,
}
}
pub fn for_aesthetic(mut self, aes: Aesthetic) -> Self {
self.aesthetic = aes;
self
}
pub fn with_name(mut self, name: &str) -> Self {
self.name = name.to_string();
self
}
pub fn with_limits(mut self, min: f64, max: f64) -> Self {
self.min = min;
self.max = max;
self.trained = true;
self.filter_oob = true;
self
}
pub fn with_transform(mut self, transform: ScaleTransform) -> Self {
self.scale_transform = transform;
self
}
/// Set custom break positions (data values where ticks appear).
pub fn with_breaks(mut self, breaks: Vec<f64>) -> Self {
self.custom_breaks = Some(breaks);
self
}
/// Set custom labels for breaks. Must match the number of breaks.
pub fn with_labels(mut self, labels: Vec<String>) -> Self {
self.custom_labels = Some(labels);
self
}
/// Labels for the custom breaks that depend on the locale (month or
/// weekday names): `f` gets the scale's locale — the plot's
/// [`GGPlot::locale`](crate::plot::GGPlot::locale) unless set on the
/// scale — or `None`. Takes precedence over [`with_labels`](Self::with_labels).
pub fn with_localized_labels<F>(mut self, f: F) -> Self
where
F: Fn(Option<&crate::locale::Locale>) -> Vec<String> + Send + Sync + 'static,
{
self.localized_labels = Some(Arc::new(f));
self
}
/// Set the expansion multiplier and additive constant.
/// Like R's `expand = c(mult, add)`, applied symmetrically. Default `(0.05, 0.0)`.
pub fn with_expand(mut self, mult: f64, add: f64) -> Self {
self.expand = (mult, add, mult, add);
self
}
/// Per-side expansion (R's `expansion(mult = c(l, u), add = c(l, u))`):
/// separate multiplicative/additive expansion for the lower and upper ends.
pub fn with_expand_sides(
mut self,
mult_lower: f64,
add_lower: f64,
mult_upper: f64,
add_upper: f64,
) -> Self {
self.expand = (mult_lower, add_lower, mult_upper, add_upper);
self
}
/// Place this axis on the opposite side (x → top, y → right).
pub fn with_position_opposite(mut self) -> Self {
self.position_opposite = true;
self
}
/// Set a label formatter. Accepts a plain `fn` (e.g. `label_comma`) or a
/// configurable formatter such as `label_si()` / `label_number(...)`.
pub fn with_label_formatter<F>(mut self, f: F) -> Self
where
F: Fn(f64) -> String + Send + Sync + 'static,
{
self.label_formatter = Some(std::sync::Arc::new(f));
self
}
/// Set a formatter for [`format_value`](Scale::format_value) — a
/// per-mark `data-fvalue` or tooltip-template value — distinct from
/// [`with_label_formatter`](Self::with_label_formatter), which only
/// affects axis break labels. Falls back to the label formatter, then
/// the locale default, when unset.
pub fn with_value_formatter<F>(mut self, f: F) -> Self
where
F: Fn(f64) -> String + Send + Sync + 'static,
{
self.value_formatter = Some(std::sync::Arc::new(f));
self
}
/// Render the default break labels with `locale`'s decimal and thousands
/// marks (`1.000`, `2,5` in de-DE). Overrides the plot locale
/// ([`GGPlot::locale`](crate::GGPlot::locale)); a custom
/// [`with_label_formatter`](Self::with_label_formatter) still wins.
pub fn with_locale(mut self, locale: crate::locale::Locale) -> Self {
self.locale = Some(locale);
self
}
/// Add a secondary axis with a transformation function.
pub fn with_sec_axis(mut self, sec: SecAxis) -> Self {
self.sec_axis = Some(sec);
self
}
/// Get the secondary axis, if any.
pub fn sec_axis(&self) -> Option<&SecAxis> {
self.sec_axis.as_ref()
}
fn format_label(&self, v: f64) -> String {
if let Some(f) = &self.label_formatter {
f(v)
} else {
super::util::format_number_opt(v, self.locale.as_ref())
}
}
fn expanded_range(&self) -> (f64, f64) {
let range = self.max - self.min;
let (ml, al, mu, au) = self.expand;
(self.min - range * ml - al, self.max + range * mu + au)
}
/// Whether this axis should be drawn on the opposite side (x → top, y → right).
pub fn is_opposite(&self) -> bool {
self.position_opposite
}
}
impl Default for ScaleContinuous {
fn default() -> Self {
Self::new()
}
}
impl Scale for ScaleContinuous {
fn set_default_locale(&mut self, locale: &crate::locale::Locale) {
if self.locale.is_none() {
self.locale = Some(locale.clone());
}
}
fn locale(&self) -> Option<&crate::locale::Locale> {
self.locale.as_ref()
}
fn format_value(&self, value: &Value) -> Option<String> {
let f = value.as_f64()?;
if !f.is_finite() {
return None;
}
// The built data holds the value in the scale's transformed space
// (e.g. `scale_y_log10` stores `log10(y)`), but `data-fvalue`/a
// tooltip template is meant to be the human-readable number —
// `y = 100` under log10, not `2` — the same inverse the break
// labels already apply (`breaks()` below calls `format_label`
// with `scale_transform.inverse(v)`, never raw `v`).
let f = self.scale_transform.inverse(f);
if !f.is_finite() {
return None;
}
Some(match &self.value_formatter {
Some(fmt) => fmt(f),
None => self.format_label(f),
})
}
fn aesthetic(&self) -> Aesthetic {
self.aesthetic.clone()
}
fn train(&mut self, values: &[Value]) {
for v in values {
if let Some(f) = v.as_f64() {
if f.is_finite() {
if f < self.min {
self.min = f;
}
if f > self.max {
self.max = f;
}
}
}
}
self.trained = true;
}
fn map(&self, value: &Value) -> f64 {
let f = match value.as_f64() {
Some(f) => f,
None => return 0.0,
};
// ±Inf means "panel edge" (ggplot2): -Inf → lower edge, +Inf → upper.
if f == f64::INFINITY {
return 1.0;
}
if f == f64::NEG_INFINITY {
return 0.0;
}
// An untrained scale (empty data) has no domain — centre everything
// rather than producing NaN.
if !self.trained || !self.min.is_finite() || !self.max.is_finite() {
return 0.5;
}
let (emin, emax) = self.expanded_range();
let range = emax - emin;
if range.abs() < f64::EPSILON {
0.5
} else {
(f - emin) / range
}
}
fn expanded_domain(&self) -> Option<(f64, f64)> {
if !self.trained || !self.min.is_finite() || !self.max.is_finite() {
return None;
}
let (a, b) = self.expanded_range();
if !(a.is_finite() && b.is_finite()) {
return None;
}
if (b - a).abs() < f64::EPSILON {
// A degenerate domain maps everything to the panel centre.
return Some((a - 0.5, b + 0.5));
}
Some((a, b))
}
fn breaks(&self) -> Vec<(f64, String)> {
if !self.trained || self.min > self.max {
return vec![];
}
// Use custom breaks if provided
if let Some(ref custom) = self.custom_breaks {
let localized = self
.localized_labels
.as_ref()
.map(|f| f(self.locale.as_ref()));
let custom_labels = localized.as_ref().or(self.custom_labels.as_ref());
return custom
.iter()
.enumerate()
.map(|(i, &v)| {
let pos = self.map(&Value::Float(v));
let label = if let Some(labels) = custom_labels {
labels
.get(i)
.cloned()
.unwrap_or_else(|| self.format_label(v))
} else {
self.format_label(self.scale_transform.inverse(v))
};
(pos, label)
})
.collect();
}
if super::util::is_degenerate_range(self.min, self.max) {
let label = self.format_label(self.scale_transform.inverse(self.min));
return vec![(0.5, label)];
}
// Extended-Wilkinson breaks over the data range (matching ggplot2's
// scales::extended_breaks), keeping those within the expanded (visible)
// range. Labels show the original (inverse-transformed) value.
let (emin, emax) = self.expanded_range();
let tol = (emax - emin).abs() * 1e-9;
let breaks: Vec<f64> = if self.scale_transform.uses_data_space_breaks() {
// Log/sqrt axes: pick round ticks in *data* space, then forward-
// transform them back onto the scale — not `extended_breaks`
// directly on the transformed range, which gives "nice" numbers
// in log/sqrt space that read as noise once inverse-transformed
// (half-decades like 316.23 under log10, squares like 625 under
// sqrt).
let data_min = self.scale_transform.inverse(self.min);
let data_max = self.scale_transform.inverse(self.max);
if data_min.is_finite() && data_max.is_finite() && data_max > data_min {
self.scale_transform
.breaks_in_data_space(data_min, data_max, 5)
.into_iter()
.map(|d| self.scale_transform.apply(d))
.filter(|&v| v.is_finite() && v >= emin - tol && v <= emax + tol)
.collect()
} else {
vec![]
}
} else {
extended_breaks(self.min, self.max, 5)
.into_iter()
.filter(|&v| v >= emin - tol && v <= emax + tol)
.collect()
};
let shown: Vec<f64> = breaks
.iter()
.map(|&v| self.scale_transform.inverse(v))
.collect();
// Without a custom formatter, label the breaks jointly so neighbours
// stay distinguishable on narrow ranges.
let labels: Vec<String> = match &self.label_formatter {
Some(f) => shown.iter().map(|&v| f(v)).collect(),
None => super::util::format_numbers_opt(&shown, self.locale.as_ref()),
};
breaks
.iter()
.zip(labels)
.map(|(&v, label)| (self.map(&Value::Float(v)), label))
.collect()
}
fn name(&self) -> &str {
&self.name
}
fn set_name(&mut self, name: &str) {
self.name = name.to_string();
}
fn transform(&self, value: &Value) -> Value {
self.scale_transform.transform_value(value)
}
fn sec_axis(&self) -> Option<&SecAxis> {
self.sec_axis.as_ref()
}
fn set_limits(&mut self, min: f64, max: f64) {
self.min = min;
self.max = max;
self.trained = true;
}
fn set_expand(&mut self, mult: f64, add: f64) {
self.expand = (mult, add, mult, add);
}
fn filter_limits(&self) -> Option<(f64, f64)> {
if self.filter_oob && self.trained {
Some((self.min, self.max))
} else {
None
}
}
fn domain(&self) -> Option<(f64, f64)> {
if self.trained {
Some((self.min, self.max))
} else {
None
}
}
fn axis_position_opposite(&self) -> bool {
self.position_opposite
}
fn clone_box(&self) -> Box<dyn Scale> {
Box::new(self.clone())
}
fn reset_training(&mut self) {
self.min = f64::INFINITY;
self.max = f64::NEG_INFINITY;
self.trained = false;
}
}