1 | use plotters::prelude::*; |
2 | |
3 | use rand::SeedableRng; |
4 | use rand_distr::{Distribution, Normal}; |
5 | use rand_xorshift::XorShiftRng; |
6 | |
7 | use num_traits::sign::Signed; |
8 | |
9 | const OUT_FILE_NAME: &'static str = "plotters-doc-data/normal-dist2.png" ; |
10 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
11 | let sd = 0.60; |
12 | |
13 | let random_points: Vec<f64> = { |
14 | let norm_dist = Normal::new(0.0, sd).unwrap(); |
15 | let mut x_rand = XorShiftRng::from_seed(*b"MyFragileSeed123" ); |
16 | let x_iter = norm_dist.sample_iter(&mut x_rand); |
17 | x_iter.take(5000).filter(|x| x.abs() <= 4.0).collect() |
18 | }; |
19 | |
20 | let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); |
21 | |
22 | root.fill(&WHITE)?; |
23 | |
24 | let mut chart = ChartBuilder::on(&root) |
25 | .margin(5) |
26 | .caption("1D Gaussian Distribution Demo" , ("sans-serif" , 30)) |
27 | .set_label_area_size(LabelAreaPosition::Left, 60) |
28 | .set_label_area_size(LabelAreaPosition::Bottom, 60) |
29 | .set_label_area_size(LabelAreaPosition::Right, 60) |
30 | .build_cartesian_2d(-4f64..4f64, 0f64..0.1)? |
31 | .set_secondary_coord( |
32 | (-4f64..4f64).step(0.1).use_round().into_segmented(), |
33 | 0u32..500u32, |
34 | ); |
35 | |
36 | chart |
37 | .configure_mesh() |
38 | .disable_x_mesh() |
39 | .disable_y_mesh() |
40 | .y_label_formatter(&|y| format!("{:.0}%" , *y * 100.0)) |
41 | .y_desc("Percentage" ) |
42 | .draw()?; |
43 | |
44 | chart.configure_secondary_axes().y_desc("Count" ).draw()?; |
45 | |
46 | let actual = Histogram::vertical(chart.borrow_secondary()) |
47 | .style(GREEN.filled()) |
48 | .margin(3) |
49 | .data(random_points.iter().map(|x| (*x, 1))); |
50 | |
51 | chart |
52 | .draw_secondary_series(actual)? |
53 | .label("Observed" ) |
54 | .legend(|(x, y)| Rectangle::new([(x, y - 5), (x + 10, y + 5)], GREEN.filled())); |
55 | |
56 | let pdf = LineSeries::new( |
57 | (-400..400).map(|x| x as f64 / 100.0).map(|x| { |
58 | ( |
59 | x, |
60 | (-x * x / 2.0 / sd / sd).exp() / (2.0 * std::f64::consts::PI * sd * sd).sqrt() |
61 | * 0.1, |
62 | ) |
63 | }), |
64 | &RED, |
65 | ); |
66 | |
67 | chart |
68 | .draw_series(pdf)? |
69 | .label("PDF" ) |
70 | .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], RED.filled())); |
71 | |
72 | chart.configure_series_labels().draw()?; |
73 | |
74 | // To avoid the IO failure being ignored silently, we manually call the present function |
75 | root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir" ); |
76 | println!("Result has been saved to {}" , OUT_FILE_NAME); |
77 | |
78 | Ok(()) |
79 | } |
80 | #[test] |
81 | fn entry_point() { |
82 | main().unwrap() |
83 | } |
84 | |