#---------------------------------------------- #--- Bivariate Normal pdf on contour and surface plot --- library(mvtnorm) # for dmvnorm() library(gtools) # for permutations() library(lattice) # for persp() put.in.matrix <- function(grid,x){ grid_max = sqrt(length(x)) A <- matrix(rep(0, grid_max^2), grid_max, grid_max) for (i in 1:grid_max^2) { A[grid[i,1],grid[i,2]] <- x[i] } return(A) } #-set up grid using all combo of (i,j) for i,j=1..10. 100x2 matrix grid_max <- 20 scale <- 2 grid <- permutations(grid_max, 2, repeats.allowed=TRUE) xy_grid <- grid/scale #- set up Bivariate Normal sigma <- matrix(c(6,2,2,6), 2, 2) mu <- c(5,5) f <- dmvnorm(xy_grid, mean=mu, sigma=sigma) # 2d Nomal for each row of t A <- put.in.matrix(grid,f) # sort out f, and put in 10x10 matrix #- 3D contour plot filled.contour((1:grid_max)/scale, (1:grid_max)/scale, A, col=rainbow(9)) #- 3D surface plot for (i in 1:13) { th <- (i-1)*30 persp((1:grid_max)/scale, (1:grid_max)/scale, A, theta=th, phi=20, col=rainbow(9), xlab="X", ylab="Y" ) readline(paste(" showing theta=",th,"hit enter for next")) # loop will wait for you to hit enter } #---------------------------------------------- #--- Repeat with another joint density --- #-set up grid using all combo of (i,j) for i,j=1..10. 100x2 matrix grid_max <- 20 scale <- 20 grid <- permutations(grid_max, 2, repeats.allowed=TRUE) xy_grid <- grid/scale #-custom joint pdf joint_f <- function(t){ z=numeric(0) for (i in 1:dim(t)[1]){ x = t[i,1] y = t[i,2] if (0