ggplot-rs 0.9.0

A Rust implementation of ggplot2's Grammar of Graphics
Documentation
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#[cfg(feature = "serde")]
pub mod config;
pub mod elements;
pub mod presets;

pub use elements::{ElementLine, ElementRect, ElementText};

/// Position of the legend.
#[derive(Clone, Debug)]
pub enum LegendPosition {
    Right,
    Left,
    Top,
    Bottom,
    None,
    /// Inside the panel at panel-relative coordinates (0..1, 0..1), like R's
    /// `legend.position = c(x, y)`. `(0, 0)` is bottom-left, `(1, 1)` top-right.
    Inside(f64, f64),
}

/// Whether title/subtitle/caption align to the panel or the whole plot width
/// (R's `plot.title.position` / `plot.caption.position`).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TitlePosition {
    #[default]
    Panel,
    Plot,
}

/// Corner for the `labs(tag)` label (R's `plot.tag.position`).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TagPosition {
    #[default]
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
}

/// Layout direction of the legend keys (R's `legend.direction`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LegendDirection {
    Vertical,
    Horizontal,
}

/// Plot margins (in pixels).
#[derive(Clone, Debug)]
pub struct Margin {
    pub top: f64,
    pub right: f64,
    pub bottom: f64,
    pub left: f64,
}

impl Default for Margin {
    fn default() -> Self {
        Margin {
            top: 10.0,
            right: 10.0,
            bottom: 10.0,
            left: 10.0,
        }
    }
}

/// Complete theme specification for a plot.
#[derive(Clone, Debug)]
pub struct Theme {
    // ── Existing fields ──
    pub text: ElementText,
    pub title: ElementText,
    pub axis_text_x: ElementText,
    pub axis_text_y: ElementText,
    pub axis_title_x: ElementText,
    pub axis_title_y: ElementText,
    pub axis_line: ElementLine,
    pub axis_ticks: ElementLine,
    pub panel_background: ElementRect,
    pub panel_grid_major: ElementLine,
    pub panel_grid_minor: ElementLine,
    pub plot_background: ElementRect,
    pub legend_position: LegendPosition,
    pub plot_margin: Margin,

    // ── New text elements ──
    pub subtitle: ElementText,
    pub caption: ElementText,
    pub legend_title: ElementText,
    pub legend_text: ElementText,
    pub strip_text: ElementText,

    // ── Per-axis optional overrides (None = inherit from parent) ──
    pub axis_line_x: Option<ElementLine>,
    pub axis_line_y: Option<ElementLine>,
    pub axis_ticks_x: Option<ElementLine>,
    pub axis_ticks_y: Option<ElementLine>,
    pub panel_grid_major_x: Option<ElementLine>,
    pub panel_grid_major_y: Option<ElementLine>,
    pub panel_grid_minor_x: Option<ElementLine>,
    pub panel_grid_minor_y: Option<ElementLine>,

    // ── New rect/line elements ──
    pub panel_border: ElementLine,
    pub legend_background: ElementRect,
    pub legend_key: ElementRect,
    pub strip_background: ElementRect,

    // ── Scalar spacing/sizing ──
    pub axis_ticks_length: f64,
    /// Number of rows to stagger x-axis tick labels across (R's
    /// `guide_axis(n.dodge = ...)`); 1 = no dodging.
    pub axis_text_x_dodge: usize,
    pub legend_key_width: f64,
    pub legend_key_height: f64,
    pub legend_spacing: f64,
    pub legend_margin: Margin,
    pub panel_spacing: f64,
    pub panel_spacing_x: Option<f64>,
    pub panel_spacing_y: Option<f64>,

    // ── Brand / primary color ──
    /// Optional brand color. When set, geoms that draw a single un-mapped series
    /// (no color/fill aesthetic) use it as their default instead of the geom's
    /// built-in color. Lets one render process serve multiple tenants' brands.
    pub primary: Option<(u8, u8, u8)>,

