如何使用 R 中的 ggplot2 顯示 y 變數的平均線?


若要使用 ggplot2 顯示 y 變數的平均線,我們可以將 geom_hline 函式與 y 軸截距結合使用。在 y 軸截距中,我們需要計算 y 變數的平均值,還可以使用 geom_hline 函式內的 color 引數更改線的顏色。

示例

考慮以下資料框架 −

線上演示

> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> df

輸出

x y
1 -1.07323904 0.368641641
2 0.92531148 -0.196530651
3 -0.57433739 0.710957804
4 1.17367100 0.300110517
5 0.00769624 -1.287517035
6 0.64901161 -0.476105351
7 0.70197701 -0.683592585
8 -0.80807441 -1.716264317
9 0.10827026 0.116964308
10 -1.10451308 0.660382307
11 -0.01612692 -1.182533283
12 2.20292198 -1.890223763
13 -1.03368161 -0.526983486
14 0.24688341 -0.709657125
15 0.46439214 -0.611872054
16 -0.86472988 0.100839958
17 -1.29702868 -0.178357498
18 -1.51781901 0.006079342
19 0.03744727 -1.062274129
20 -1.62755835 -1.532681680

載入 ggplot2 程式包並在 x 和 y 之間建立一個點狀圖 −

> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()

輸出

在 x 和 y 之間建立一個點狀圖,其中包含 y 的平均線 −

> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=mean(y),color="red")

輸出

更新時間: 04-Mar-2021

2K+ 次瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.