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

all*_*ian 2 r ggplot2 boxplot density-plot

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

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
Run Code Online (Sandbox Code Playgroud)

测试图

但是,正如您所看到的,这不会将箱线图均匀地移动到密度图上方。我也用过

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

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

Axe*_*man 5

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

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) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

另外,不要试图躲避geom_density