查看原文
其他

R可视化——分组散点图的绘制以及拟合曲线和回归方程的添加!

王志山 科研后花园 2023-09-08
 

点击上方

“科研后花园”

关注我们


代码如下

1、加载绘图包

rm(list=ls())#clear Global Environmentsetwd('D:/桌面/分组散点图')#设置工作路径
#加载R包library(ggplot2) # Create Elegant Data Visualisations Using the Grammar of Graphicslibrary(ggpmisc) # Miscellaneous Extensions to 'ggplot2'library(RColorBrewer) # ColorBrewer Paletteslibrary(grid) # The Grid Graphics Packagelibrary(scales) # Scale Functions for Visualization

2、读取数据——以Chiplot绘图平台数据为例

df <- read.table(file="data.txt",sep="\t",header=T,check.names=FALSE)

3、自定义颜色

#自定义颜色col<-c("#be0027", "#cf8d2e")#构建背景色color1 <- colorRampPalette(brewer.pal(11,"PiYG"))(30)color2 <- colorRampPalette(brewer.pal(11,"PuOr"))(30)

4、绘图

p <- 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_poly_eq(formula = y ~ x, aes(color=group,label = paste(after_stat(eq.label), ..rr.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='#333c41',size=12), legend.text = element_text(color='#333c41',size=12), legend.title = element_blank())+ labs(x=NULL,y=NULL)p

5、添加背景

grid.raster(alpha(color1, 0.2), width = unit(1, "npc"), height = unit(1,"npc"), interpolate = T)

6、分面并添加背景

p+facet_grid(~group, scales = "free")+ theme(legend.position = "none")#添加背景grid.raster(alpha(color2, 0.2), width = unit(1, "npc"), height = unit(1,"npc"), interpolate = T)

温馨提示

如果你喜欢本文,请分享到朋友圈,想要获得更多信息,请关注我。





您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存