如何在R中使用ggplot2繪製迴歸模型的置信區間並設定透明度?
要繪製迴歸模型的置信區間,我們可以使用ggplot2包中的geom_ribbon函式,但預設情況下它將是深灰色。藉助於該函式內的alpha引數,可以將其設定為透明,alpha引數可以根據我們的需求進行調整,但我最推薦的值是0.2。
示例
考慮以下資料框:
> x<-rnorm(20,25,2.24) > y<-rnorm(20,30,1.27) > df<-data.frame(x,y) > df
輸出
x y 1 22.67102 29.37057 2 21.59415 29.54027 3 20.56817 28.27672 4 24.97228 31.38193 5 21.41651 31.86811 6 23.94699 28.22775 7 23.90155 30.03807 8 26.57466 29.32966 9 22.32727 32.10336 10 30.04399 31.76219 11 26.84023 30.12260 12 23.73143 31.71349 13 22.57145 29.10705 14 25.86364 30.61687 15 25.17939 30.79297 16 22.49971 27.51084 17 22.01182 29.96766 18 23.93069 30.31963 19 19.57823 30.01839 20 22.90537 32.30613
載入ggplot2包並建立一個帶有置信區間的迴歸模型圖:
示例
> library(ggplot2) > ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat="smooth",method="lm",se=TRUE)+geom_line(stat="smooth",method="lm")
輸出
建立具有透明置信區間的圖:
示例
> ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat="smooth",method="lm",se=TRUE,alpha=0.2)+geom_line(stat="smooth",method="lm")
輸出
廣告