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


本文首發於“生信補給站”,https://mp.weixin.qq.com/s/_rTWJHcbUu2Eqtex74gUBA

 

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

那加起來復雜嗎?還真不一定!

 

一 載入數據和R包

使用內置數據集

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參數添加公式,內含參數可調整位置等

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, 添加方差結果表

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 為另一種調整位置的方式 ,用label.y可完全避免重疊

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

 

5,細節優化方差表

上述方差表中的行名,列名,以及NA,,,稍加調整后,看起來更“專業”

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的一些參數亦可使用:

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

ggplot2|theme主題設置,詳解繪圖優化-“精雕細琢”

ggplot2 |legend參數設置,圖形精雕細琢

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

 

參考資料:

https://github.com/cran/ggpmisc

 

PS:有個交流的討論組,想溝通交流的,公眾號后台回復”入群“。

◆ ◆ ◆ ◆ ◆

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM