user3741035
user3741035

Reputation: 2545

Preserve width of box plot in ggplot when varying number of boxes

Is there a way to preserve the width of boxplots in ggplot? By default, the width will vary depending on how many boxes that are included in the plot.

Upvotes: 1

Views: 496

Answers (1)

arvi1000
arvi1000

Reputation: 9582

How about manually setting x axis?

# Problem: different widths between these two plots
p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + 
  geom_boxplot()

p2 <- ggplot(mtcars[mtcars$cyl<8,], aes(x=factor(cyl), y=mpg)) + 
  geom_boxplot()

# Solution: fix x axis
p3 <- ggplot(mtcars[mtcars$cyl<8,], aes(x=factor(cyl), y=mpg)) + 
  geom_boxplot() + 
  scale_x_discrete(limits=c('4', '6', '8'))

library(gridExtra)
grid.arrange(p1, p2, p1, p3, ncol=2, main='Before', sub='After')

enter image description here

Upvotes: 1

Related Questions