R语言笔记——ggplot2画回归曲线，添加方程或P值

library(ggplot2)

library(dplyr) #加载dplyr

library(ggpmisc) #加载ggpmisc

library(RColorBrewer)

library(ggpubr)

#载入数据，计算均值和se

windowsFonts(SH = windowsFont("Times New Roman"))

#第一种方案，做点状图，加回归线，添加回归方程和R2

a<- ggplot(data=data,aes(x=Fert, y=Hight))+

geom_point(aes(color=treatment),size = 3)+ #设置分组颜色和点的大小

geom_smooth(method = "lm",linetype=3,se=FALSE,colour="black",span=0.8)+ # 添加回归曲线，se取消置信空间，linetype设置线型

stat_poly_eq(aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')), formula = y ~ x, parse = T,family = "SH") + #添加回归方程和R2

scale_x_continuous()+

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

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

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

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

)+

scale_color_brewer(palette = "YlOrRd")+

theme()

a

#第二种方案，做点状图，加回归线，添加R2和P值

a<- ggplot(data=data,aes(x=Fert, y=Hight))+

geom_point(aes(color=treatment),size = 3)+ #设置分组颜色和点的大小

geom_smooth(method = "lm",linetype=3,se=FALSE,colour="black",span=0.8)+ # 添加回归曲线，se取消置信空间，linetype设置线型

stat_fit_glance(method = 'lm',

method.args = list(formula = y ~ x),

mapping = aes(label = sprintf('R^2~"="~%.3f~~italic(P)~"="~%.2g', stat(r.squared), stat(p.value))),

parse = TRUE,label.x = 0.95,label.y = 0.95,family = "SH")+

#方案2，仅添加R2P值，label.xlabel.y设置文字位置。

scale_x_continuous()+

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

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

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

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

)+

scale_color_brewer(palette = "YlOrRd")+

theme()

a

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

全部作者的其他最新博文

GMT+8, 2024-6-21 15:51