【问题标题】:ggplot with posterior distribution plotted over geom_smooth具有后验分布的ggplot绘制在geom_smooth上
【发布时间】:2016-04-21 14:02:25
【问题描述】:

我想使用 ggplot 从Posterior predicted distribution for linear regression in JAGS 上的这篇博客文章中重新创建这个情节?

了解所有可用于 ggplot 的附加功能后,有什么方法可以解决这个问题?

【问题讨论】:

  • 当您说“更好”时,您到底在寻找什么?有哪些重要/缺失的功能?您的情节已经与示例不同。最好从问题中删除您的“答案”并将该部分作为答案发布在下面。然后人们可以对其进行投票或提供替代解决方案。
  • @MrFlick by "better" 我的意思是这是我第一次遇到 ggplot 问题,我在 SO 上找不到解决方案 :)。我假设有人已经这样做了,并且正在寻找他们可能做了什么。我很感激你的想法,如果很快没有替代方案发布,我会移动我的解决方案来回答

标签: r ggplot2 bayesian


【解决方案1】:

这是我使用density 添加geom_path 的基本示例。

library(ggplot2)
#mydat <- read.csv("HtWt30.csv")

mydat <- structure(list(male = c(0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 
                                 1L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 
                                 0L, 0L, 1L, 0L), 
                        height = c(64, 62.3, 67.9, 64.2, 64.8, 57.5, 
                                   65.6, 70.2, 63.9, 71.1, 66.5, 68.1, 62.9, 75.1, 64.6, 69.2, 68.1, 
                                   72.6, 63.2, 64.1, 64.1, 71.5, 76, 69.7, 73.3, 61.7, 66.4, 65.7, 
                                   68.3, 66.9), 
                        weight = c(136.4, 215.1, 173.6, 117.3, 123.3, 96.5, 
                                   178.3, 191.1, 158, 193.9, 127.1, 147.9, 119, 204.4, 143.4, 124.4, 
                                   140.9, 164.7, 139.8, 110.2, 134.1, 193.6, 180, 155, 188.2, 187.4, 
                                   139.2, 147.9, 178.6, 111.1)), 
                   .Names = c("male", "height", "weight"), class = "data.frame", row.names = c(NA, -30L))


# smooth plot
g_smooth <- ggplot(mydat, aes(x = height, y = weight)) + geom_smooth()

# fake posterior at a height = 60
p60 <- data.frame(x = 60, y = rnorm(1000, mean = 145, sd = 10))
# density kernel 
d60 <- density(p60$y)
# calculate scaling factor so that density covers 1/20 of full x range
density_scaling <- ((max(mydat$height) - min(mydat$height)) / 20) / max(d60$y)
# convert to points
d60points <- data.frame(y = d60$x, x = 60 + d60$y * density_scaling)
# add path to plot
g_smooth <- g_smooth + geom_path(data = d60points, aes(x = x, y = y))

# fake posterior at a height = 70
p70 <-  data.frame(x = 60, y = rnorm(1000, mean = 165, sd = 10))
# density kernel 
d70 <- density(p70$y)
# calculate scaling factor so that density covers 1/20 of full x range
density_scaling <- ((max(mydat$height) - min(mydat$height)) / 20) / max(d70$y)
# convert to points
d70points <- data.frame(y = d70$x, x = 70 + d70$y * density_scaling)
# add path to plot
g_smooth <- g_smooth + geom_path(data = d70points, aes(x = x, y = y))

g_smooth

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多