Jai Broome
Jai Broome

Reputation: 15

Increase maximum width of boxplots with facet_wrap in ggplot2

When generating boxplots with a facet_wrap, ggplot2 leaves a lot of space between the boxes. I would like to make them wider.

library(ggplot2)
packageVersion("ggplot2")
ggplot(diamonds, aes(x = cut, y = price)) +
  geom_boxplot(varwidth = FALSE) +
  facet_wrap("color")

Figure 1

I believe it's because it is leaving space in case it needs to plot combinations of factor levels that don't need to be plotted in each panel. To check this, I generated a similar plot with a new variable which is cut by color, plotted it on the x-axis, facet_wrapped by color with scales = "fixed". It looks like the box widths are the same in both plots.

library(dplyr)
diamonds2 <- mutate(diamonds, CUTxCOLOR = paste(cut, color, sep = "."))
ggplot(diamonds2, aes(x = CUTxCOLOR, y = price)) +
  geom_boxplot(varwidth = FALSE) +
  facet_wrap("color", scales = "fixed")

Figure 2

Any ideas about how to go about this would be appreciated.

Upvotes: 0

Views: 1906

Answers (1)

javierps
javierps

Reputation: 26

The width parameter in geom_boxplot should do the trick:

ggplot(diamonds, aes(x = cut, y = price)) + 
  geom_boxplot(width = .6, position = "dodge") + 
  facet_wrap("color")

Upvotes: 1

Related Questions