r - Illustrate mean and standard deviation in ggplot2 density plot -
i'm working plot 2 distributed random variables using ggplot2 showing mean , standard deviation (sd) on x-axis , sd on y-axis respectively. i've gotten far, obliviously don't have sd on y-axis, bu density. i'm don't wrong? (code below)
set.seed(1) foo <- rnorm(10^5, mean = 2, sd = 1) bar <- rnorm(10^4, mean = 5, sd = 2) # install.packages("reshape2", dependencies = true) require(reshape2) df.m <- melt(data.frame(foo = foo, bar = bar)) # install.packages("ggplot2", dependencies = true) require(ggplot2) ggplot(df.m) + geom_density(aes(x = value, colour = variable)) + labs(x = null) mean(foo); sd(foo) # [1] 1.997756 # [1] 1.003523 mean(bar); sd(bar) # [1] 5.002044 # [1] 1.983901 currently thinking this box plot solution
the mean , standard deviation measured on x-scale, you'd need plot them along x-axis. y-axis density of points within given x-interval, , analogous height of bars in histogram.
maybe give looking for: code below adds horizontal line spans standard deviation of each density plot, along droplines mark location on x-axis. sd line located @ y-value width of distribution equal standard deviation. if wish, in addition (or instead) fill region spanned 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 , 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) sd has same width 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") 

Comments
Post a Comment