如何使用 R 中的 ggplot2 建立具有多個因子級別的箱線圖?


要建立一個箱線圖,我們需要一個因子和一個數值列,並且針對該因子中的每個類別或級別建立該箱線圖。現在,如果我們有兩個因子,則可以透過在 geom_boxplot 中傳遞填充引數來針對這兩個因子級別建立箱線圖。這將幫助我們區分兩個因子的箱線圖。檢視以下示例以瞭解其工作原理。

示例

考慮以下資料框 −

即時演示

> x<-sample(c("Male","Female"),30,replace=TRUE)
> y<-rnorm(30)
> grp<-sample(letters[1:3],30,replace=TRUE)
> df<-data.frame(x,y,grp)
> df

輸出

       x              y  grp
1 Female    0.790349405    b
2   Male    0.868186299    b
3 Female   -2.108607808    b
4 Female    0.284872060    c
5   Male   -1.128470452    b
6   Male    0.001181183    b
7 Female   -2.915847134    c
8   Male   -1.416607857    c
9 Female   -1.784574028    a
10  Male    0.685830764    a
11 Female   0.581216168    c
12   Male   0.387109500    c
13 Female   0.611448059    c
14 Female   0.603614728    c
15   Male   0.207989975    c
16   Male   0.357018523    b
17 Female  -0.196608618    c
18   Male   1.165436068    c
19   Male   0.466733550    c
20 Female  -1.293515169    b
21   Male  -1.046339186    b
22 Female   1.692938740    c
23 Female   1.360998968    a
24 Female  -0.141122217    c
25   Male  -0.946920446    a
26 Female   1.091516275    c
27   Male   0.216101163    a
28 Female   0.935390544    a
29   Male  -0.636606941    a
30 Female   0.266238867    b

載入 ggplot2 並建立箱線圖 −

> library(ggplot2)
> ggplot(df,aes(x,y))+geom_boxplot(aes(fill=grp))

輸出

更新日期:2021 年 3 月 4 日

4,000+ 次瀏覽

開啟你的 事業

透過完成課程取得認證

開始
廣告
© . All rights reserved.