    // ── Advanced layout (R's theme() extras) ──
    /// Fix the panel's height:width ratio (R's `aspect.ratio`). `None` = free.
    pub aspect_ratio: Option<f64>,
    /// Draw gridlines on top of the data layers (R's `panel.ontop`).
    pub panel_ontop: bool,
    /// Draw minor tick marks between major ticks (R's `axis.minor.ticks`).
    pub axis_minor_ticks: bool,
    /// Whether title/subtitle/caption align to the panel or the whole plot
    /// (R's `plot.title.position` / `plot.caption.position`).
    pub title_position: TitlePosition,
    /// Corner for the `labs(tag)` label (R's `plot.tag.position`).
    pub tag_position: TagPosition,
    /// Legend key layout direction; `None` = auto from `legend_position`.
    pub legend_direction: Option<LegendDirection>,
}

impl Theme {
    /// Resolve the effective series color: the theme's brand color if set,
    /// otherwise the geom's own default.
    pub fn primary_or(&self, fallback: (u8, u8, u8)) -> (u8, u8, u8) {
        self.primary.unwrap_or(fallback)
    }

    /// Set the brand/primary color (builder style).
    pub fn with_primary(mut self, color: (u8, u8, u8)) -> Self {
        self.primary = Some(color);
        self
    }

    /// Resolve R-style element inheritance: text-child elements still at the
    /// default `family`/`color` inherit them from the root `text` element, so
    /// setting only `theme.text.family` restyles every text element. Child
    /// elements that already override a property keep it. Called once before
    /// rendering.
    pub fn resolve_inheritance(&mut self) {
        let root = self.text.clone();
        let def = ElementText::default();
        let children: [&mut ElementText; 10] = [
            &mut self.title,
            &mut self.subtitle,
            &mut self.caption,
            &mut self.axis_text_x,
            &mut self.axis_text_y,
            &mut self.axis_title_x,
            &mut self.axis_title_y,
            &mut self.legend_title,
            &mut self.legend_text,
            &mut self.strip_text,
        ];
        for el in children {
            if el.family == def.family {
                el.family = root.family.clone();
            }
            if el.color == def.color {
                el.color = root.color;
            }
        }
    }

    // ── Fallback accessors for Option fields ──

    pub fn get_axis_line_x(&self) -> &ElementLine {
        self.axis_line_x.as_ref().unwrap_or(&self.axis_line)
    }

    pub fn get_axis_line_y(&self) -> &ElementLine {
        self.axis_line_y.as_ref().unwrap_or(&self.axis_line)
    }

    pub fn get_axis_ticks_x(&self) -> &ElementLine {
        self.axis_ticks_x.as_ref().unwrap_or(&self.axis_ticks)
    }

    pub fn get_axis_ticks_y(&self) -> &ElementLine {
        self.axis_ticks_y.as_ref().unwrap_or(&self.axis_ticks)
    }

    pub fn get_panel_grid_major_x(&self) -> &ElementLine {
        self.panel_grid_major_x
            .as_ref()
            .unwrap_or(&self.panel_grid_major)
    }

    pub fn get_panel_grid_major_y(&self) -> &ElementLine {
        self.panel_grid_major_y
            .as_ref()
            .unwrap_or(&self.panel_grid_major)
    }

    pub fn get_panel_grid_minor_x(&self) -> &ElementLine {
        self.panel_grid_minor_x
            .as_ref()
            .unwrap_or(&self.panel_grid_minor)
    }

    pub fn get_panel_grid_minor_y(&self) -> &ElementLine {
        self.panel_grid_minor_y
            .as_ref()
            .unwrap_or(&self.panel_grid_minor)
    }

    pub fn get_panel_spacing_x(&self) -> f64 {
        self.panel_spacing_x.unwrap_or(self.panel_spacing)
    }

    pub fn get_panel_spacing_y(&self) -> f64 {
        self.panel_spacing_y.unwrap_or(self.panel_spacing)
    }

    // ── Existing setters ──

    pub fn set_axis_text_x(mut self, el: ElementText) -> Self {
        self.axis_text_x = el;
        self
    }

    pub fn set_axis_text_y(mut self, el: ElementText) -> Self {
        self.axis_text_y = el;
        self
    }

