ggplot画标准误条形图加显著性标记(愚蠢)
2019-03-19 本文已影响0人
白云梦_7
一、准备工作,计算SEM,仅作为示例
df <- ToothGrowth(R语言数据集)
image.png
计算数据的标准误(aggregate函数)
mean<-aggregate(df$len,by=list(df$supp,df$dose),FUN=mean) #计算均值
sd<-aggregate(df$len,by=list(df$supp,df$dose),FUN=sd) #计算标准差
N<-aggregate(df$len,by=list(df$supp,df$dose),FUN=length) #计算个数
data<-data.frame(mean,sd=sd$x,N=N$x)#合并数据框
colnames(data)=c("supp","dose","len","sd","N")
data$se <- data$sd / sqrt(data$N) #计算标准误
查看统计数据:
image注:画图前将dose列的类型更改为factor型
data$dose =as.factor(data$dose)
这是因为如果dose是数值型向量将会作为连续型数据进行处理,而因子型变量则会被作为离散型数据进行处理。
二、画图(以下数据与上面来源不同,但形式相同(懒得再来一次))
dddd$type=factor(dd$type,levels = rev(unique(dd$type)))
#规定显示顺序
ggplot(dd,aes(x=week,y=con,fill=type))+
geom_bar(position = position_dodge(),color="black",stat = "identity",width = .3)+
geom_errorbar(aes(ymin=con, ymax=con+se),width=.2,position = position_dodge(.3))+
+ scale_fill_manual(values=c("blue","red"))+
#自定义颜色
+ theme(legend.position="right",
+ axis.title.x =element_text(size=14),
+ axis.title.y=element_text(size=14),
#去掉图例的标题
+ panel.grid.major =element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(),
#以上是去掉网格和背景色
+ axis.line = element_line(colour = "black"),
+ axis.text = element_text(color = "black",size = 14))+
+ xlab("Weeks")+ylab("Plamsa glucose concentration (mmol/L)")+
+ scale_y_continuous(breaks = seq(0,13,1),limits=c(0,13),expand = c(0,0))+
#自定义坐标轴,expand=c(0,0),使得y轴与x轴无缝衔接
#加数值geom_text(label=dd$con,colour = "black", vjust=-0.5)
+ geom_segment(aes(x=0.93, y=8.75, xend=0.93, yend=9.2))+geom_segment(aes(x=1.07, y=8.75, xend=1.07, yend=9.2))+geom_segment(aes(x=0.93, y=9.2, xend=1.07, yend=9.2))+annotate("text", x=1, y=9.3, label="***", size=5)+geom_segment(aes(x=1.92, y=11.2, xend=1.92, yend=11.65))+geom_segment(aes(x=2.08, y=11.2, xend=2.08, yend=11.65))+geom_segment(aes(x=1.92, y=11.65, xend=2.08, yend=11.65))+annotate("text", x=2.00, y=11.75, label="**", size=5)+geom_segment(aes(x=1.07, y=12, xend=1.07, yend=12.45))+geom_segment(aes(x=2.08, y=12, xend=2.08, yend=12.45))+geom_segment(aes(x=1.07, y=12.45, xend=2.08, yend=12.45))+annotate("text", x=1.55, y=12.52, label="**", size=5)
#显著性标记,这方法太蠢了……
image.png