plotpy 1.21.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
use super::GraphMaker;
use std::fmt::Write;

/// Implements the capability to add inset Axes to existing Axes.
///
/// # Examples
///
/// ```
/// use plotpy::{Curve, InsetAxes, Plot, StrError};
///
/// fn main() -> Result<(), StrError> {
///     // draw curve
///     let mut curve = Curve::new();
///     curve.draw(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
///
///     // allocate inset and add curve to it
///     let mut inset = InsetAxes::new();
///     inset
///         .add(&curve) // add curve to inset
///         .set_range(0.5, 1.5, 0.5, 1.5) // set the range of the inset
///         .draw(0.5, 0.5, 0.4, 0.3);
///
///     // add curve and inset to plot
///     let mut plot = Plot::new();
///     plot.add(&curve)
///         .set_range(0.0, 5.0, 0.0, 5.0)
///         .add(&inset) // IMPORTANT: add inset after setting the range
///         .save("/tmp/plotpy/doc_tests/doc_inset_axes_add.svg")
/// }
/// ```
///
/// ![doc_inset_axes_add.svg](https://raw.githubusercontent.com/cpmech/plotpy/main/figures/doc_inset_axes_add.svg)
///
/// # Warning
///
/// **WARNING:** If the range of axes has been modified in [crate::Plot], e.g. by `plot.set_range(...)`,
/// then the inset must be added after the range has been set. Otherwise, the inset will not be displayed correctly.
/// Specifically the connector lines will not be drawn if the inset is added before `set_range`.
pub struct InsetAxes {
    range: Option<(f64, f64, f64, f64)>,
    extra_for_axes: String,
    extra_for_indicator: String,
    indicator_line_style: String,
    indicator_line_color: String,
    indicator_line_width: f64,
    indicator_hatch: String,
    indicator_alpha: Option<f64>,
    axes_visible: bool,
    indicator_disabled: bool,
    title: String,
    buffer: String,
}

impl InsetAxes {
    /// Creates a new `InsetAxes` object with an empty buffer.
    ///
    /// # Returns
    ///
    /// A new instance of `InsetAxes`.
    ///
    /// # Warning
    ///
    /// **WARNING:** If the range of axes has been modified in [crate::Plot], e.g. by `plot.set_range(...)`,
    /// then the inset must be added after the range has been set. Otherwise, the inset will not be displayed correctly.
    /// Specifically the connector lines will not be drawn if the inset is added before `set_range`.
    ///
    /// For example, below is the correct procedure:
    ///
    /// ```
    /// use plotpy::{InsetAxes, Plot};
    /// let mut inset = InsetAxes::new();
    /// let mut plot = Plot::new();
    /// plot.set_range(0.0, 10.0, 0.0, 10.0)
    ///     .add(&inset); // IMPORTANT: add inset after setting the range
    /// ```
    pub fn new() -> Self {
        Self {
            range: None,
            extra_for_axes: String::new(),
            extra_for_indicator: String::new(),
            indicator_line_style: String::new(),
            indicator_line_color: String::new(),
            indicator_line_width: 0.0,
            indicator_hatch: String::new(),
            indicator_alpha: None,
            axes_visible: false,
            indicator_disabled: false,
            title: String::new(),
            buffer: String::new(),
        }
    }

    /// Sets the line style for the indicator (e.g. "--", ":", "-.")
    pub fn set_indicator_line_style(&mut self, style: &str) -> &mut Self {
        self.indicator_line_style = style.to_string();
        self
    }

    /// Sets the line color for the indicator (e.g. "red", "#FF0000")
    pub fn set_indicator_line_color(&mut self, color: &str) -> &mut Self {
        self.indicator_line_color = color.to_string();
        self
    }

    /// Sets the line width for the indicator
    pub fn set_indicator_line_width(&mut self, width: f64) -> &mut Self {
        self.indicator_line_width = width;
        self
    }

