1  use plotters::prelude::*;
2  
3  use rand::SeedableRng;
4  use rand_distr::{Distribution, Normal};
5  use rand_xorshift::XorShiftRng;
6  
7  const OUT_FILE_NAME: &'static str = "plotters-doc-data/normal-dist.png";
main() -> Result<(), Box<dyn std::error::Error>>8  fn main() -> Result<(), Box<dyn std::error::Error>> {
9      let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area();
10  
11      root.fill(&WHITE)?;
12  
13      let sd = 0.13;
14  
15      let random_points: Vec<(f64, f64)> = {
16          let norm_dist = Normal::new(0.5, sd).unwrap();
17          let mut x_rand = XorShiftRng::from_seed(*b"MyFragileSeed123");
18          let mut y_rand = XorShiftRng::from_seed(*b"MyFragileSeed321");
19          let x_iter = norm_dist.sample_iter(&mut x_rand);
20          let y_iter = norm_dist.sample_iter(&mut y_rand);
21          x_iter.zip(y_iter).take(5000).collect()
22      };
23  
24      let areas = root.split_by_breakpoints([944], [80]);
25  
26      let mut x_hist_ctx = ChartBuilder::on(&areas[0])
27          .y_label_area_size(40)
28          .build_cartesian_2d((0.0..1.0).step(0.01).use_round().into_segmented(), 0..250)?;
29      let mut y_hist_ctx = ChartBuilder::on(&areas[3])
30          .x_label_area_size(40)
31          .build_cartesian_2d(0..250, (0.0..1.0).step(0.01).use_round())?;
32      let mut scatter_ctx = ChartBuilder::on(&areas[2])
33          .x_label_area_size(40)
34          .y_label_area_size(40)
35          .build_cartesian_2d(0f64..1f64, 0f64..1f64)?;
36      scatter_ctx
37          .configure_mesh()
38          .disable_x_mesh()
39          .disable_y_mesh()
40          .draw()?;
41      scatter_ctx.draw_series(
42          random_points
43              .iter()
44              .map(|(x, y)| Circle::new((*x, *y), 2, GREEN.filled())),
45      )?;
46      let x_hist = Histogram::vertical(&x_hist_ctx)
47          .style(GREEN.filled())
48          .margin(0)
49          .data(random_points.iter().map(|(x, _)| (*x, 1)));
50      let y_hist = Histogram::horizontal(&y_hist_ctx)
51          .style(GREEN.filled())
52          .margin(0)
53          .data(random_points.iter().map(|(_, y)| (*y, 1)));
54      x_hist_ctx.draw_series(x_hist)?;
55      y_hist_ctx.draw_series(y_hist)?;
56  
57      // To avoid the IO failure being ignored silently, we manually call the present function
58      root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir");
59      println!("Result has been saved to {}", OUT_FILE_NAME);
60  
61      Ok(())
62  }
63  #[test]
entry_point()64  fn entry_point() {
65      main().unwrap()
66  }
67