plotpy 1.23.0

Rust plotting library using Python (Matplotlib)
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
use super::{generate_list, generate_nested_list, matrix_to_array, AsMatrix, GraphMaker};
use num_traits::Num;
use std::fmt::Write;

/// Draw a box and whisker plot
///
/// Each box shows the median, quartiles (Q1/Q3), and whiskers (default: 1.5 × IQR).
/// Outlier points (fliers) are drawn beyond the whiskers.
///
/// Two data formats are supported:
/// - **Nested list** (via [`draw`](Self::draw)): one box per sub-array (variable group sizes)
/// - **2D matrix** (via [`draw_mat`](Self::draw_mat)): one box per column (equal group sizes)
///
/// [See Matplotlib's documentation](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
///
/// # Examples
///
/// ## Data as a nested list
///
/// ```
/// use plotpy::{Boxplot, Plot, StrError};
///
/// fn main() -> Result<(), StrError> {
///     // data (as a nested list)
///     let data = vec![
///         vec![1, 2, 3, 4, 5],              // A
///         vec![2, 3, 4, 5, 6, 7, 8, 9, 10], // B
///         vec![3, 4, 5, 6],                 // C
///         vec![4, 5, 6, 7, 8, 9, 10],       // D
///         vec![5, 6, 7],                    // E
///     ];
///
///     // x ticks and labels
///     let n = data.len();
///     let ticks: Vec<_> = (1..(n + 1)).into_iter().collect();
///     let labels = ["A", "B", "C", "D", "E"];
///
///     // boxplot object and options
///     let mut boxes = Boxplot::new();
///     boxes.draw(&data);
///
///     // save figure
///     let mut plot = Plot::new();
///     plot.add(&boxes)
///         .set_title("boxplot documentation test")
///         .set_ticks_x_labels(&ticks, &labels)
///         .save("/tmp/plotpy/doc_tests/doc_boxplot_2.svg")?;
///     Ok(())
/// }
/// ```
///
/// ![doc_boxplot_2.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/doc_boxplot_2.svg)
///
/// ## Data as a 2D array
///
/// ```
/// use plotpy::{Boxplot, Plot, StrError};
///
/// fn main() -> Result<(), StrError> {
///     // data (as a 2D array/matrix)
///     let data = vec![
///         //   A  B  C  D  E
///         vec![1, 2, 3, 4, 5],
///         vec![2, 3, 4, 5, 6],
///         vec![3, 4, 5, 6, 7],
///         vec![4, 5, 6, 7, 8],
///         vec![5, 6, 7, 8, 9],
///         vec![6, 7, 8, 9, 10],
///         vec![14, 14, 14, 14, 14], // fliers
///     ];
///
///     // x ticks and labels
///     let ncol = data[0].len();
///     let ticks: Vec<_> = (1..(ncol + 1)).into_iter().collect();
///     let labels = ["A", "B", "C", "D", "E"];
///
///     // boxplot object and options
///     let mut boxes = Boxplot::new();
///     boxes.draw_mat(&data);
///
///     // save figure
///     let mut plot = Plot::new();
///     plot.add(&boxes)
///         .set_title("boxplot documentation test")
///         .set_ticks_x_labels(&ticks, &labels)
///         .save("/tmp/plotpy/doc_tests/doc_boxplot_1.svg")?;
///     Ok(())
/// }
/// ```
///
/// ![doc_boxplot_1.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/doc_boxplot_1.svg)
///
/// ## More examples
///
/// See also integration test in the **tests** directory.
pub struct Boxplot {
    symbol: String,        // The default symbol for flier (outlier) points.
    horizontal: bool,      // Horizontal boxplot (default is false)
    whisker: Option<f64>,  // The position of the whiskers
    positions: Vec<f64>,   // The positions of the boxes
    width: Option<f64>,    // The width of the boxes
    no_fliers: bool,       // Disables fliers
    patch_artist: bool,    // Enables the use of Patch artist to draw boxes
    median_props: String,  // The properties of the median
    box_props: String,     // The properties of the box
    whisker_props: String, // The properties of the whisker
    extra: String,         // Extra commands (comma separated)
    buffer: String,        // Buffer
}

