散點圖繪制回歸曲線很常用,那么添加上回歸方程,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")
2, 連接點到線
p +
stat_smooth(color = "skyblue", formula = y ~ x,fill = "skyblue", method = "lm")+
stat_fit_deviations(formula = y ~ x, color = "skyblue")
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)
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",
)
注:此處僅為展示 ,label.y.npc 為另一種調整位置的方式 ,用label.y可完全避免重疊
如擔心方差表和公示與圖重疊,可以通過ggplot2 的 ylim
和xlim
適當調整,然后調整位置即可。
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()
其他:既然是ggplot2的擴展包,ggplot2的一些參數亦可使用:
ggplot2|theme主題設置,詳解繪圖優化-“精雕細琢”
參考資料:
https://github.com/cran/ggpmisc
◆ ◆ ◆ ◆ ◆
精心整理(含圖版)|R語言生信分析,可視化,你要的全拿走,建議收藏!