    pub fn set_axis_title_x(mut self, el: ElementText) -> Self {
        self.axis_title_x = el;
        self
    }

    pub fn set_axis_title_y(mut self, el: ElementText) -> Self {
        self.axis_title_y = el;
        self
    }

    pub fn set_axis_line(mut self, el: ElementLine) -> Self {
        self.axis_line = el;
        self
    }

    pub fn set_axis_ticks(mut self, el: ElementLine) -> Self {
        self.axis_ticks = el;
        self
    }

    pub fn set_panel_background(mut self, el: ElementRect) -> Self {
        self.panel_background = el;
        self
    }

    pub fn set_panel_grid_major(mut self, el: ElementLine) -> Self {
        self.panel_grid_major = el;
        self
    }

    pub fn set_panel_grid_minor(mut self, el: ElementLine) -> Self {
        self.panel_grid_minor = el;
        self
    }

    pub fn set_plot_background(mut self, el: ElementRect) -> Self {
        self.plot_background = el;
        self
    }

    pub fn set_legend_position(mut self, pos: LegendPosition) -> Self {
        self.legend_position = pos;
        self
    }

    pub fn set_plot_margin(mut self, margin: Margin) -> Self {
        self.plot_margin = margin;
        self
    }

    pub fn set_title(mut self, el: ElementText) -> Self {
        self.title = el;
        self
    }

    pub fn set_text(mut self, el: ElementText) -> Self {
        self.text = el;
        self
    }

    // ── New setters ──

    pub fn set_subtitle(mut self, el: ElementText) -> Self {
        self.subtitle = el;
        self
    }

    pub fn set_caption(mut self, el: ElementText) -> Self {
        self.caption = el;
        self
    }

    pub fn set_legend_title(mut self, el: ElementText) -> Self {
        self.legend_title = el;
        self
    }

    pub fn set_legend_text(mut self, el: ElementText) -> Self {
        self.legend_text = el;
        self
    }

    pub fn set_strip_text(mut self, el: ElementText) -> Self {
        self.strip_text = el;
        self
    }

    pub fn set_axis_line_x(mut self, el: Option<ElementLine>) -> Self {
        self.axis_line_x = el;
        self
    }

    pub fn set_axis_line_y(mut self, el: Option<ElementLine>) -> Self {
        self.axis_line_y = el;
        self
    }

    pub fn set_axis_ticks_x(mut self, el: Option<ElementLine>) -> Self {
        self.axis_ticks_x = el;
        self
    }

    pub fn set_axis_ticks_y(mut self, el: Option<ElementLine>) -> Self {
        self.axis_ticks_y = el;
        self
    }

    pub fn set_panel_grid_major_x(mut self, el: Option<ElementLine>) -> Self {
        self.panel_grid_major_x = el;
        self
    }

    pub fn set_panel_grid_major_y(mut self, el: Option<ElementLine>) -> Self {
        self.panel_grid_major_y = el;
        self
    }

    pub fn set_panel_grid_minor_x(mut self, el: Option<ElementLine>) -> Self {
        self.panel_grid_minor_x = el;
        self
    }

    pub fn set_panel_grid_minor_y(mut self, el: Option<ElementLine>) -> Self {
        self.panel_grid_minor_y = el;
        self
    }

    pub fn set_panel_border(mut self, el: ElementLine) -> Self {
        self.panel_border = el;
        self
    }

    pub fn set_legend_background(mut self, el: ElementRect) -> Self {
        self.legend_background = el;
        self
    }

    pub fn set_legend_key(mut self, el: ElementRect) -> Self {
        self.legend_key = el;
        self
    }

    pub fn set_strip_background(mut self, el: ElementRect) -> Self {
        self.strip_background = el;
        self
    }

    pub fn set_axis_ticks_length(mut self, val: f64) -> Self {
        self.axis_ticks_length = val;
        self
    }

    pub fn set_legend_key_width(mut self, val: f64) -> Self {
        self.legend_key_width = val;
        self
    }

    pub fn set_legend_key_height(mut self, val: f64) -> Self {
        self.legend_key_height = val;
        self
    }

