|||
R语言笔记——向ggplot2箱图添加显著性差异字母标识
1. 读取数据
data<-read.csv("E:/R/Rfiles/yangfentianjia/20191220_data.csv") #载入数据,数据格式如下:
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. 将2和3的数据结果导入Excel中,暂时使用复制-粘贴方法,在Excel中整理排列数据,将数据存储为lsd.csv文件,整理好的数据如下:
5. 作图,用ggplot2包
library(ggplot2)
library(RColorBrewer)
library(Rmisc)
library(ggpubr)
data<-read.csv("E:/R/Rfiles/yangfentianjia/20191220_data.csv") #加载原始数据文件
data$month<-factor(data$month,levels=c("7","8"),ordered = TRUE) #月份因子化
windowsFonts(SH = windowsFont("Times New Roman")) #设置字体
lsd<-read.csv("E:/R/Rfiles/yangfentianjia/20191220_data_lsd.csv") #读取lsd数据文件
#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
出图效果如下:
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-25 20:18
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社