11

I am plotting the interaction between multiple variables with geom_boxplot, and the resulting factor names are very long. I want to rename these factor names on the plot without changing the factors in the original data set to make the plot easier to interpret.

As an example using the mtcars cars data set:

library(tidyverse)
ggplot(mtcars) + geom_boxplot(aes(factor(cyl), mpg))

This results in a boxplot with 4, 6, and 8 cylinders as the x axis factors. What I would like to do is change those x axis factors. For example, how could I change 4 to "Four Cyl" without editing the original data?

user513951
  • 12,445
  • 7
  • 65
  • 82
James Wade
  • 337
  • 2
  • 3
  • 13

1 Answers1

35

Try this:

ggplot(mtcars) + 
  geom_boxplot(aes(factor(cyl), mpg)) + 
  scale_x_discrete(labels = c('Four','Six','Eight'))

See ?discrete_scale.

joran
  • 169,992
  • 32
  • 429
  • 468
  • 9
    How to change also in the legend? – Saren Tasciyan Jun 27 '19 at 13:50
  • I'd still recommend to add a new column, e.g. `cyl.str`, to the data frame with the desired strings and use that in the plot. If values change in the original data, hard-coded labels can diverge from real factors inadvertently. – schoettl Jun 30 '21 at 19:27