其他
R绘图模板——散点图+拟合曲线+边际组合图形!!!
点击上方
“科研后花园”
关注我们
图片灵感来源:
1、设置工作环境并加载所需R包:
rm(list=ls())#clear Global Environment
setwd('D:/桌面散点图+拟合曲线+边际组合图形')#设置工作路径
#加载R包
library(ggplot2) # Create Elegant Data Visualisations Using the Grammar of Graphics
library(ggpmisc) # Miscellaneous Extensions to 'ggplot2'
library(ggpubr) # 'ggplot2' Based Publication Ready Plots
library(gghalves) # Compose Half-Half Plots Using Your Favourite Geoms
2、加载绘图数据(根据原文图片随机编写数据,无实际意义):
df <- read.table(file="data.txt",sep="\t",header=T,check.names=FALSE)
3、绘图:
#自定义颜色
col<-c("#0099e5")
###绘图
#散点图
p1 <- ggplot(df,aes(x,y,fill=group))+
geom_point(shape=21,size=3,alpha=0.5)+
geom_smooth(method = "lm",aes(color=group), se=T,
formula = y ~ x,
linetype=1,alpha=0.5)+
stat_cor(color=col,method = "pearson",label.x = 0.2, label.y = 8.5,size=4)+
stat_poly_eq(formula = y ~ x,
aes(color=group,label = paste(after_stat(eq.label),
sep = "~~~")), parse = TRUE) +
scale_fill_manual(values = col)+
scale_color_manual(values = col)+
theme_bw()+
theme(panel.grid=element_blank(),
axis.text=element_text(color='black',size=12),
axis.title = element_text(color='black',size=14),
legend.position = "none")+
labs(x="The title of x",y="The title of y")
p1
###添加边际组合图形——散点+箱线图+半小提琴
# 右边边际图
p2 <- ggplot(df,aes(1,y))+
geom_half_violin(fill="#00d1b2",position = position_nudge(x=0.26),side = "r",width=0.5,color=NA)+
geom_boxplot(fill="#ff4c4c",width=0.1,size=1.2,outlier.color =NA,position = position_nudge(x=0.2))+
geom_jitter(fill="#0099e5",shape=21,size=3,width=0.12,alpha=0.5)+
theme_void()+
theme(legend.position = "none")
p2
#顶部边际图
p3 <- ggplot(df,aes(1,x))+
geom_half_violin(fill="#00d1b2",position = position_nudge(x=0.26),side = "r",width=0.5,color=NA)+
geom_boxplot(fill="#ff4c4c",width=0.1,size=1.2,outlier.color =NA,position = position_nudge(x=0.2))+
geom_jitter(fill="#0099e5",shape=21,size=3,width=0.12,alpha=0.5)+
theme_void()+
theme(legend.position = "none")+
coord_flip()
p3
#组合图形——基于aplot包进行组合
library(aplot) # Decorate a 'ggplot' with Associated Information
p1%>%insert_top(p3,height = 0.4)%>%
insert_right(p2,width = 0.4)
PS: 以上内容是小编个人学习代码笔记分享,仅供参考学习,欢迎大家一起交流学习。
完整代码(附带注释)及原始数据获取:
夸克网盘(手机端下载夸克APP进行搜索提取):
链接:https://pan.quark.cn/s/bb4a6ac85ac9
提取码:U7Zb
R绘图模板合集获取可见此推文:R绘图模板源代码获取!
温馨提示
如果你喜欢本文,请分享到朋友圈,想要获得更多信息,请关注我。