BioStatR语言R数据可视化

R语言之为柱形图添加ABCD差异标记

2019-03-22  本文已影响17人  Oodelay

1. 加载工具包

lbs = c("car","emmeans","dplyr","multcompView")
lapply(lbs,require,character.only = T)

2. 加载数据

df= read.table('barplot.txt',row.names = 1, header = T)
summary(df)
str(df)

3. 拟合和注释

fit = lm(richness ~ year, df) # 线性回归

sig = fit %>% anova() %>% as.data.frame() # 差异分析

res = fit %>% 
  emmeans( ~ year) %>%  #计算各组均值和标准误以及置信区间
  cld(alpha = 0.05, Letters = letters,adjust = "tukey") # 设定显著性阈值,进行差异标记,letters为小写字母,LETTERS为大写字母

4. 结果整理和成图

res$year = gsub('y','',res$year) #去除名称的字符
res$year = factor(res$year, #定义变量中元素的出图顺序
                  levels = c('0','0-150','150-300','300-550','550-630'))

library('ggplot2')

p <- ggplot(res,aes(x = year, y = emmean,fill = year))+ 
  theme_bw()+
  geom_bar(stat = 'identity',width = 0.5)+
  coord_flip()+  #x.y反转
  guides(fill = FALSE) + #不显示图例
  labs(x= "stage of succession (in years)", y = "" )+
  scale_x_discrete(limits = rev(levels(res$year)))+ #因为图经过反转之后,x轴的顺序也发生了反转,故这里进行校正
  geom_errorbar(aes(ymax = emmean + SE, ymin = emmean - SE), 
                position = position_dodge(0.9), width = 0.2,lwd = 2)+ # 添加误差线
  theme(axis.text = element_text(face = 'bold',color = 'black',size = 15),
        axis.title.y = element_text(face = 'bold',color = 'black',size = 20, 
                                    margin = margin(t = 0, r = 30, b = 0, l = 0)))+#在图像区域内部增大坐标轴标题与标签的距离,直接使用vjust = 5会使标题字体突破图像区域
  geom_text(aes(label = .group),hjust = 3,color = 'black',size = 10,fontface='bold')

#输出图片
ggsave(p,filename = 'barplot.jpg',width = 10, height = 8,dpi = 600)
上一篇下一篇

猜你喜欢

热点阅读