简体   繁体   English

重命名 R 中的图例值

[英]Rename Legend Values in R

With ggplot2 , I have learned to rename the X-Axis, the Y-Axis and the individual legends.通过ggplot2 ,我学会了重命名 X 轴、Y 轴和各个图例。 However, I also want to rename the legend values.但是,我也想重命名图例值。

As an example, for simplicity I have used 0 for male and 1 for female in a dataset, and when I display it and map gender to an aesthetic, I don't want the legend to read 0 or 1 for the data values, but male and female.例如,为简单起见,我在数据集中使用 0 表示男性,使用 1 表示女性,当我将它和 map 性别显示为审美时,我不希望图例读取数据值的 0 或 1,但是雄性和雌性。

Or, in this example below, instead of "4", "f" and "r" using "4 wheel drive", "front wheel drive", "rear wheel drive" would make the graph much easier to understand.或者,在下面的示例中,使用“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")

在此处输入图像描述

  • One option would be to open the Excel file and change all the 0s and 1s in the specific column to "male" and "female".一种选择是打开 Excel 文件并将特定列中的所有 0 和 1 更改为“男性”和“女性”。
  • Another option would be to rename the values within R, but I have absolutely no idea how to do this.另一种选择是重命名 R 中的值,但我完全不知道该怎么做。 I'm very new to R.我对 R 很陌生。

What I'm hoping for is a simple way to rename the values displayed in the legend.我希望的是一种简单的方法来重命名图例中显示的值。

You can use the labels argument in a scale to customise labelling.您可以在比例中使用labels参数来自定义标签。 You can provide a function or a character vector to the labels argument.您可以为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")
  )

Created on 2020-12-23 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 12 月 23 日创建

You could recode the values before plotting:您可以在绘图之前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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM