ggplot2 - 2D Normal PDF with ggplot and R -


i'm trying make contour/image plot using ggplot no success til now.

consider following piece of code in r creates matrix z pdf of bivariate normal:

require(mvtnorm) x1 = seq(-3, 3, length.out=200) x2 = seq(-3, 3, length.out=200) z = matrix(0, length(x1), length(x2)) (i in 1:length(x1)) {     = x1     b = x2[i]     z[,i] = dmvnorm(cbind(a,b)) } image(x1,x2,z) 

2d normal pdf image plot

is possible plot matrix z using ggplot?

thanks!

# reshape data require(reshape2) dat <- melt(z)  # use geom_raster mimic image  gg <- ggplot(dat, aes(x=var2, y=var1, fill=value)) gg <- gg + labs(x="", y="") gg <- gg + geom_raster() gg <- gg + coord_equal() gg <- gg + scale_fill_gradient(low="red", high="yellow") gg <- gg + scale_x_continuous(expand = c(0, 0)) gg <- gg + scale_y_continuous(expand = c(0, 0)) gg <- gg + theme_bw() gg 

enter image description here

you can change axis labels pretty if need to.


Comments

Popular posts from this blog

ruby - How do I merge two hashes into a hash of arrays? -

java - the value of local variable is not used -