屬於比較常用的技巧。下面我用ggplot2內置數據集進行演示:
先來看一下,僅有散點和擬合線的圖
df=diamonds[sample(1:dim(diamonds)[1],40),]
df$price=df$price / 10000
p=df%>%ggplot(aes(carat,price))+
geom_point(size=4,alpha=0.3,color="#6baed6")+
geom_smooth(method = "lm", formula = y~x, color = "#756bb1", fill = "#cbc9e2")+ #顏色選自https://colorbrewer2.org/
theme_bw()+
theme(
panel.grid.major = element_blank(),panel.grid.minor = element_blank()
)
p
ggsave("tmp1.pdf",width = 8,height = 8,units = "cm")
如果想添加擬合的方程,可以使用ggpmisc包的stat_poly_eq()函數,該函數可以擬合多項式方程並生成多種標簽,比如p值、決定系數R方,這些由函數計算出來的量通常名稱前后有兩個點
..eq.label..
..adj.rr.label..
..p.value.label..
對應的代碼只有一行,其余代碼和上面一樣:
library(ggpmisc)
p+stat_poly_eq(aes(label=paste(..eq.label..,..adj.rr.label..,..p.value.label..,sep = "~~~~")),formula = y~x,parse=T,size=2.5)
#這一行paste()中的內容是一個類似Latex的表達,“~”表示空格,parse=T表示將這個語句翻譯成可讀形式;size=2.5表示字體大小
ggsave("tmp2.pdf",width = 8,height = 8,units = "cm")
如果需要添加相關系數,可以按照相同的思路,先求出對應的值,再加到stat_poly_eq()的label參數里
cor=round(cor(df$carat,df$price),2)
p+stat_poly_eq(aes(label=paste("italic(r)~`=`~",cor,sep = "")),formula = y~x,parse=T,size=4)
ggsave("tmp3.pdf",width = 8,height = 8,units = "cm")
另外也可以使用ggpubr包的stat_cor()函數,添加相關系數以及p值
library(ggpubr)
p+stat_cor()
ggsave("tmp4.pdf",width = 8,height = 8,units = "cm")
將stat_poly_eq()和stat_cor()結合起來也是可以的,當然兩個文本的位置需要調整一下
p+stat_poly_eq(aes(label=..eq.label..),formula = y~x,parse=T,size=4)+
stat_cor(label.y=0.9,size=4)
因水平有限,有錯誤的地方,歡迎批評指正!