Instantly share code, notes, and snippets.

Embed
What would you like to do?
Which method do you prefer?
library(tidyverse)
library(forcats)
# The original plot
## This has an ugly legend title, maybe we should remove it and modify the labels
ggplot(mtcars, aes(x = mpg, y = disp, col = as.factor(cyl))) +
geom_point()
# Approach 1: Modify the plot
# Use ggplot to map each level of a factor (specified with 'breaks') to a new lablel
ggplot(mtcars, aes(x = mpg, y = disp, col = as.factor(cyl))) +
geom_point() +
scale_color_discrete(name = "",
breaks = c(4,6,8), labels = c('4 cylinders','6 cylinders','8 cylinders'))
# Approach 2: Modify the data frame
## Option a: Use sprintf to create a new string based on the old one
mtcars %>%
mutate(cyl_str = sprintf('%d cylinders', cyl)) %>%
ggplot(aes(x = mpg, y = disp, col = cyl_str)) +
geom_point() +
scale_color_discrete(name = "")
## Option b: Create a factor and explicitly specify the levels and labels
### Note: this will break if cyl is already a factor unless you force as.character first
mtcars %>%
mutate(cyl_factor = factor(cyl,
levels = c(4,6,8),
labels = c('4 cylinders','6 cylinders','8 cylinders'))) %>%
ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
geom_point() +
scale_color_discrete(name = "")
## Option c: Use dplyr's recode_factor to change labels
### Note: old values on the left, new ones on the right
mtcars %>%
mutate(cyl_factor = as.factor(cyl),
cyl_factor = recode_factor(cyl_factor,
"4"="4 cylinders", "6"="6 cylinders", "8"="8 cylinders")) %>%
ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
geom_point() +
scale_color_discrete(name = "")
## Option d: Use forcat's fct_recode to change labels
### Note: new values on the left, old ones on the right (opposite of above)
mtcars %>%
mutate(cyl_factor = as.factor(cyl),
cyl_factor = fct_recode(cyl_factor,
"4 cylinders"="4", "6 cylinders"="6", "8 cylinders"="8")) %>%
ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
geom_point() +
scale_color_discrete(name = "")
## Option e: Use plyr's revalue
### Note: like previous option, but you pass a named vector instead of a sequence of named arguments
mtcars %>%
mutate(cyl_factor = as.factor(cyl),
cyl_factor = plyr::revalue(cyl_factor,
c("4"="4 cylinders", "6"="6 cylinders", "8"="8 cylinders"))) %>%
ggplot(aes(x = mpg, y = disp, col = cyl_factor)) +
geom_point() +
scale_color_discrete(name = "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment