R语言ggplot2绘制两个分组的柱状图

#运行ggplot2

library(ggplot2)

#读取数据

library(xlsx)#导入xlsx或者xls文件,其他文件不需要

workbook<- ("D:/Adata/First/abundance.xlsx")#导入文件的路径,根据自己的文件位置修改所需要的路径

stat<-read.xlsx(workbook,1)#导入第一个表格

stat#查看数据

stat$OTUID<-factor(stat$OTUID,levels = c('S10','S20','S30'))#修改处理名称

#给细菌类群按丰度高低排个序,下面的丰度从低到高排列,出的图从长到短

stat$Sample<-factor(stat$Sample, levels = c("Allorhizobium--ASV86","unclassified--ASV37","Pseudomonas--ASV4","Pseudomonas--ASV3","unclassified--ASV17",    "Acinetobacter--ASV2","unclassified--ASV21","unclassified--ASV1","Bacillus--ASV5"))

#ggplot2 分组柱状图

p1 <- ggplot(stat, aes(y=average, x=Sample, fill =OTUID))+

  geom_col(position = position_dodge(width = 0.8), width = 0.8) +

  geom_errorbar(aes(ymin = average-bzc, ymax = average+bzc), width = 0.25, size = 0.2, position = position_dodge(0.9)) +#添加标准误差线

  geom_text(aes(label = xz, vjust = 0.3, hjust = -1.5), size=4.3, position = position_dodge(0.8)) +#添加显著性

  scale_fill_manual(values = c("#FF5400B2","#00FF87B2", "#0000AAB2")) +

  labs(title = NULL, x = NULL, y = 'Relative abundance (%)', fill = NULL) +

  theme(panel.grid = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = 'black'), legend.position = c(0.9, 0.85)) +

  theme(axis.text.x = element_text(size = 14, angle = 0, hjust = 0.5,color = 'black'))+

  theme(axis.text.y  = element_text(size = 12, angle = 0, hjust = 0.5,color = 'black'))+

  scale_y_continuous(expand = c(0, 0), limit = c(0, 30))+#limit是限制y轴的长度,以最长轴加标准差为最小,不然会缺失

  coord_flip();p1

下面是数据的格式

你可能感兴趣的:(R语言ggplot2绘制两个分组的柱状图)