Illustrate mean and standard deviation in ggplot2 density plot

纵然是瞬间 提交于 2019-12-04 15:45:24

The mean and standard deviation are measured on the x-scale, so you'd need to plot them along the x-axis. The y-axis is the density of points within a given x-interval, and is analogous to the height of the bars in a histogram.

Maybe this will give you something like what you were looking for: The code below adds a horizontal line that spans the standard deviation of each density plot, along with droplines to mark their location on the x-axis. The sd line is located at y-value where the width of the distribution is equal to the standard deviation. If you wish, you could in addition (or instead) fill the region spanned by the standard deviation.

library(dplyr)

# Densities
n = 2^10
df = data.frame(x = c(density(foo,n=n)$x, density(bar,n=n)$x),
                y = c(density(foo,n=n)$y, density(bar,n=n)$y),
                group=rep(c("foo","bar"), each=n))

## Mean and SD
msd =  melt(data.frame(foo=foo, bar=bar)) %>% 
         group_by(group=variable) %>% summarise(mean=mean(value), sd=sd(value))

# Find y value (of density) where sd has same width as density
msd$y = unlist(lapply(unique(df$group), function(g) {
  d = df[df$group==g,]
  d$y[which.min(abs(d$x - (msd$mean[msd$group==g] - msd$sd[msd$group==g])))]
}))

ggplot(df, aes(x=x, y=y, colour=group)) + 
  geom_line() + labs(x = NULL) +
  geom_segment(data=msd, aes(y=y,yend=y, x=mean - sd, xend=mean + sd), lty="21") +
  geom_point(data=msd, aes(y=y, x=mean)) +
  geom_segment(data=msd, aes(x=mean-sd, xend=mean-sd, y=0, yend=y), alpha=0.5, lty="21") +
  geom_segment(data=msd, aes(x=mean+sd, xend=mean+sd, y=0, yend=y), alpha=0.5, lty="21")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!