    /// Sets the alpha (opacity) for the indicator
    pub fn set_indicator_alpha(&mut self, alpha: f64) -> &mut Self {
        self.indicator_alpha = Some(alpha);
        self
    }

    /// Sets the hatch pattern for the indicator (e.g. "/", "\\", "|", "-", "+", "x", "o", "O", ".", "*")
    ///
    /// Common hatch patterns include:                                                                                 
    ///
    /// * "/" - diagonal hatching                                                                                     
    /// * "\" - back diagonal hatching                                                                                
    /// * "|" - vertical hatching                                                                                     
    /// * "-" - horizontal hatching                                                                                   
    /// * "+" - crossed hatching                                                                                      
    /// * "x" - crossed diagonal hatching                                                                             
    /// * "o" - small circle hatching                                                                                 
    /// * "O" - large circle hatching                                                                                 
    /// * "." - dot hatching                                                                                          
    /// * "*" - star hatching  
    ///
    /// [See options in ](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.indicate_inset.html#matplotlib.axes.Axes.indicate_inset)
    ///
    /// [See Matplotlib's documentation for more hatch patterns](https://matplotlib.org/stable/gallery/shapes_and_collections/hatch_demo.html)
    pub fn set_indicator_hatch(&mut self, hatch: &str) -> &mut Self {
        self.indicator_hatch = hatch.to_string();
        self
    }

    /// Adds new graph entity
    ///
    /// # Warning
    ///
    /// **WARNING:** If the range of axes has been modified in [crate::Plot], e.g. by `plot.set_range(...)`,
    /// then the inset must be added after the range has been set. Otherwise, the inset will not be displayed correctly.
    /// Specifically the connector lines will not be drawn if the inset is added before `set_range`.
    ///
    /// For example, below is the correct procedure:
    ///
    /// ```
    /// use plotpy::{InsetAxes, Plot};
    /// let mut inset = InsetAxes::new();
    /// let mut plot = Plot::new();
    /// plot.set_range(0.0, 10.0, 0.0, 10.0)
    ///     .add(&inset); // IMPORTANT: add inset after setting the range
    /// ```
    pub fn add(&mut self, graph: &dyn GraphMaker) -> &mut Self {
        // Note: the order of replacements is important
        let buf = graph
            .get_buffer()
            .replace("plt.gca()", "zoom")
            .replace("plt.barh", "zoom.barh")
            .replace("plt.bar", "zoom.bar")
            .replace("plt.boxplot", "zoom.boxplot")
            .replace("plt.contourf", "zoom.contourf")
            .replace("plt.contour", "zoom.contour")
            .replace("plt.clabel", "zoom.clabel")
            .replace("plt.colorbar", "ignore_this")
            .replace("cb.ax.set_ylabel", "ignore_this")
            .replace("plt.fill_between", "zoom.fill_between")
            .replace("plt.imshow", "zoom.imshow")
            .replace("plt.legend", "zoom.legend")
            .replace("plt.hist", "zoom.hist")
            .replace("plt.plot", "zoom.plot")
            .replace("plt.quiver", "zoom.quiver")
            .replace("plt.text", "zoom.text")
            .replace("plt.streamplot", "zoom.streamplot")
            .replace("plt.tricontour", "zoom.tricontour")
            .replace("plt.tricontourf", "zoom.tricontourf")
            .replace("plt.triplot", "zoom.triplot");
        self.buffer.push_str(&buf);
        self
    }

