R-ggpmisc|回歸曲線添加回歸方程,R2,方差表,香不香?

本文首發(fā)于“生信補給站”,https://mp.weixin.qq.com/s/_rTWJHcbUu2Eqtex74gUBA

散點圖繪制回歸曲線很常用,那么添加上回歸方程,P值,R2或者方差結(jié)果表等可以展示更量化的信息。

那加起來復(fù)雜嗎?還真不一定!

一 載入數(shù)據(jù)和R包

使用內(nèi)置數(shù)據(jù)集

library(ggplot2) #加載ggplot2包
library(dplyr) #加載dplyr包
library(ggpmisc) #加載ggpmisc包
#展示 使用Species為setosa的亞集
iris2 <- subset(iris,Species == "setosa")

二 回歸曲線的可能性

1, 繪制點圖,添加回歸線

#散點圖
p <- ggplot(iris2, aes(Sepal.Length, Sepal.Width)) +
  geom_point(color = "grey50",size = 3, alpha = 0.6)
#回歸線
#添加回歸曲線
p + stat_smooth(color = "skyblue", fill = "skyblue", method = "lm")
img

2, 連接點到線

p + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm")+
  stat_fit_deviations(formula = y ~ x, color = "skyblue")
img

3,添加回歸公式

stat_poly_eq參數(shù)添加公式,內(nèi)含參數(shù)可調(diào)整位置等

p + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm") +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')),
    formula = y ~ x,  parse = TRUE,
      size = 5, #公式字體大小
      label.x = 0.1,  #位置 ,0-1之間的比例
      label.y = 0.95)
img

4, 添加方差結(jié)果表

p +  ylim(2,5) + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm") +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')),
    formula = y ~ x,  parse = TRUE,size = 3,label.x = 0.1, label.y = 0.99) +
  stat_fit_tb(tb.type = 'fit.anova',
    label.y.npc = "top", label.x.npc = "left",
  )
img

注:此處僅為展示 ,label.y.npc 為另一種調(diào)整位置的方式 ,用label.y可完全避免重疊

如擔心方差表和公示與圖重疊,可以通過ggplot2 的 ylimxlim適當調(diào)整,然后調(diào)整位置即可。

5,細節(jié)優(yōu)化方差表

上述方差表中的行名,列名,以及NA,,,稍加調(diào)整后,看起來更“專業(yè)”

p +  ylim(2,5) + 
  stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm") +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~')),
    formula = y ~ x,  parse = TRUE,size = 4,label.x = 0.1, label.y = 0.95) +
  stat_fit_tb(method = "lm",
              method.args = list(formula = y ~ x),
              tb.type = "fit.anova",
              tb.vars = c(Effect = "term", 
                          "df",
                          "M.S." = "meansq", 
                          "italic(F)" = "statistic", 
                          "italic(P)" = "p.value"),
              label.y = 0.87, label.x = 0.1,
              size = 4,
              parse = TRUE
  ) +
theme_classic()
img
其他:既然是ggplot2的擴展包,ggplot2的一些參數(shù)亦可使用:

ggplot2|詳解八大基本繪圖要素

ggplot2|theme主題設(shè)置,詳解繪圖優(yōu)化-“精雕細琢”

ggplot2 |legend參數(shù)設(shè)置,圖形精雕細琢

ggplot2|ggpubr進行“paper”組圖合并

參考資料:

https://github.com/cran/ggpmisc

PS:有個交流的討論組,公眾號后臺回復(fù)”入群“,歡迎交流。

◆ ◆ ◆ ◆ ◆

精心整理(含圖版)|R語言生信分析,可視化,你要的全拿走,建議收藏!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容