Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve the bivariate normal pdf 3d plot example #197

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions examples/3d-plot2.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
use plotters::prelude::*;
use std::f64::consts::PI;
fn pdf(x: f64, y: f64) -> f64 {
const SDX: f64 = 0.1;
const SDY: f64 = 0.1;
const A: f64 = 5.0;
let x = x as f64 / 10.0;
let y = y as f64 / 10.0;
A * (-x * x / 2.0 / SDX / SDX - y * y / 2.0 / SDY / SDY).exp()
// see https://mathworld.wolfram.com/BivariateNormalDistribution.html
// assumes x_bar = 0 and y_bar = 0
const SDX: f64 = 0.3;
const SDY: f64 = 0.3;
const vx: f64 = SDX * SDX;
const vy : f64 = SDY * SDY;
const sdx_sdy: f64 = SDX * SDY;
const RHO : f64 = 0.9;
const c1: f64 = 1.0 - RHO * RHO;
let c2 : f64 = c1.sqrt();
let A: f64 = 1.0 / (2.0 * PI * sdx_sdy * c2);
let Z: f64 = x * x / vx - 2.0 * RHO * x * y / sdx_sdy + y * y / vy;
let res = A * (-Z / 2.0 / c1).exp();
res
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand All @@ -17,7 +26,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

let mut chart = ChartBuilder::on(&root)
.caption("2D Guassian PDF", ("sans-serif", 20))
.build_cartesian_3d(-3.0..3.0, 0.0..6.0, -3.0..3.0)?;
.build_cartesian_3d(-1.0..1.0, 0.0..3.0, -1.0..1.0)?;
chart.with_projection(|mut p| {
p.pitch = 1.57 - (1.57 - pitch as f64 / 50.0).abs();
p.scale = 0.7;
Expand All @@ -28,8 +37,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

chart.draw_series(
SurfaceSeries::xoz(
(-15..=15).map(|x| x as f64 / 5.0),
(-15..=15).map(|x| x as f64 / 5.0),
(-30..=30).map(|x| x as f64 / 30.0),
(-30..=30).map(|x| x as f64 / 30.0),
pdf,
)
.style_func(&|&v| {
Expand Down