2014-09-29 52 views
1

我想使用ggplot做一個輪廓/圖像繪圖,但直到現在沒有成功。2D正常PDF與ggplot和R

考慮在R上的下面的代碼段,與二元正常的PDF創建一個矩陣z

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

2D normal pdf image plot

是否有可能使用ggplot繪製矩陣z

謝謝!

回答

3
# reshape the data 
require(reshape2) 
dat <- melt(z) 

# use geom_raster to 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

你可以很容易地,如果你需要更改軸標籤。

+2

+ 1只需將此步驟添加到您的答案:'dat $ Var1 < - x1', 'dat $ Var2 < - rep(x2,each = 200)',那麼x和y軸將是正確的。 – 2014-09-29 19:08:17

+0

謝謝大家!它工作得很好。 – 2014-09-29 19:15:00