原创r语言ggplot2误差棒图快速指南数据分析报告论文代码数据Word格式.docx
《原创r语言ggplot2误差棒图快速指南数据分析报告论文代码数据Word格式.docx》由会员分享,可在线阅读,更多相关《原创r语言ggplot2误差棒图快速指南数据分析报告论文代码数据Word格式.docx(9页珍藏版)》请在冰点文库上搜索。
-as.factor(df$dose)head(df)##lensuppdose##14.2VC0.5##211.5VC0.5##37.3VC0.5##45.8VC0.5##56.4VC0.5##610.0VC0.5
len:
牙齿长度
dose:
剂量(0.5,1,2)单位是毫克
supp:
支持类型(VCorOJ)
在下面的例子中,我们将绘制每组中牙齿长度的均值。
标准差用来绘制图形中的误差棒。
首先,下面的帮助函数会用来计算每组中兴趣变量的均值和标准差:
#+++++++++++++++++++++++++#Functiontocalculatethemeanandthestandarddeviation#foreachgroup#+++++++++++++++++++++++++#data:
adataframe#varname:
thenameofacolumncontainingthevariable#tobesummariezed#groupnames:
vectorofcolumnnamestobeusedas#groupingvariablesdata_summary<
-function(data,varname,groupnames){require(plyr)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)##suppdoselensd##1OJ0.513.234.459709##2OJ122.703.910953##3OJ226.062.655058##4VC0.57.982.746634##5VC116.772.515309##6VC226.144.797731有误差棒的直方图
函数
geom_errorbar()可以用来生成误差棒:
library(ggplot2)#Defaultbarplotp<
-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),width=.2,position=position_dodge(.9))print(p)#Finishedbarplotp+labs(title="
Toothlengthperdose"
x="
Dose(mg)"
y=
"
Length"
)+theme_classic()+scale_fill_manual(values=c('
#999999'
'
#E69F00'
))
你可以选择只保留上方的误差棒:
#Keeponlyuppererrorbarsggplot(df2,aes(x=dose,y=len,fill=supp))+geom_bar(stat="
position=position_dodge())+geom_errorbar(aes(ymin=len,ymax=len+sd),width=.2,position=position_dodge(.9))
1
有误差棒的线图#Defaultlineplotp<
-ggplot(df2,aes(x=dose,y=len,group=supp,color=supp))+geom_line()+geom_point()+geom_errorbar(aes(ymin=len-sd,ymax=len+sd),width=.2,position=position_dodge(0.05))print(p)#Finishedlineplotp+labs(title="
y="
)+theme_classic()+scale_color_manual(values=c('
你也可以使用函数
geom_pointrange()
或
geom_linerange()
替换
geom_errorbar()
#Usegeom_pointrangeggplot(df2,aes(x=dose,y=len,group=supp,color=supp))+geom_pointrange(aes(ymin=len-sd,ymax=len+sd))#Usegeom_line()+geom_pointrange()ggplot(df2,aes(x=dose,y=len,group=supp,color=supp))+geom_line()+geom_pointrange(aes(ymin=len-sd,ymax=len+sd))
有均值和误差棒的点图
使用函数
geom_dotplot()
and
stat_summary()
:
Themean+/-SDcanbeadded
as
acrossbar,aerrorbarorapointrange:
p<
-ggplot(df,aes(x=dose,y=len))+geom_dotplot(binaxis='
y'
stackdir='
center'
)#usegeom_crossbar()p+stat_summary(fun.data="
mean_sdl"
fun.args=list(mult=1),geom="
crossbar"
width=0.5)#Usegeom_errorbar()p+stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="
errorbar"
red"
width=0.2)+stat_summary(fun.y=mean,geom="
point"
)#Usegeom_pointrange()p+stat_summary(fun.data=mean_sdl,fun.args=list(mult=1),geom="
pointrange"
)