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

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.
