1. 加載工具包
lbs = c("car","emmeans","dplyr","multcompView")
lapply(lbs,require,character.only = T)
2. 加載數(shù)據(jù)
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) %>% #計算各組均值和標準誤以及置信區(qū)間
cld(alpha = 0.05, Letters = letters,adjust = "tukey") # 設(shè)定顯著性閾值蘸炸,進行差異標記舀瓢,letters為小寫字母呆抑,LETTERS為大寫字母
4. 結(jié)果整理和成圖
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反轉(zhuǎn)
guides(fill = FALSE) + #不顯示圖例
labs(x= "stage of succession (in years)", y = "" )+
scale_x_discrete(limits = rev(levels(res$year)))+ #因為圖經(jīng)過反轉(zhuǎn)之后宾袜,x軸的順序也發(fā)生了反轉(zhuǎn)速侈,故這里進行校正
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)))+#在圖像區(qū)域內(nèi)部增大坐標軸標題與標簽的距離显设,直接使用vjust = 5會使標題字體突破圖像區(qū)域
geom_text(aes(label = .group),hjust = 3,color = 'black',size = 10,fontface='bold')
#輸出圖片
ggsave(p,filename = 'barplot.jpg',width = 10, height = 8,dpi = 600)