[英]Rename Legend Values in R
通过ggplot2
,我学会了重命名 X 轴、Y 轴和各个图例。 但是,我也想重命名图例值。
例如,为简单起见,我在数据集中使用 0 表示男性,使用 1 表示女性,当我将它和 map 性别显示为审美时,我不希望图例读取数据值的 0 或 1,但是雄性和雌性。
或者,在下面的示例中,使用“4 轮驱动”、“前轮驱动”、“后轮驱动”代替“4”、“f”和“r”将使图表更易于理解。
library(tidyverse)
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color = drv)) + labs(x = "Engine Size (Liters)", y = "Fuel Efficiency (Miles per Gallon)", color = "Drive")
我希望的是一种简单的方法来重命名图例中显示的值。
您可以在比例中使用labels
参数来自定义标签。 您可以为labels
参数提供 function 或字符向量。
library(tidyverse)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = drv)) +
labs(x = "Engine Size (Liters)", y = "Fuel Efficiency (Miles per Gallon)", color = "Drive") +
scale_colour_discrete(
labels = c("4" = "4 wheel drive",
"f" = "front wheel drive",
"r" = "rear wheel drive")
)
由代表 package (v0.3.0) 于 2020 年 12 月 23 日创建
您可以在绘图之前recode
值:
library(dplyr)
library(ggplot2)
mpg %>%
mutate(drv = recode(drv, "4" = "4 wheel drive",
"f" = "front wheel drive",
"r" = "rear wheel drive")) %>%
ggplot() +
geom_point(aes(x = displ, y = hwy, color = drv)) +
labs(x = "Engine Size (Liters)",
y = "Fuel Efficiency (Miles per Gallon)",
color = "Drive")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.