在 R 中重命名图例值

Rename Legend Values in R

通过 ggplot2,我学会了重命名 X 轴、Y 轴和各个图例。不过,我也想重命名图例值。

例如,为简单起见,我在数据集中使用 0 表示男性,1 表示女性,当我显示它并将性别映射到审美时,我不希望图例读取 0 或 1数据值,但男性和女性。

或者,在下面的这个例子中,使用“4 wheel drive”、“front wheel drive”、“rear wheel drive”代替“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")

我希望的是一种重命名图例中显示的值的简单方法。

您可以 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")

您可以在比例尺中使用 labels 参数来自定义标签。您可以为 labels 参数提供函数或字符向量。

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")
  )

reprex package (v0.3.0)

于 2020-12-23 创建