苏华的个人博客分享 http://blog.sciencenet.cn/u/Hunshandake

博文

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

已有 22521 次阅读 2020-1-2 15:35 |个人分类:软件使用|系统分类:科研笔记| ggplot, 回归, P值, geom_smooth

library(ggplot2)

library(dplyr) #加载dplyr

library(ggpmisc) #加载ggpmisc

library(RColorBrewer)

library(ggpubr)

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

caomuxi<-read.csv("E:/R/Rfiles/data.csv")

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

出图如下:

image.png

#第二种方案,做点状图,加回归线,添加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

出图如下:

image.png






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

上一篇:R语言笔记——向ggplot2箱图添加显著性差异字母标识
下一篇:退耕还林(草)工程
收藏 IP: 159.226.89.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-16 21:16

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部