impl Boxplot {
    /// Creates a new Boxplot object
    pub fn new() -> Self {
        Boxplot {
            symbol: String::new(),
            horizontal: false,
            whisker: None,
            positions: Vec::new(),
            width: None,
            no_fliers: false,
            patch_artist: false,
            median_props: String::new(),
            box_props: String::new(),
            whisker_props: String::new(),
            extra: String::new(),
            buffer: String::new(),
        }
    }

    /// Draws the box plot given a nested list of values
    ///
    /// Each inner `Vec` produces one box. Groups can have different sizes.
    ///
    /// # Input
    ///
    /// * `data` -- a sequence of 1D arrays; one box is drawn per sub-array
    ///
    /// See also: [`draw_mat`](Self::draw_mat) for matrix-oriented data
    pub fn draw<T>(&mut self, data: &Vec<Vec<T>>)
    where
        T: std::fmt::Display + Num,
    {
        generate_nested_list(&mut self.buffer, "x", data);
        if self.positions.len() > 0 {
            generate_list(&mut self.buffer, "positions", self.positions.as_slice());
        }
        let opt = self.options();
        write!(&mut self.buffer, "p=plt.boxplot(x{})\n", &opt).unwrap();
    }

    /// Draws the box plot given a 2D matrix of values
    ///
    /// Each **column** of the matrix produces one box. All groups must have
    /// the same number of rows (unlike [`draw`](Self::draw) which allows variable sizes).
    ///
    /// # Input
    ///
    /// * `data` -- a 2D matrix (rows = observations, columns = groups)
    pub fn draw_mat<'a, T, U>(&mut self, data: &'a T)
    where
        T: AsMatrix<'a, U>,
        U: 'a + std::fmt::Display + Num,
    {
        matrix_to_array(&mut self.buffer, "x", data);
        if self.positions.len() > 0 {
            generate_list(&mut self.buffer, "positions", self.positions.as_slice());
        }
        let opt = self.options();
        write!(&mut self.buffer, "p=plt.boxplot(x{})\n", &opt).unwrap();
    }

    /// Sets the [marker symbol](https://matplotlib.org/stable/api/markers_api.html) for outlier points (fliers)
    ///
    /// Example: `"b+"` for blue crosses, `"rx"` for red x-marks.
    pub fn set_symbol(&mut self, symbol: &str) -> &mut Self {
        self.symbol = symbol.to_string();
        self
    }

    /// Enables drawing horizontal boxes instead of vertical
    ///
    /// When `true`, the boxplot is rotated 90° clockwise so categories
    /// appear on the y-axis.
    pub fn set_horizontal(&mut self, flag: bool) -> &mut Self {
        self.horizontal = flag;
        self
    }

    /// Sets the position of the whiskers
    ///
    /// The default value of whisker = 1.5 corresponds to Tukey's original definition of boxplots.
    ///
    /// [See Matplotlib's documentation](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    pub fn set_whisker(&mut self, whisker: f64) -> &mut Self {
        self.whisker = Some(whisker);
        self
    }

    /// Overrides the default x-axis positions of the boxes
    ///
    /// By default boxes are placed at sequential integer positions (1, 2, 3, …).
    /// Use this to spread or group boxes at custom locations.
    pub fn set_positions(&mut self, positions: &[f64]) -> &mut Self {
        self.positions = positions.to_vec();
        self
    }

    /// Sets the width of each box (default: 0.5)
    pub fn set_width(&mut self, width: f64) -> &mut Self {
        self.width = Some(width);
        self
    }

    /// Hides outlier points (fliers) when `true`
    ///
    /// Outliers are data points beyond 1.5 × IQR from the quartiles.
    pub fn set_no_fliers(&mut self, flag: bool) -> &mut Self {
        self.no_fliers = flag;
        self
    }

    /// Enables Patch artist drawing so boxes can be filled with color
    ///
    /// By default Matplotlib uses Line2D to draw boxes. Setting this to `true`
    /// allows [`set_boxprops`](Self::set_boxprops) to fill boxes with color.
    pub fn set_patch_artist(&mut self, flag: bool) -> &mut Self {
        self.patch_artist = flag;
        self
    }

    /// Sets the median line properties as a Python dict string
    ///
    /// Example: `"{'color': 'red', 'linewidth': 2}"`
    ///
    /// [See Matplotlib's documentation](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    pub fn set_medianprops(&mut self, props: &str) -> &mut Self {
        self.median_props = props.to_string();
        self
    }

    /// Sets the box body properties as a Python dict string
    ///
    /// Requires [`set_patch_artist(true)`](Self::set_patch_artist).
    /// Example: `"{'facecolor': 'lightblue', 'edgecolor': 'black'}"`
    pub fn set_boxprops(&mut self, props: &str) -> &mut Self {
        self.box_props = props.to_string();
        self
    }

    /// Sets the whisker line properties as a Python dict string
    ///
    /// Example: `"{'linestyle': '--', 'color': 'gray'}"`
    pub fn set_whiskerprops(&mut self, props: &str) -> &mut Self {
        self.whisker_props = props.to_string();
        self
    }

    /// Sets extra matplotlib commands (comma separated)
    ///
    /// **Important:** The extra commands must be comma separated. For example:
    ///
    /// ```text
    /// param1=123,param2='hello'
    /// ```
    ///
    /// [See Matplotlib's documentation for extra parameters](https://matplotlib.org/3.6.3/api/_as_gen/matplotlib.pyplot.boxplot.html)
    pub fn set_extra(&mut self, extra: &str) -> &mut Self {
        self.extra = extra.to_string();
        self
    }

    /// Returns options (optional parameters) for boxplot
    fn options(&self) -> String {
        let mut opt = String::new();
        if self.symbol != "" {
            write!(&mut opt, ",sym=r'{}'", self.symbol).unwrap();
        }
        if self.horizontal {
            write!(&mut opt, ",vert=False").unwrap();
        }
        if self.whisker != None {
            write!(&mut opt, ",whis={}", self.whisker.unwrap()).unwrap();
        }
        if self.positions.len() > 0 {
            write!(&mut opt, ",positions=positions").unwrap();
        }
        if self.width != None {
            write!(&mut opt, ",widths={}", self.width.unwrap()).unwrap();
        }
        if self.no_fliers {
            write!(&mut opt, ",showfliers=False").unwrap();
        }
        if self.patch_artist {
            write!(&mut opt, ",patch_artist=True").unwrap();
        }
        if self.median_props != "" {
            write!(&mut opt, ",medianprops={}", self.median_props).unwrap();
        }
        if self.box_props != "" {
            write!(&mut opt, ",boxprops={}", self.box_props).unwrap();
        }
        if self.whisker_props != "" {
            write!(&mut opt, ",whiskerprops={}", self.whisker_props).unwrap();
        }
        if self.extra != "" {
            write!(&mut opt, ",{}", self.extra).unwrap();
        }
        opt
    }
}

