1extern crate rustplotlib;
2#[cfg(feature = "native")]
3extern crate cpython;
4
5use rustplotlib::{backend, Backend};
6use rustplotlib::{Figure, Axes2D, Scatter, Line2D, FillBetween};
7use std::f64::consts::PI;
8
9fn make_figure<'a>(x: &'a [f64], y1: &'a [f64], y2: &'a [f64]) -> Figure<'a> {
10 let ax1 = Axes2D::new()
11 .add(Scatter::new(r"$y_1 = \sin(x)$")
12 .data(x, y1)
13 .marker("o"))
14 .add(Line2D::new(r"$y_2 = \cos(x)$")
15 .data(x, y2)
16 .color("red")
17 .marker("x")
18 .linestyle("--")
19 .linewidth(1.0))
20 .xlabel("Time [sec]")
21 .ylabel("Distance [mm]")
22 .legend("lower right")
23 .xlim(0.0, 8.0)
24 .ylim(-2.0, 2.0);
25
26 let ax2 = Axes2D::new()
27 .add(FillBetween::new()
28 .data(x, y1, y2)
29 .interpolate(true))
30 .xlim(0.0, 8.0)
31 .ylim(-1.5, 1.5);
32
33 Figure::new().subplots(2, 1, vec![Some(ax1), Some(ax2)])
34}
35
36fn apply_mpl(fig: &Figure, filename: &str) -> std::io::Result<()> {
37 let mut mp = backend::Matplotlib::new()?;
38 mp.set_style("ggplot")?;
39 fig.apply(&mut mp)?;
40 mp.savefig(filename)?
41 .dump_pickle(format!("{}.pkl", filename))?
42 .wait()
43}
44
45#[cfg(feature = "native")]
46fn apply_mpl_native(fig: &Figure, filename: &str) -> std::io::Result<()> {
47 let mut mp = backend::MatplotlibNative::new();
48 mp.set_style("dark_background")?;
49 fig.apply(&mut mp)?;
50 mp.savefig(filename)?;
51 mp.dump_pickle(format!("{}.pkl", filename))?;
52 Ok(())
53}
54
55fn main() {
56 let x: Vec<f64> = (0..40).into_iter().map(|i| (i as f64) * 0.08 * PI).collect();
57 let y1: Vec<f64> = x.iter().map(|x| x.sin()).collect();
58 let y2: Vec<f64> = x.iter().map(|x| x.cos()).collect();
59
60 let fig = make_figure(&x, &y1, &y2);
61
62 apply_mpl(&fig, "simple.png").unwrap();
63 #[cfg(feature = "native")]
64 apply_mpl_native(&fig, "simple_native.png").unwrap();
65}