    pub fn set_legend_spacing(mut self, val: f64) -> Self {
        self.legend_spacing = val;
        self
    }

    pub fn set_legend_margin(mut self, margin: Margin) -> Self {
        self.legend_margin = margin;
        self
    }

    pub fn set_panel_spacing(mut self, val: f64) -> Self {
        self.panel_spacing = val;
        self
    }

    pub fn set_panel_spacing_x(mut self, val: Option<f64>) -> Self {
        self.panel_spacing_x = val;
        self
    }

    pub fn set_panel_spacing_y(mut self, val: Option<f64>) -> Self {
        self.panel_spacing_y = val;
        self
    }

    /// Apply incremental theme modifications.
    /// Only fields that are `Some` in the update are applied.
    pub fn update(mut self, upd: ThemeUpdate) -> Self {
        if let Some(v) = upd.text {
            self.text = v;
        }
        if let Some(v) = upd.title {
            self.title = v;
        }
        if let Some(v) = upd.subtitle {
            self.subtitle = v;
        }
        if let Some(v) = upd.caption {
            self.caption = v;
        }
        if let Some(v) = upd.axis_text_x {
            self.axis_text_x = v;
        }
        if let Some(v) = upd.axis_text_y {
            self.axis_text_y = v;
        }
        if let Some(v) = upd.axis_title_x {
            self.axis_title_x = v;
        }
        if let Some(v) = upd.axis_title_y {
            self.axis_title_y = v;
        }
        if let Some(v) = upd.axis_line {
            self.axis_line = v;
        }
        if let Some(v) = upd.axis_ticks {
            self.axis_ticks = v;
        }
        if let Some(v) = upd.panel_background {
            self.panel_background = v;
        }
        if let Some(v) = upd.panel_grid_major {
            self.panel_grid_major = v;
        }
        if let Some(v) = upd.panel_grid_minor {
            self.panel_grid_minor = v;
        }
        if let Some(v) = upd.panel_border {
            self.panel_border = v;
        }
        if let Some(v) = upd.plot_background {
            self.plot_background = v;
        }
        if let Some(v) = upd.legend_position {
            self.legend_position = v;
        }
        if let Some(v) = upd.legend_title {
            self.legend_title = v;
        }
        if let Some(v) = upd.legend_text {
            self.legend_text = v;
        }
        if let Some(v) = upd.legend_background {
            self.legend_background = v;
        }
        if let Some(v) = upd.strip_text {
            self.strip_text = v;
        }
        if let Some(v) = upd.strip_background {
            self.strip_background = v;
        }
        if let Some(v) = upd.plot_margin {
            self.plot_margin = v;
        }
        self
    }
}

/// Incremental theme modifications. All fields are optional — only `Some` values are applied.
/// Like R's `theme(axis.text.x = element_text(...))`.
#[derive(Clone, Debug, Default)]
pub struct ThemeUpdate {
    pub text: Option<ElementText>,
    pub title: Option<ElementText>,
    pub subtitle: Option<ElementText>,
    pub caption: Option<ElementText>,
    pub axis_text_x: Option<ElementText>,
    pub axis_text_y: Option<ElementText>,
    pub axis_title_x: Option<ElementText>,
    pub axis_title_y: Option<ElementText>,
    pub axis_line: Option<ElementLine>,
    pub axis_ticks: Option<ElementLine>,
    pub panel_background: Option<ElementRect>,
    pub panel_grid_major: Option<ElementLine>,
    pub panel_grid_minor: Option<ElementLine>,
    pub panel_border: Option<ElementLine>,
    pub plot_background: Option<ElementRect>,
    pub legend_position: Option<LegendPosition>,
    pub legend_title: Option<ElementText>,
    pub legend_text: Option<ElementText>,
    pub legend_background: Option<ElementRect>,
    pub strip_text: Option<ElementText>,
    pub strip_background: Option<ElementRect>,
    pub plot_margin: Option<Margin>,
}

impl Default for Theme {
    fn default() -> Self {
        presets::theme_gray()
    }
}