在geom_density上绘制间隔

时间:2017-11-26 00:19:00

标签: r ggplot2 intervals facet density-plot

如何绘制一条水平线,表示ggplot2中刻面密度图的最高(后验)密度区间?这就是我的尝试:

# Functions to calculate lower and upper part of HPD.
hpd_lower = function(x) coda::HPDinterval(as.mcmc(x))[1]
hpd_upper = function(x) coda::HPDinterval(as.mcmc(x))[2]

# Data: two groups with different means
df = data.frame(value=c(rnorm(500), rnorm(500, mean=5)), group=rep(c('A', 'B'), each=500))

# Plot it
ggplot(df, aes(x=value)) + 
  geom_density() +
  facet_wrap(~group) + 
  geom_segment(aes(x=hpd_lower(value), xend=hpd_upper(value), y=0, yend=0), size=3)

enter image description here

如您所见,geom_segment计算两个方面的所有数据,而我希望它尊重分面。我还想要一个解决方案,HPDinterval每个方面只运行一次。

1 个答案:

答案 0 :(得分:1)

预先计算hpd间隔。 ggplot评估整个数据框中aes()函数的计算,即使数据已分组。

# Plot it
library(dplyr)
df_hpd <- group_by(df, group) %>% summarize(x=hpd_lower(value), xend=hpd_upper(value))

ggplot(df, aes(x=value)) + 
  geom_density() +
  facet_wrap(~group) + 
  geom_segment(data = df_hpd, aes(x=x, xend=xend, y=0, yend=0), size=3)

enter image description here