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