    /// Draws the inset Axes.
    ///
    /// Example of normalized coordinates: `(0.5, 0.5, 0.4, 0.3)`.
    ///
    /// # Arguments
    ///
    /// * `u0` -- The normalized (0 to 1) horizontal figure coordinate of the lower-left corner of the inset Axes.
    /// * `v0` -- The normalized (0 to 1) vertical figure coordinate of the lower-left corner of the inset Axes.
    /// * `width` -- The width of the inset Axes.
    /// * `height` -- The height of the inset Axes.
    ///
    /// # Warning
    ///
    /// **WARNING:** If the range of axes has been modified in [crate::Plot], e.g. by `plot.set_range(...)`,
    /// then the inset must be added after the range has been set. Otherwise, the inset will not be displayed correctly.
    /// Specifically the connector lines will not be drawn if the inset is added before `set_range`.
    pub fn draw(&mut self, u0: f64, v0: f64, width: f64, height: f64) {
        let opt1 = self.options_for_axes();
        let opt2 = self.options_for_indicator();
        if let Some((xmin, xmax, ymin, ymax)) = self.range {
            self.buffer.insert_str(
                0,
                &format!(
                    "zoom=plt.gca().inset_axes([{},{},{},{}],xlim=({},{}),ylim=({},{}){})\n",
                    u0, v0, width, height, xmin, xmax, ymin, ymax, opt1,
                ),
            );
        } else {
            self.buffer.insert_str(
                0,
                &format!(
                    "zoom=plt.gca().inset_axes([{},{},{},{}]{})\n",
                    u0, v0, width, height, opt1,
                ),
            );
        }
        if !self.axes_visible {
            write!(&mut self.buffer, "zoom.set_xticks([])\nzoom.set_yticks([])\n").unwrap();
        }
        if !self.title.is_empty() {
            write!(&mut self.buffer, "zoom.set_title(r'{}')\n", self.title).unwrap();
        }
        if !self.indicator_disabled {
            write!(&mut self.buffer, "plt.gca().indicate_inset_zoom(zoom{})\n", opt2,).unwrap();
        }
    }

