在 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")
- 一种选择是打开 Excel 文件并将特定列中的所有 0 和 1 更改为“男性”和“女性”。
- 另一种选择是重命名 R 中的值,但我完全不知道该怎么做。我是 R 的新手。
我希望的是一种重命名图例中显示的值的简单方法。
您可以 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 创建
通过 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")
- 一种选择是打开 Excel 文件并将特定列中的所有 0 和 1 更改为“男性”和“女性”。
- 另一种选择是重命名 R 中的值,但我完全不知道该怎么做。我是 R 的新手。
我希望的是一种重命名图例中显示的值的简单方法。
您可以 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 创建