关于算法:r语言ggplot2误差棒图快速指南

5次阅读

共计 2316 个字符,预计需要花费 6 分钟才能阅读完成。

原文链接:http://tecdat.cn/?p=5506

给直方图和线图增加误差棒

筹备数据

这里应用 ToothGrowth 数据集。

library(ggplot2) 
df <- ToothGrowth 
df$dose <- as.factor(df$dose) 
head(df) 
## len supp dose ## 1 4.2 VC 0.5 ## 2 11.5 VC 0.5 ## 3 7.3 VC 0.5 ## 4 5.8 VC 0.5 ## 5 6.4 VC 0.5 ## 6 10.0 VC 0.5

len : 牙齿长度
dose : 剂量 (0.5, 1, 2) 单位是毫克
supp : 反对类型 (VC or OJ)

在上面的例子中,咱们将绘制每组中牙齿长度的均值。标准差用来绘制图形中的误差棒。

首先,上面的帮忙函数会用来计算每组中趣味变量的均值和标准差:

#+++++++++++++++++++++++++ 
# 计算每个组的均值和标准差 #+++++++++++++++++++++++++ 
# data : a data frame 
# varname : 蕴含变量的列名  
#要汇总的 #groupnames : 列名的向量,作为 #分组变量应用  
data_summary <- function(data, varname, groupnames){summary_func <- function(x, col){c(mean = mean(x\[\[col\]\], na.rm=TRUE), sd = sd(x\[\[col\]\], na.rm=TRUE)) } 
data\_sum<-ddply(data, groupnames, .fun=summary\_func, varname) 
data\_sum <- rename(data\_sum, c("mean" = varname)) 
return(data_sum) 
}

统计数据 

df2 <- data_summary(ToothGrowth, varname="len", groupnames=c("supp", "dose")) 
# 把剂量转换为因子变量 
df2$dose=as.factor(df2$dose) head(df2) 
## supp dose len sd ## 1 OJ 0.5 13.23 4.459709 ## 2 OJ 1 22.70 3.910953 ## 3 OJ 2 26.06 2.655058 ## 4 VC 0.5 7.98 2.746634 ## 5 VC 1 16.77 2.515309 ## 6 VC 2 26.14 4.797731 有误差棒的直方图 

函数 geom_errorbar() 能够用来生成误差棒:

p<- ggplot(df2, aes(x=dose, y=len, fill=supp)) + geom\_bar(stat="identity", color="black", position=position\_dodge()) + geom_errorbar(aes(ymin=len-sd, ymax=len+sd),) 
print(p) # 条形图 

你能够抉择只保留上方的误差棒:

# 只保留上部的误差条 
ggplot(df2, aes(x=dose, y=len, fill=supp)) + geom\_bar(stat="identity", color="black", position=position\_dodge()) + geom_errorbar(aes(ymin=len, ymax=len+sd), width=.2)

1

  

 有误差棒的线图 
p<- ggplot(df2, aes(x=dose, y=len, group=supp, color=supp)) position=position_dodge(0.05)) print(p) 
#线图 
p+labs(title="Tooth length per dose", x="Dose (mg)

你也能够应用函数 geom\_pointrange() 或 geom\_linerange() 替换 geom_errorbar()

# 用 geom_pointrange 
geom_pointrange(aes(ymin=len-sd, ymax=len+sd)) 
# 用 geom\_line()+geom\_pointrange() 
 geom\_line()+ geom\_pointrange(aes(ymin=len-sd, ymax=len+sd))

 
 

有均值和误差棒点图

应用函数 geom\_dotplot() and stat\_summary():

 平均值 +/-SD 能够作为误差条或点范畴增加。# 用 geom_crossbar() 
p + stat\_summary(fun.data="mean\_sdl", fun.args = list(mult=1), geom="crossbar", width=0.5) 
# 用 geom_errorbar() 
 geom="errorbar", color="red", width=0.2) + stat_summary(fun.y=mean, geom="point", color="red") 
# 用 geom_pointrange() 
summary(fun.data=mean_sdl, fun.args = list(mult=1))
正文完
 0