    /// Sets the limits of axes in the inset.
    pub fn set_range(&mut self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> &mut Self {
        self.range = Some((xmin, xmax, ymin, ymax));
        self
    }

    /// Sets extra Matplotlib commands for the inset Axes (comma separated).
    ///
    /// [See Matplotlib's documentation for extra parameters](<https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes>)
    pub fn set_extra_for_axes(&mut self, extra: &str) -> &mut Self {
        self.extra_for_axes = extra.to_string();
        self
    }

    /// Sets extra Matplotlib commands for the indicator (comma separated).
    ///
    /// [See Matplotlib's documentation for extra parameters](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.indicate_inset.html#matplotlib.axes.Axes.indicate_inset)
    pub fn set_extra_for_indicator(&mut self, extra: &str) -> &mut Self {
        self.extra_for_indicator = extra.to_string();
        self
    }

    /// Sets the visibility of the axes ticks
    ///
    /// # Arguments
    ///
    /// * `visible` - If true, shows the axes ticks. If false, hides them.
    pub fn set_visibility(&mut self, visible: bool) -> &mut Self {
        self.axes_visible = visible;
        self
    }

    /// Sets the title of the inset axes
    pub fn set_title(&mut self, title: &str) -> &mut Self {
        self.title = title.to_string();
        self
    }

    /// Sets whether the indicator lines are disabled
    ///
    /// # Arguments
    ///
    /// * `disabled` - If true, hides the indicator lines. If false, shows them.
    pub fn set_indicator_disabled(&mut self, disabled: bool) -> &mut Self {
        self.indicator_disabled = disabled;
        self
    }

    /// Returns options for the inset Axes
    fn options_for_axes(&self) -> String {
        let mut opt = String::new();
        if !self.extra_for_axes.is_empty() {
            write!(&mut opt, ",{}", self.extra_for_axes).unwrap();
        }
        opt
    }

    /// Returns options for the indicator
    fn options_for_indicator(&self) -> String {
        let mut opt = String::new();
        if !self.indicator_line_style.is_empty() {
            write!(&mut opt, ",linestyle='{}'", self.indicator_line_style).unwrap();
        }
        if !self.indicator_line_color.is_empty() {
            write!(&mut opt, ",edgecolor='{}'", self.indicator_line_color).unwrap();
        }
        if self.indicator_line_width > 0.0 {
            write!(&mut opt, ",linewidth={}", self.indicator_line_width).unwrap();
        }
        if !self.indicator_hatch.is_empty() {
            write!(&mut opt, ",hatch='{}'", self.indicator_hatch).unwrap();
        }
        if let Some(alpha) = self.indicator_alpha {
            write!(&mut opt, ",alpha={}", alpha).unwrap();
        }
        if !self.extra_for_indicator.is_empty() {
            write!(&mut opt, ",{}", self.extra_for_indicator).unwrap();
        }
        opt
    }
}

impl GraphMaker for InsetAxes {
    /// Returns a reference to the buffer containing the generated commands.
    ///
    /// # Returns
    ///
    /// A reference to the buffer as a `String`.
    fn get_buffer<'a>(&'a self) -> &'a String {
        &self.buffer
    }

    /// Clears the buffer, removing all stored commands.
    fn clear_buffer(&mut self) {
        self.buffer.clear();
    }
}

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

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

    #[test]
    fn test_new() {
        let inset = InsetAxes::new();
        assert_eq!(inset.range, None);
        assert!(inset.buffer.is_empty());
    }

    #[test]
    fn test_set_range() {
        let mut inset = InsetAxes::new();
        inset.set_range(-1.0, 2.0, -3.0, 4.0);
        assert_eq!(inset.range, Some((-1.0, 2.0, -3.0, 4.0)));
    }

    #[test]
    fn test_set_title() {
        let mut inset = InsetAxes::new();
        inset.set_title("Test Title");
        assert_eq!(inset.title, "Test Title");
    }

    #[test]
    fn test_set_visibility() {
        let mut inset = InsetAxes::new();
        inset.set_visibility(true);
        assert!(inset.axes_visible);
        inset.set_visibility(false);
        assert!(!inset.axes_visible);
    }

    #[test]
    fn test_indicator_options() {
        let mut inset = InsetAxes::new();
        inset
            .set_indicator_line_style("--")
            .set_indicator_line_color("red")
            .set_indicator_line_width(2.0)
            .set_indicator_hatch("/")
            .set_indicator_alpha(0.5);

        let options = inset.options_for_indicator();
        assert!(options.contains("linestyle='--'"));
        assert!(options.contains("edgecolor='red'"));
        assert!(options.contains("linewidth=2"));
        assert!(options.contains("hatch='/'"));
        assert!(options.contains("alpha=0.5"));
    }

    #[test]
    fn test_draw_basic() {
        let mut inset = InsetAxes::new();
        inset.draw(0.5, 0.5, 0.4, 0.3);
        let buffer = inset.get_buffer();
        assert!(buffer.contains("zoom=plt.gca().inset_axes([0.5,0.5,0.4,0.3]"));
        assert!(buffer.contains("plt.gca().indicate_inset_zoom(zoom"));
    }

    #[test]
    fn test_indicator_disabled() {
        let mut inset = InsetAxes::new();
        assert_eq!(inset.indicator_disabled, false);

        inset.set_indicator_disabled(true);
        assert_eq!(inset.indicator_disabled, true);

        inset.draw(0.5, 0.5, 0.4, 0.3);
        let buffer = inset.get_buffer();
        assert!(!buffer.contains("indicate_inset_zoom"));

        inset.set_indicator_disabled(false);
        inset.clear_buffer();
        inset.draw(0.5, 0.5, 0.4, 0.3);
        let buffer = inset.get_buffer();
        assert!(buffer.contains("indicate_inset_zoom"));
    }

    #[test]
    fn test_clear_buffer() {
        let mut inset = InsetAxes::new();
        inset.draw(0.5, 0.5, 0.4, 0.3);
        assert!(!inset.buffer.is_empty());
        inset.clear_buffer();
        assert!(inset.buffer.is_empty());
    }
}