【R语言】绘制误差线图+数据分布+显著性分析
2022-04-19 本文已影响0人
巩翔宇Ibrahimovic
写在前面
绘制一个生物学研究中最普遍的图,误差线图+数据分布+显著性分析。
数据准备
自行编写一个数据集,无实际意义。
options(stringsAsFactors = F)
rm(list=ls())
#创建数据集
vec <- c("N","P","Q")
dff <- data.frame()
for(i in 1:length(vec)){
df <- data.frame(group=vec[i],runif(30))
dff <- rbind(dff,df)
}
#编写函数计算平均值和标准差
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm = T),
sd = sd(x[[col]], na.rm = T))
}
data_sum <- ddply(data, groupnames, .fun = summary_func, varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
#测试函数的功能
df2 <- data_summary(dff, varname = "runif.30.", groupnames = c("group"))
df2$count <- c(30,30,30)
colnames(df2) <- c("group","mean","sd","count")
绘图
p<- ggplot()+
geom_bar(data=df2,mapping=aes(x=group,y=mean), #柱状图
fill = "white",
size = 1.5,
#color = c("#1E90FF","gold","red"),
position="dodge", # 柱状图格式
stat="identity", # 数据格式
width = 0.6)+ # 柱状图尺寸
geom_jitter(data=dff, #散点
mapping=aes(x=group,y=runif.30.,fill = group,colour = group,shape = group),
size = 2,
height = 0.05,#散点纵向抖动
width = 0.1)+scale_fill_aaas()+ #散点横向抖动
# scale_color_manual(values = c("#1E90FF","gold","red"))+ #散点颜色
geom_signif(data=dff,mapping=aes(x=group,y=runif.30.), # 不同组别的显著性
comparisons = list(c("N", "P"), # 哪些组进行比较
c("N", "Q"),
c("P", "Q")),
#annotation=c("**"), # 显著性差异做标记
#map_signif_level=T, # T为显著性,F为直接显示p value
#tip_length=c(0,0,0,0,0,0), # 修改显著性线两端的长短
y_position = c(1,1.5,1), # 设置显著性线的位置高度,每个数值代表每个组
#size=1, # 修改线的粗细
#textsize = 7, # 修改*标记的大小
test = "t.test")+ # 检验的类型
geom_errorbar(data=df2,mapping=aes(x = group,ymin = mean-sd, ymax = mean+sd), # 误差线添加
width = 0.3, #误差线的宽度
color = c("black"), #颜色
size=0.8)+ #粗细
scale_y_continuous(limits =c(0, 2) ,expand = c(0,0))+ # y轴的范围
theme_classic( # 主题设置,这个是无线条主题
base_line_size = 1 # 坐标轴的粗细
)+
labs(title="White blood cell(WBC)",x="",y="Retive_Abundance")+ # 添加标题,x轴,y轴内容
theme(plot.title = element_text(size = 15,
colour = "black",
hjust = 0.5),
axis.title.y = element_text(size = 15,
# family = "myFont",
color = "black",
face = "bold",
vjust = 1.9,
hjust = 0.5,
angle = 90),
legend.title = element_text(color="black", # 修改图例的标题
size=15,
face="bold"),
legend.text = element_text(color="black", # 设置图例标签文字
size = 10,
face = "bold"),
axis.text.x = element_text(size = 13, # 修改X轴上字体大小,
color = "black", # 颜色
face = "bold", # face取值:plain普通,bold加粗,italic斜体,bold.italic斜体加粗
vjust = 0.5, # 位置
hjust = 0.5,
angle = 0), #角度
axis.text.y = element_text(size = 13,
color = "black",
face = "bold",
vjust = 0.5,
hjust = 0.5,
angle = 0)
)
p
最后出图的效果:
image.png
我选的都是随机数据,没有差异也算是意料之内把。
参考链接:
1.https://mp.weixin.qq.com/s/19yZc8_HDoJ2w-e1h-k58Q
2.https://www.jianshu.com/p/634f6061a9cb
3.https://cloud.tencent.com/developer/article/1692505
后记
我还想做一种图,是把差异的结果用ABCD表示,但是我发现,好像ggplot做不了,找到了一个老哥写的帖子,后面好好学习一下。https://www.jianshu.com/p/e11164ee0577