如何在 R 中的 ggplot2 中更改圖例標題?


在 ggplot2 中,預設情況下,圖例標題是資料框的分組列的標題。如果我們想更改該標題,可以使用 scale_color_discrete 函式。例如,如果我們有一個名為 df 的資料框,其中包含兩個數字列 x 和 y,還有一個分組列(例如 group),則可以使用以下命令建立具有不同圖例標題的散點圖 -

ggplot(df,aes(x,y,color=group))+geom_point()+scale_color_discrete("Gender")

示例

考慮以下資料框 -

線上玩

> x<-rnorm(20)
> y<-rnorm(20)
> grp<-sample(c("Male","Female"),20,replace=TRUE)
> df<-data.frame(x,y,grp)
> df

輸出

             x          y    grp
1  -2.27846496  0.8121008   Male
2  -1.75112768 -0.1718679 Female
3  -0.12504696 -0.3265867 Female
4   0.10895490 -0.2015613 Female
5  -1.51196132  0.8480887   Male
6   1.68028497 -1.1329240   Male
7  -0.65238760 -0.9495177   Male
8   0.84725937  1.4825983 Female
9   0.53645228  2.1630524 Female
10 -2.04814594  0.4503883 Female
11 -0.37741279 -1.1621875   Male
12  0.79303416 -0.1804637   Male
13 -0.02095395 -0.9740427   Male
14  0.61453646  1.0327821 Female
15 -0.32875489 -0.4071753   Male
16  0.94227215  2.0651996 Female
17  1.79740910  0.8630703   Male
18  1.09133101 -0.1053076   Male
19  0.33748223 -0.1238961 Female
20 -0.10264760  1.5338488   Male

載入 ggplot2 包,並使用 grp 分組建立 x 和 y 之間的點圖 -

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

輸出

使用 grp 分組建立 x 和 y 之間的點圖,並使用圖例標題 Gender -

> ggplot(df,aes(x,y,color=grp))+geom_point()+scale_color_discrete("Gender")

輸出

更新時間:2021 年 3 月 5 日

403 次檢視

開始你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.