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) 
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 
you can change axis labels pretty if need to.
Comments
Post a Comment