Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change factor names on x axis with ggplot2 and R? [duplicate]

Tags:

r

ggplot2

axis

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?

like image 349
James Wade Avatar asked Mar 16 '17 21:03

James Wade


1 Answers

Try this:

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

See ?discrete_scale.

like image 80
joran Avatar answered Oct 18 '22 16:10

joran