rizzma 1.14.1

A Rust reimplementation of the good parts of matplotlib/pyplot, with first-class wasm support.
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
//! Typed runtime configuration ([`RcParams`]), mirroring matplotlib's `rcParams`.
//!
//! matplotlib exposes ~300 string-keyed configuration entries. This module
//! captures a curated, strongly-typed subset of the most useful ones, grouped
//! by the area they configure (figure, axes, lines, ticks, font, and grid).
//! Field names follow matplotlib's dotted keys with dots replaced by
//! underscores (e.g. `figure.figsize` becomes [`RcParams::figure_figsize`]).
//!
//! [`RcParams::default`] (aliased as [`RcParams::matplotlib`]) returns
//! matplotlib's documented default values. The struct (de)serializes via serde,
//! so a configuration can be round-tripped through JSON or any other serde
//! format.

use crate::core::color::{DEFAULT_COLOR_CYCLE, Rgba};
use crate::render::{CapStyle, JoinStyle};

/// The direction tick marks point relative to the axes.
///
/// Mirrors matplotlib's `xtick.direction` / `ytick.direction` setting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TickDirection {
    /// Ticks point outward, away from the plotting area (matplotlib's default).
    Out,
    /// Ticks point inward, into the plotting area.
    In,
    /// Ticks straddle the axis spine, pointing both ways.
    InOut,
}

/// Where an axes' grid draws among its artists: matplotlib's
/// `axes.axisbelow`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AxisBelow {
    /// Beneath every artist (matplotlib's `True`, grid zorder 0.5).
    Below,
    /// Above patches, fills and scatters, below lines and their markers
    /// (matplotlib's default `"line"`, grid zorder 1.5).
    #[default]
    Line,
    /// Above every artist (matplotlib's `False`, grid zorder 2.5).
    Above,
}

impl AxisBelow {
    /// The grid's zorder: matplotlib's 0.5, 1.5 or 2.5.
    #[must_use]
    pub fn zorder(self) -> f64 {
        match self {
            AxisBelow::Below => 0.5,
            AxisBelow::Line => 1.5,
            AxisBelow::Above => 2.5,
        }
    }
}

/// How SVG output writes text: matplotlib's `svg.fonttype`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SvgFontType {
    /// Glyph outlines, drawn as paths: the text looks the same everywhere but
    /// cannot be searched or selected (matplotlib's default `"path"`).
    #[default]
    Path,
    /// Native `<text>` elements naming the font family: smaller files whose
    /// text can be searched and selected, drawn in whatever font the viewer
    /// resolves (matplotlib's `"none"`). Mathtext still draws as paths.
    None,
}

/// Build the default ten-color property cycle (matplotlib's `tab10`).
///
/// Resolves the hex strings in [`DEFAULT_COLOR_CYCLE`] into [`Rgba`] values.
#[must_use]
fn default_prop_cycle() -> Vec<Rgba> {
    DEFAULT_COLOR_CYCLE
        .iter()
        .map(|hex| Rgba::from_hex(hex).expect("DEFAULT_COLOR_CYCLE entries are valid hex"))
        .collect()
}

