简体   繁体   中英

Rename Legend Values in R

With ggplot2 , I have learned to rename the X-Axis, the Y-Axis and the individual legends. 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.

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.

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".
  • Another option would be to rename the values within R, but I have absolutely no idea how to do this. I'm very new to 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. You can provide a function or a character vector to the labels argument.

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)

You could recode the values before plotting:

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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