【问题标题】:2D Normal PDF with ggplot and R带有 ggplot 和 R 的 2D Normal PDF
【发布时间】:2014-11-24 05:04:06
【问题描述】:

我正在尝试使用 ggplot 绘制轮廓/图像图,但到目前为止还没有成功。

考虑 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)

是否可以使用 ggplot 绘制矩阵z

谢谢!

【问题讨论】:

    标签: r ggplot2 contour probability-density


    【解决方案1】:
    # 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
    

    如果需要,您可以很容易地更改轴标签。

    【讨论】:

    • + 1 只需将此步骤添加到您的答案中:dat$Var1 &lt;- x1, dat$Var2 &lt;- rep(x2, each=200) 然后 x 和 y 轴将是正确的。
    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2015-10-02
    相关资源
    最近更新 更多