/// A typed subset of matplotlib's `rcParams` runtime configuration.
///
/// Fields are grouped by the area they configure. Construct the matplotlib
/// defaults with [`RcParams::default`] or its alias [`RcParams::matplotlib`],
/// and override individual fields as needed. Use [`RcParams::merge`] to layer a
/// set of overrides on top of an existing configuration.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RcParams {
    // --- figure ---
    /// Default figure size in inches, as `(width, height)` (`figure.figsize`).
    pub figure_figsize: (f64, f64),
    /// Figure resolution in dots per inch (`figure.dpi`).
    pub figure_dpi: f64,
    /// Figure background color (`figure.facecolor`).
    pub figure_facecolor: Rgba,
    /// Resolution in dots per inch used when saving figures (`savefig.dpi`).
    pub savefig_dpi: f64,

    // --- axes ---
    /// Axes background color (`axes.facecolor`).
    pub axes_facecolor: Rgba,
    /// Color of the axes spines (`axes.edgecolor`).
    pub axes_edgecolor: Rgba,
    /// Width of the axes spines in points (`axes.linewidth`).
    pub axes_linewidth: f64,
    /// Whether to show the grid by default (`axes.grid`).
    pub axes_grid: bool,
    /// Where the grid draws among the artists (`axes.axisbelow`): by default
    /// above fills and scatters, below lines and markers.
    #[serde(default, skip_serializing_if = "is_default_axisbelow")]
    pub axes_axisbelow: AxisBelow,
    /// Log-axis powers whose exponent is below this in magnitude are labelled
    /// as plain numbers rather than `base^n` (`axes.formatter.min_exponent`;
    /// default 0, every power as an exponent).
    #[serde(default, skip_serializing_if = "is_zero")]
    pub axes_formatter_min_exponent: i32,
    /// Cap style of solid lines' ends (`lines.solid_capstyle`, projecting).
    #[serde(
        default = "default_solid_capstyle",
        skip_serializing_if = "is_default_solid_capstyle"
    )]
    pub lines_solid_capstyle: CapStyle,
    /// Join style of solid lines' corners (`lines.solid_joinstyle`, round).
    #[serde(default = "round_join", skip_serializing_if = "is_round_join")]
    pub lines_solid_joinstyle: JoinStyle,
    /// Cap style of dashed lines' dashes (`lines.dash_capstyle`, butt).
    #[serde(default, skip_serializing_if = "is_butt_cap")]
    pub lines_dash_capstyle: CapStyle,
    /// Join style of dashed lines' corners (`lines.dash_joinstyle`, round).
    #[serde(default = "round_join", skip_serializing_if = "is_round_join")]
    pub lines_dash_joinstyle: JoinStyle,
    /// Font size of the axes title in points (`axes.titlesize`).
    pub axes_titlesize: f64,
    /// Padding above the axes title in points (`axes.titlepad`).
    pub axes_titlepad: f64,
    /// Font size of the x/y axis labels in points (`axes.labelsize`).
    pub axes_labelsize: f64,
    /// Padding between tick labels and axis labels in points (`axes.labelpad`).
    pub axes_labelpad: f64,
    /// The property cycle of colors used for successive plots
    /// (`axes.prop_cycle`); defaults to the ten-color `tab10` cycle.
    pub axes_prop_cycle: Vec<Rgba>,

    // --- lines ---
    /// Default line width in points (`lines.linewidth`).
    pub lines_linewidth: f64,
    /// Default marker size in points (`lines.markersize`).
    pub lines_markersize: f64,

    // --- ticks ---
    /// Font size of x-axis tick labels in points (`xtick.labelsize`).
    pub xtick_labelsize: f64,
    /// Font size of y-axis tick labels in points (`ytick.labelsize`).
    pub ytick_labelsize: f64,
    /// Length of major x-axis ticks in points (`xtick.major.size`).
    pub xtick_major_size: f64,
    /// Length of major y-axis ticks in points (`ytick.major.size`).
    pub ytick_major_size: f64,
    /// Padding between x-axis major ticks and labels in points
    /// (`xtick.major.pad`).
    pub xtick_major_pad: f64,
    /// Padding between y-axis major ticks and labels in points
    /// (`ytick.major.pad`).
    pub ytick_major_pad: f64,
    /// Direction x-axis ticks point (`xtick.direction`).
    pub xtick_direction: TickDirection,
    /// Direction y-axis ticks point (`ytick.direction`).
    pub ytick_direction: TickDirection,

    // --- font ---
    /// Default font size in points (`font.size`).
    pub font_size: f64,
    /// Default font family (`font.family`).
    pub font_family: String,

    // --- grid ---
    /// Grid line color (`grid.color`).
    pub grid_color: Rgba,
    /// Grid line width in points (`grid.linewidth`).
    pub grid_linewidth: f64,
    /// Grid line opacity (`grid.alpha`).
    pub grid_alpha: f64,

    // --- legend ---
    /// Legend box background color (`legend.facecolor`).
    pub legend_facecolor: Rgba,
    /// Legend box border color (`legend.edgecolor`).
    pub legend_edgecolor: Rgba,
    /// Legend label text color (`legend.labelcolor`).
    pub legend_labelcolor: Rgba,

    // --- text ---
    /// Default ink color for titles, axis/tick labels, and annotations
    /// (`text.color`). Also seeds each axis' spine/tick ink together with
    /// [`axes_edgecolor`](Self::axes_edgecolor).
    pub text_color: Rgba,

    // --- path ---
    /// Merge nearly collinear segments of long lines before drawing
    /// (`path.simplify`). Lines of 1000 or more vertices are simplified in
    /// display space, matplotlib's `PathSimplifier`; shorter lines are drawn
    /// as given.
    #[serde(
        default = "default_path_simplify",
        skip_serializing_if = "is_default_path_simplify"
    )]
    pub path_simplify: bool,
    /// How far, in pixels, a vertex may stray from the segment being built
    /// and still merge into it (`path.simplify_threshold`, default 1/9).
    #[serde(
        default = "default_path_simplify_threshold",
        skip_serializing_if = "is_default_path_simplify_threshold"
    )]
    pub path_simplify_threshold: f64,

    // --- svg ---
    /// How SVG output writes text (`svg.fonttype`). An output setting, so
    /// portable figures do not carry it.
    #[serde(skip)]
    pub svg_fonttype: SvgFontType,
}

