在 R 中重命名图例值

Nar*_*san 3 r ggplot2 axis-labels

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

举个例子,为了简单起见,我在数据集中使用 0 代表男性,1 代表女性,当我显示它并将性别映射到审美时,我不希望图例读取 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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 一种选择是打开 Excel 文件并将特定列中的所有 0 和 1 更改为“男性”和“女性”。
  • 另一种选择是重命名 R 中的值,但我完全不知道如何执行此操作。我对 R 很陌生。

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

teu*_*and 7

您可以使用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")
  )
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 12 月 23 日创建