geom_bars下面的重要字母

时间:2016-11-10 00:11:17

标签: r ggplot2 statistics data-visualization reshape

这是iris数据集的条形图。每个条形图上方的字母表示从kruskal-wallis测试中获得的显着差异。 enter image description here虽然它们在这个示例图中并不太杂乱,但我的真实数据有更大的误差条和条形长度的差异。因此,字母遍布整个地方,变得难以阅读。我想知道是否可以将字母放在每个条形图下方,就在x轴上方。通过这种方式,它们都可以对齐并且易于阅读。你觉得怎么样?

代码:

library(reshape2)
library(ggplot2)
library(agricolae)
library(Rmisc)

file<-iris

melt <- melt(file, id=c("Species"))

x1 <- summarySE(melt, measurevar = "value", groupvars = c("variable", "Species"), na.rm=TRUE)

d=list()
tmp=list()

for(i in 1:4){
  if(var(file[,i]) > 0){
    tmp<-c(tmp,colnames(file[i]))
    krusk <- kruskal(file[,i],file[,5],group=TRUE)
    krusk$groups<-krusk$groups[order(krusk$groups[,'trt']),]
    d[[i]]<-as.data.frame(krusk$groups)       
  }
} 

big_data=do.call(rbind,d)

plot<- ggplot(x1, aes(x = variable, y = value, fill = Species)) + 
  coord_flip()+
  geom_bar(stat = "identity", position =position_dodge(),colour="black",width=.7,size=.5)+ 
  geom_errorbar(aes(ymin=value-se, ymax=value+se), width=.1,size=.5,position=position_dodge(.7))+
  theme(
    axis.text = element_text(angle=0, vjust=1,size=8,face="bold"),legend.title=element_blank(),legend.position="bottom",
    legend.text=element_text(face="italic"))+
  labs(title=NULL,x=NULL,y=NULL)+
  geom_text(aes(label=big_data$M,colour=Species),position=position_dodge(width=1),vjust=.8,hjust=-1,size=3)

plot

1 个答案:

答案 0 :(得分:2)

这样的事情:
对于geom_text,请设置y = 0hjust = 1.5 请注意,条形,误差条和文本的躲避宽度是相同的。还要注意,条的宽度等于躲避宽度,因此条在每个变量内相互对接。

plot <- ggplot(x1, aes(x = variable, y = value, fill = Species)) + 
  coord_flip() +
  geom_bar(stat = "identity", position = position_dodge(width = .7),
     colour = "black", width = .7, size = .5) + 
  geom_errorbar(aes(ymin = value-se, ymax = value+se), position=position_dodge(width = .7),
     width = .1, size = .5) +
  geom_text(aes(y = 0, label = big_data$M, colour = Species), 
     position=position_dodge(width = .7), hjust = 1.5, size = 3) +
  theme(
    axis.text = element_text(angle=0, vjust=1,size=8,face="bold"),legend.title=element_blank(),legend.position="bottom",
    legend.text=element_text(face="italic")) +
  labs(title=NULL,x=NULL,y=NULL)

plot