fn is_zero(value: &i32) -> bool {
    *value == 0
}

fn default_solid_capstyle() -> CapStyle {
    CapStyle::Projecting
}

fn is_default_solid_capstyle(cap: &CapStyle) -> bool {
    *cap == CapStyle::Projecting
}

fn is_butt_cap(cap: &CapStyle) -> bool {
    *cap == CapStyle::Butt
}

fn round_join() -> JoinStyle {
    JoinStyle::Round
}

fn is_round_join(join: &JoinStyle) -> bool {
    *join == JoinStyle::Round
}

fn is_default_axisbelow(axisbelow: &AxisBelow) -> bool {
    *axisbelow == AxisBelow::default()
}

fn default_path_simplify() -> bool {
    true
}

fn is_default_path_simplify(on: &bool) -> bool {
    *on
}

fn default_path_simplify_threshold() -> f64 {
    1.0 / 9.0
}

fn is_default_path_simplify_threshold(threshold: &f64) -> bool {
    *threshold == default_path_simplify_threshold()
}

impl Default for RcParams {
    /// matplotlib's documented default `rcParams`.
    fn default() -> Self {
        Self {
            figure_figsize: (6.4, 4.8),
            figure_dpi: 100.0,
            figure_facecolor: Rgba::WHITE,
            savefig_dpi: 100.0,

            axes_facecolor: Rgba::WHITE,
            axes_edgecolor: Rgba::BLACK,
            axes_linewidth: 0.8,
            axes_grid: false,
            axes_axisbelow: AxisBelow::Line,
            axes_formatter_min_exponent: 0,
            lines_solid_capstyle: CapStyle::Projecting,
            lines_solid_joinstyle: JoinStyle::Round,
            lines_dash_capstyle: CapStyle::Butt,
            lines_dash_joinstyle: JoinStyle::Round,
            axes_titlesize: 12.0,
            axes_titlepad: 6.0,
            axes_labelsize: 10.0,
            axes_labelpad: 4.0,
            axes_prop_cycle: default_prop_cycle(),

            lines_linewidth: 1.5,
            lines_markersize: 6.0,

            xtick_labelsize: 10.0,
            ytick_labelsize: 10.0,
            xtick_major_size: 3.5,
            ytick_major_size: 3.5,
            xtick_major_pad: 3.5,
            ytick_major_pad: 3.5,
            xtick_direction: TickDirection::Out,
            ytick_direction: TickDirection::Out,

            font_size: 10.0,
            font_family: "DejaVu Sans".to_string(),

            // ~0.85 gray; built from 8-bit channels so it round-trips through
            // the hex serialization of `Rgba` exactly.
            grid_color: Rgba::from_u8(217, 217, 217, 255),
            grid_linewidth: 0.8,
            grid_alpha: 1.0,

            legend_facecolor: Rgba::WHITE,
            legend_edgecolor: Rgba::from_u8(128, 128, 128, 255),
            legend_labelcolor: Rgba::BLACK,

            text_color: Rgba::BLACK,

            path_simplify: default_path_simplify(),
            path_simplify_threshold: default_path_simplify_threshold(),

            svg_fonttype: SvgFontType::Path,
        }
    }
}

impl RcParams {
    /// matplotlib's default configuration; an alias for [`RcParams::default`].
    #[must_use]
    pub fn matplotlib() -> Self {
        Self::default()
    }

    /// A dark-theme preset: dark figure and axes backgrounds with light
    /// foreground colors. Otherwise identical to [`RcParams::default`].
    #[must_use]
    pub fn dark() -> Self {
        // 8-bit-derived so the preset round-trips through hex serialization.
        let dark = Rgba::from_u8(31, 31, 31, 255);
        let panel = Rgba::from_u8(45, 45, 45, 255);
        let light = Rgba::from_u8(230, 230, 230, 255);
        Self {
            figure_facecolor: dark,
            axes_facecolor: dark,
            axes_edgecolor: light,
            grid_color: Rgba::from_u8(77, 77, 77, 255),
            legend_facecolor: panel,
            legend_edgecolor: Rgba::from_u8(160, 160, 160, 255),
            legend_labelcolor: light,
            text_color: light,
            ..Self::default()
        }
    }

    /// Resolve the color at index `i` of [`Self::axes_prop_cycle`], wrapping
    /// modulo the cycle length. Returns [`None`] only if the cycle is empty.
    #[must_use]
    pub fn cycle_color(&self, i: usize) -> Option<Rgba> {
        let cycle = &self.axes_prop_cycle;
        if cycle.is_empty() {
            return None;
        }
        Some(cycle[i % cycle.len()])
    }

