有没有办法在 ggplot2 中手动设置水平箱线图的高度? (垂直闪避)

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

我正在尝试制作一个图形,在底部有密度图,在密度图上方有相应的箱线图。我的密度图和箱线图是 filled/colored 分类变量。我想不出一种方法让箱线图高于密度图并避开。这是我到目前为止能够得到的:

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

但是,如您所见,这并没有将箱线图均匀地移动到密度图上方。我也用过

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

但我的箱线图最终重叠了(它们不再垂直闪避)。基本上,我正在寻找一种方法来为我的一组箱线图设置垂直高度,以便它们位于我的密度图之上,并使它们在垂直方向上相互避开。非常感谢任何建议。

将您希望框以 y 为中心的值映射到 geom_boxplotaes 内。例如:

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) 

另外,不要试图躲闪geom_density