Is there a way to manually set the height of horizontal boxplots in ggplot2? (Vertical dodge)

Viewed 231

I am trying to make a figure that will have density plots on the bottom and corresponding boxplots above the density plots. My density plots and boxplots are filled/colored by a categorical variable. I cannot figure out a way to get the boxplots to be above the density plots and also dodged. This is what I've been able to get so far:

d <- mtcars
d$cyl <- as.factor(d$cyl)

fig <- ggplot(data = d) + 
  geom_density(aes(x = mpg, fill = cyl),
               position = "dodge", 
               na.rm = TRUE) +
  geom_boxplot(aes(x = mpg, color = cyl), 
               position = ggstance::position_dodgev(height = 1),
               width = .05, show.legend = FALSE,
               na.rm = TRUE) + 
  facet_grid(~am, scales = "free_x") + 
  scale_fill_brewer(palette = "Set2") + 
  scale_color_brewer(palette = "Set2") +
  theme_minimal() + 
  guides(color = FALSE, fill = FALSE) 
fig

Test figure

But, as you can see, this does not uniformly move the boxplots above the density plots. I've also used

geom_boxplot(aes(x = mpg, color = cyl), 
            position = position_nudge(x = 0, y = .3),
            width = .05, show.legend = FALSE,
            na.rm = TRUE) + 

but I end up having my boxplots overlap (they are no longer vertically dodged). Basically, I'm looking for a way to set a vertical height for my group of boxplots so they're above my density plots AND keep them vertically dodged from one another. Any suggestions are much appreciated.

1 Answers

Map the value you want your boxes to be centered around to y, inside the aes for geom_boxplot. E.g.:

ggplot(data = d) + 
  geom_density(aes(x = mpg, fill = cyl)) +
  geom_boxplot(aes(x = mpg, color = cyl, y = 1), 
               position = ggstance::position_dodgev(height = 0.2),
               width = .05, show.legend = FALSE) + 
  facet_grid(~am, scales = "free_x") + 
  scale_fill_brewer(palette = "Set2") + 
  scale_color_brewer(palette = "Set2") +
  theme_minimal() + 
  guides(color = FALSE, fill = FALSE) 

enter image description here

Also, don't try to dodge geom_density.

Related