rustplotlib/
figure.rs

1use std::io;
2use axes2d::Axes2D;
3use backend::Backend;
4
5/// Represents an instance of `matplotlib.figure.Figure`.
6#[derive(Debug, Default)]
7pub struct Figure<'a> {
8  rows: u32,
9  cols: u32,
10  axes: Vec<Option<Axes2D<'a>>>,
11}
12
13impl<'a> Figure<'a> {
14  /// create an empty instance of `Figure`.
15  ///
16  /// This method is the shortcut of `Default::default()`.
17  pub fn new() -> Figure<'a> {
18    Default::default()
19  }
20
21  /// set the axes object in the figure.
22  pub fn subplots(mut self, rows: u32, cols: u32, axes: Vec<Option<Axes2D<'a>>>) -> Self {
23    self.axes.clear();
24    self.rows = rows;
25    self.cols = cols;
26    self.axes = axes;
27
28    let remains = (self.rows * self.cols) as usize - self.axes.len();
29    if remains > 0 {
30      self.axes.extend((0..remains).into_iter().map(|_| None));
31    }
32    self
33  }
34
35  pub fn apply<B: Backend>(&self, mpl: &mut B) -> io::Result<()> {
36    mpl.figure()?;
37    for (i, axes) in self.axes.iter().enumerate() {
38      if let &Some(ref axes) = axes {
39        mpl.subplot(self.rows, self.cols, (i + 1) as u32)?;
40        axes.apply(mpl)?;
41      }
42    }
43    Ok(())
44  }
45}