impl GraphMaker for Boxplot {
    fn get_buffer<'a>(&'a self) -> &'a String {
        &self.buffer
    }
    fn clear_buffer(&mut self) {
        self.buffer.clear();
    }
}

/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::Boxplot;
    use crate::GraphMaker;

    #[test]
    fn new_works() {
        let boxes = Boxplot::new();
        assert_eq!(boxes.symbol.len(), 0);
        assert_eq!(boxes.horizontal, false);
        assert_eq!(boxes.whisker, None);
        assert_eq!(boxes.positions.len(), 0);
        assert_eq!(boxes.width, None);
        assert_eq!(boxes.no_fliers, false);
        assert_eq!(boxes.patch_artist, false);
        assert_eq!(boxes.median_props.len(), 0);
        assert_eq!(boxes.box_props.len(), 0);
        assert_eq!(boxes.whisker_props.len(), 0);
        assert_eq!(boxes.extra.len(), 0);
        assert_eq!(boxes.buffer.len(), 0);
    }

    #[test]
    fn draw_works_1() {
        let x = vec![
            vec![1, 2, 3],       // A
            vec![2, 3, 4, 5, 6], // B
            vec![6, 7],          // C
        ];
        let mut boxes = Boxplot::new();
        boxes.draw(&x);
        let b: &str = "x=[[1,2,3,],[2,3,4,5,6,],[6,7,],]\n\
                       p=plt.boxplot(x)\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }

    #[test]
    fn draw_works_2() {
        let x = vec![
            vec![1, 2, 3],       // A
            vec![2, 3, 4, 5, 6], // B
            vec![6, 7],          // C
        ];
        let mut boxes = Boxplot::new();
        boxes
            .set_symbol("b+")
            .set_no_fliers(true)
            .set_horizontal(true)
            .set_whisker(1.5)
            .set_positions(&[1.0, 2.0, 3.0])
            .set_width(0.5)
            .set_patch_artist(true)
            .set_boxprops("{'facecolor': 'C0', 'edgecolor': 'white','linewidth': 0.5}")
            .draw(&x);
        let b: &str = "x=[[1,2,3,],[2,3,4,5,6,],[6,7,],]\n\
                       positions=[1,2,3,]\n\
                       p=plt.boxplot(x,sym=r'b+',vert=False,whis=1.5,positions=positions,widths=0.5,showfliers=False,patch_artist=True,boxprops={'facecolor': 'C0', 'edgecolor': 'white','linewidth': 0.5})\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }

    #[test]
    fn draw_mat_works_1() {
        let x = vec![
            //   A  B  C  D  E
            vec![1, 2, 3, 4, 5],
            vec![2, 3, 4, 5, 6],
            vec![3, 4, 5, 6, 7],
            vec![4, 5, 6, 7, 8],
            vec![5, 6, 7, 8, 9],
            vec![6, 7, 8, 9, 10],
        ];
        let mut boxes = Boxplot::new();
        boxes.draw_mat(&x);
        let b: &str = "x=np.array([[1,2,3,4,5,],[2,3,4,5,6,],[3,4,5,6,7,],[4,5,6,7,8,],[5,6,7,8,9,],[6,7,8,9,10,],])\n\
                       p=plt.boxplot(x)\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }

    #[test]
    fn draw_mat_works_2() {
        let x = vec![
            //   A  B  C  D  E
            vec![1, 2, 3, 4, 5],
            vec![2, 3, 4, 5, 6],
            vec![3, 4, 5, 6, 7],
            vec![4, 5, 6, 7, 8],
            vec![5, 6, 7, 8, 9],
            vec![6, 7, 8, 9, 10],
        ];
        let mut boxes = Boxplot::new();
        boxes
            .set_symbol("b+")
            .set_no_fliers(true)
            .set_horizontal(true)
            .set_whisker(1.5)
            .set_positions(&[1.0, 2.0, 3.0, 4.0, 5.0])
            .set_width(0.5)
            .draw_mat(&x);
        let b: &str = "x=np.array([[1,2,3,4,5,],[2,3,4,5,6,],[3,4,5,6,7,],[4,5,6,7,8,],[5,6,7,8,9,],[6,7,8,9,10,],])\n\
                       positions=[1,2,3,4,5,]\n\
                       p=plt.boxplot(x,sym=r'b+',vert=False,whis=1.5,positions=positions,widths=0.5,showfliers=False)\n";
        assert_eq!(boxes.buffer, b);
        boxes.clear_buffer();
        assert_eq!(boxes.buffer, "");
    }
}