use*_*564 8 r ggplot2 confidence-interval
所以我有一个三列数据框,有Trials,Ind.Variable,Observation.就像是:
df1<- data.frame(Trial=rep(1:10,5), Variable=rep(1:5, each=10), Observation=rnorm(1:50))
我试图绘制一个95%的conf.每个试验的平均值间隔使用相当低效的方法如下:
b<-NULL
b$mean<- aggregate(Observation~Variable, data=df1,mean)[,2]
b$sd <- aggregate(Observation~Variable, data=df1,sd)[,2]
b$Variable<- df1$Variable
b$Observation <- df1$Observation
b$ucl <- rep(qnorm(.975, mean=b$mean, sd=b$sd), each=10)
b$lcl <- rep(qnorm(.025, mean=b$mean, sd=b$sd), each=10)
b<- as.data.frame(b)
c <- ggplot(b, aes(Variable, Observation))
c + geom_point(color="red") +
geom_smooth(aes(ymin = lcl, ymax = ucl), data=b, stat="summary", fun.y="mean")
Run Code Online (Sandbox Code Playgroud)
这是低效的,因为它复制了ymin,ymax的值.我已经看过geom_ribbon方法,但我仍然需要复制.但是,如果我使用像glm这样的任何平滑,代码更简单,没有重复.有没有更好的方法呢?
参考文献:1.R用ggplot绘制置信区间 2. 用ggplot2手动着色置信区间 3. http://docs.ggplot2.org/current/geom_smooth.html
使用此方法,我获得与您的方法相同的输出.这是受到ggplot文档的启发.同样,只要每个x值有多个点,这将是有意义的.
set.seed(1)
df1 <- data.frame(Trial=rep(1:10,5), Variable=rep(1:5, each=10), Observation=rnorm(1:50)) my_ci <- function(x) data.frame(y=mean(x), ymin=mean(x)-2*sd(x), ymax=mean(x)+2*sd(x))
my_ci <- function(x) data.frame(
y=mean(x),
ymin=mean(x) - 2 * sd(x),
ymax=mean(x) + 2 * sd(x)
)
ggplot(df1, aes(Variable, Observation)) + geom_point(color="red") +
stat_summary(fun.data="my_ci", geom="smooth")
Run Code Online (Sandbox Code Playgroud)

该ggplot包带有包装器,用于包中的许多总结功能Hmisc,包括
mean_cl_normal 它根据 t 分布计算置信限,mean_cl_boot 它使用不假设均值分布的引导方法,mean_sdl 它使用标准偏差的倍数(默认值 = 2)。后一种方法与上面的答案相同,但不是95% CL。基于 t 分布的置信限由下式给出:
CL = t × s / √n
其中 t 是 t 分布的适当分位数,s 是样本标准偏差。比较置信区间:
ggplot(df1, aes(x=Variable, y=Observation)) +
stat_summary(fun.data="mean_sdl", geom="line", colour="blue")+
stat_summary(fun.data="mean_sdl", mult=2, geom="errorbar",
width=0.1, linetype=2, colour="blue")+
geom_point(color="red") +
labs(title=expression(paste(bar(x)," \u00B1 ","2 * sd")))
Run Code Online (Sandbox Code Playgroud)

ggplot(df1, aes(x=Variable, y=Observation)) +
geom_point(color="red") +
stat_summary(fun.data="mean_cl_normal", geom="line", colour="blue")+
stat_summary(fun.data="mean_cl_normal", conf.int=0.95, geom="errorbar",
width=0.1, linetype=2, colour="blue")+
stat_summary(fun.data="mean_cl_normal", geom="point", size=3,
shape=1, colour="blue")+
labs(title=expression(paste(bar(x)," \u00B1 ","t * sd / sqrt(n)")))
Run Code Online (Sandbox Code Playgroud)

最后,使用旋转最后一个图会coord_flip()生成非常接近 a 的东西Forest Plot,这是汇总像您这样的数据的标准方法。
ggplot(df1, aes(x=Variable, y=Observation)) +
geom_point(color="red") +
stat_summary(fun.data="mean_cl_normal", conf.int=0.95, geom="errorbar",
width=0.2, colour="blue")+
stat_summary(fun.data="mean_cl_normal", geom="point", size=3,
shape=1, colour="blue")+
geom_hline(aes(yintercept=mean(Observation)), linetype=2)+
labs(title="Forest Plot")+
coord_flip()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
3711 次 |
| 最近记录: |