# R语言笔记——向ggplot2箱图添加显著性差异字母标识

R语言笔记——向ggplot2箱图添加显著性差异字母标识

1.        读取数据

2.        计算数据均值和sd值，使用summarySE

sd<- summarySE(data, measurevar="Hight", groupvars = c("treatment","month"))

3. 计算处理间显著性差异，使用agricolae包中的LSD.test

library("agricolae") #加载包

Jul<-data[month==7,] #提取7月份数据

attach(Jul) #加载数据

model<-aov(Hight~treatment) #7月数据方差分析,以下3句为一套语句。

bijiao<-LSD.test(model,"treatment",alpha=0.05,p.adj = c("bonferroni"),group = TRUE,main = "Height")

bijiao

detach(Jul)

4. 23的数据结果导入Excel中，暂时使用复制-粘贴方法，在Excel中整理排列数据，将数据存储为lsd.csv文件，整理好的数据如下：

5. 作图，用ggplot2

library(ggplot2)

library(RColorBrewer)

library(Rmisc)

library(ggpubr)

data$month<-factor(data$month,levels=c("7","8"),ordered = TRUE) #月份因子化

windowsFonts(SH = windowsFont("Times New Roman")) #设置字体

#ggplot做箱图

H_Jul<-ggplot(data=data[data$month=="7",],aes(x=treatment, y=Hight,fill=treatment))+ geom_boxplot()+ geom_text(data=lsd[lsd$month=="7",],aes(x=treatment,y=Hight+Hsd+2,label=Ha),family="SH")+ #添加显著性差异字母

scale_x_discrete(name=" ",breaks = c("L0","L1","L2","L3","L4","L5","L6"))+

scale_y_continuous(expand = c(0, 0),#设定x轴和y轴的交叉点

name ="Height (cm)",#设定y轴标题

breaks=seq(0,50,10),#设定y轴的数据间隔

limits = c(10,50) #设定y轴的数据上下限

)+

annotate("text",x="L3",y=48,label="Jul",parse=T,family="SH",fontface="bold",size=4,alpha = .8)+  #添加文字标注,alpha设置透明度

theme(axis.title.y = element_text(face="plain",size="14",color = "black",family = "SH"),

axis.title.x = element_text(face="plain",size="14",color = "black",family = "SH"),

axis.text.x =  element_text(size="12",color = "black",family = "SH"),

axis.text.y =  element_text(size="12",color = "black",family = "SH"),

panel.background = element_rect(fill = "transparent",color="black"),

panel.border = element_rect(fill = "transparent",color = "black",linetype = 1),

panel.grid =element_blank(),

legend.text = element_text(colour="black", size = 11, face = "plain"),

legend.title=element_blank())+

scale_fill_brewer(palette = "YlOrBr")

H_Jul

https://blog.sciencenet.cn/blog-587128-1211583.html

## 全部精选博文导读

GMT+8, 2024-6-22 08:46