Reputation: 2545
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
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')
Upvotes: 1