    /// Layer `overrides` on top of `self`, returning the combined configuration.
    ///
    /// Each field of the result is taken from `overrides` where it differs from
    /// the default, and from `self` otherwise. This makes it easy to express a
    /// sparse set of changes: build them on top of [`RcParams::default`] and
    /// merge them onto a base configuration.
    #[must_use]
    pub fn merge(&self, overrides: &RcParams) -> RcParams {
        let base = RcParams::default();
        // Field-by-field: prefer the override when it diverges from the default.
        let mut out = self.clone();
        macro_rules! merge_field {
            ($field:ident) => {
                if overrides.$field != base.$field {
                    out.$field = overrides.$field.clone();
                }
            };
        }
        merge_field!(figure_figsize);
        merge_field!(figure_dpi);
        merge_field!(figure_facecolor);
        merge_field!(savefig_dpi);
        merge_field!(axes_facecolor);
        merge_field!(axes_edgecolor);
        merge_field!(axes_linewidth);
        merge_field!(axes_grid);
        merge_field!(axes_axisbelow);
        merge_field!(axes_formatter_min_exponent);
        merge_field!(lines_solid_capstyle);
        merge_field!(lines_solid_joinstyle);
        merge_field!(lines_dash_capstyle);
        merge_field!(lines_dash_joinstyle);
        merge_field!(axes_titlesize);
        merge_field!(axes_titlepad);
        merge_field!(axes_labelsize);
        merge_field!(axes_labelpad);
        merge_field!(axes_prop_cycle);
        merge_field!(lines_linewidth);
        merge_field!(lines_markersize);
        merge_field!(xtick_labelsize);
        merge_field!(ytick_labelsize);
        merge_field!(xtick_major_size);
        merge_field!(ytick_major_size);
        merge_field!(xtick_major_pad);
        merge_field!(ytick_major_pad);
        merge_field!(xtick_direction);
        merge_field!(ytick_direction);
        merge_field!(font_size);
        merge_field!(font_family);
        merge_field!(grid_color);
        merge_field!(grid_linewidth);
        merge_field!(grid_alpha);
        merge_field!(legend_facecolor);
        merge_field!(legend_edgecolor);
        merge_field!(legend_labelcolor);
        merge_field!(text_color);
        merge_field!(svg_fonttype);
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_has_documented_values() {
        let rc = RcParams::default();
        assert_eq!(rc.figure_figsize, (6.4, 4.8));
        assert_eq!(rc.figure_dpi, 100.0);
        assert_eq!(rc.savefig_dpi, 100.0);
        assert_eq!(rc.figure_facecolor, Rgba::WHITE);
        assert_eq!(rc.axes_facecolor, Rgba::WHITE);
        assert_eq!(rc.axes_edgecolor, Rgba::BLACK);
        assert_eq!(rc.axes_linewidth, 0.8);
        assert!(!rc.axes_grid);
        assert_eq!(rc.axes_titlesize, 12.0);
        assert_eq!(rc.axes_titlepad, 6.0);
        assert_eq!(rc.axes_labelsize, 10.0);
        assert_eq!(rc.axes_labelpad, 4.0);
        assert_eq!(rc.lines_linewidth, 1.5);
        assert_eq!(rc.lines_markersize, 6.0);
        assert_eq!(rc.xtick_labelsize, 10.0);
        assert_eq!(rc.ytick_labelsize, 10.0);
        assert_eq!(rc.xtick_major_size, 3.5);
        assert_eq!(rc.ytick_major_size, 3.5);
        assert_eq!(rc.xtick_major_pad, 3.5);
        assert_eq!(rc.ytick_major_pad, 3.5);
        assert_eq!(rc.xtick_direction, TickDirection::Out);
        assert_eq!(rc.font_size, 10.0);
        assert_eq!(rc.font_family, "DejaVu Sans");
        assert_eq!(rc.grid_linewidth, 0.8);
        assert_eq!(rc.grid_alpha, 1.0);
        assert_eq!(rc.legend_facecolor, Rgba::WHITE);
        assert_eq!(rc.legend_edgecolor, Rgba::from_u8(128, 128, 128, 255));
        assert_eq!(rc.legend_labelcolor, Rgba::BLACK);
        assert_eq!(rc.text_color, Rgba::BLACK);
    }

    #[test]
    fn matplotlib_aliases_default() {
        assert_eq!(RcParams::matplotlib(), RcParams::default());
    }

    #[test]
    fn default_prop_cycle_has_ten_colors() {
        let rc = RcParams::default();
        assert_eq!(rc.axes_prop_cycle.len(), 10);
        // matplotlib's C0 is tab:blue, #1f77b4.
        assert_eq!(rc.axes_prop_cycle[0], Rgba::from_hex("#1f77b4").unwrap());
    }

    #[test]
    fn cycle_color_wraps() {
        let rc = RcParams::default();
        assert_eq!(rc.cycle_color(0), Rgba::from_hex("#1f77b4"));
        assert_eq!(rc.cycle_color(10), rc.cycle_color(0));
    }

    #[test]
    fn json_round_trip() {
        let rc = RcParams::default();
        let json = serde_json::to_string(&rc).expect("serialize");
        let back: RcParams = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(rc, back);
    }

    #[test]
    fn dark_preset_round_trips() {
        let rc = RcParams::dark();
        assert_ne!(rc.figure_facecolor, Rgba::WHITE);
        let json = serde_json::to_string(&rc).expect("serialize");
        let back: RcParams = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(rc, back);
    }

    #[test]
    fn merge_applies_overrides() {
        let base = RcParams::default();
        let overrides = RcParams {
            lines_linewidth: 3.0,
            axes_grid: true,
            ..RcParams::default()
        };
        let merged = base.merge(&overrides);
        assert_eq!(merged.lines_linewidth, 3.0);
        assert!(merged.axes_grid);
        // Untouched fields keep the base value.
        assert_eq!(merged.figure_dpi, base.figure_dpi);
    }
}