ggplot绘制散点图并添加拟合曲线和方程

载入包

建完回归模型后想看一下模型的效果,文献中一般都是使用散点图+lm拟合曲线+Rsquared来表示

  • Cairo包用来导出pdf图片,尝试过多种通过代码保存pdf的方法,最后发现Cairo最好用,很少遇到字体不兼容的问题
pacman::p_load(ggplot2,ggtrendline,Cairo)

看一下我的数据

> end_data
       predict     real
3192T 3.743376 3.567744
3222T 3.716128 3.660186
3229T 3.894045 3.964088
3262T 3.920661 4.113444
3274T 4.026531 4.145387
3278T 3.736389 3.698550
3282T 3.723784 3.641492
3294T 3.792821 3.846829
3385T 3.761303 3.884813
3419T 3.792147 3.674821

ggtrendline函数

R包ggtrendline中的ggtrendline函数可以快速构建拟合曲线,其中method函数用来指定拟合曲线的类型

  • “line2P” (formula as: y=a*x+b),
  • “line3P” (y=ax^2+bx+c),
  • “log2P” (y=a*ln(x)+b),
  • “exp2P” (y=aexp(bx)),
  • “exp3P” (y=aexp(bx)+c),
  • “power2P” (y=a*x^b),
  • and “power3P” (y=a*x^b+c).

ggtrendline函数的返回值

  • 其返回值中明确的包含了R^2,p值等信息,并且会自动添加到图上
  • 也可以在使用该函数计算想要的统计量之后,通过ggplot绘制散点图并使用geom_smooth(method=“lm”)达到同样的效果,最后再将统计量添加到图上,个人感觉直接使用ggtrendline会更简便,而且支持ggplot的主题系统和图层添加功能;
> ggtrendline(end_data$predict,end_data$real)

Call:
lm(formula = y ~ x)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.13173 -0.05057  0.00246  0.04718  0.15333 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   -2.986      1.161   -2.57  0.03300 *  
x              1.786      0.304    5.87  0.00038 ***
---
Signif. codes:  0***0.001**0.01*0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.094 on 8 degrees of freedom
Multiple R-squared:  0.811,	Adjusted R-squared:  0.788 
F-statistic: 34.4 on 1 and 8 DF,  p-value: 0.000376


N: 10 , AIC: -15.1 , AICc: -11.1 , BIC:  -14.2 
Residual Sum of Squares:  0.0707

在这里插入图片描述

添加散点图并优化字体及其他主题

windowsFonts(TNR=windowsFont("Times New Roman"))#设置PDF字体

ggtrendline(end_data$predict,end_data$real,
	eSize = 4,#用来控制方程和统计量的字体大小
	eq.x = 3.8,eq.y = 4.25,rrp.x = 3.8,rrp.y =4.2)+#这四个参数可以分别用来控制回归方程和其他两个统计量的位置
  	geom_point(aes(end_data$predict,end_data$real))+
  	theme(axis.line = element_line(size=1),
        panel.background = element_blank(),
        text = element_text(family = "TNR",size = 15))+
  	labs(x="Predicted sorafenib AUC by Random Forest",y="Observed sorafenib AUC")->p
  p

在这里插入图片描述

保存为pdf

CairoPDF(file = "sorafenib_auc_model",width = 8.21,height = 6.63)
p
dev.off()
system("sorafenib_auc_model.pdf")#explorer 可以在windows系统上可以直接打开刚刚保存的pdf
  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值