Narusan
Narusan

Reputation: 502

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

enter image description here

What I'm hoping for is a simple way to rename the values displayed in the legend.

Upvotes: 4

Views: 3662

Answers (2)

teunbrand
teunbrand

Reputation: 37913

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)

Upvotes: 7

Ronak Shah
Ronak Shah

Reputation: 388817

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

enter image description here

Upvotes: 4

Related Questions