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?

0

1 Answer 1

39

Try this:

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

See ?discrete_scale.

Sign up to request clarification or add additional context in comments.

2 Comments

How to change also in the legend?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.