本文首發(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 的 ylim
和xlim
適當調(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|theme主題設(shè)置,詳解繪圖優(yōu)化-“精雕細琢”
ggplot2 |legend參數(shù)設(shè)置,圖形精雕細琢
參考資料:
https://github.com/cran/ggpmisc
PS:有個交流的討論組,公眾號后臺回復(fù)”入群“,歡迎交流。
◆ ◆ ◆ ◆ ◆