有没有办法在ggplot2中手动设置水平框的高度? 垂直闪避

问题描述

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

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

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

geom_Boxplot(aes(x = mpg,position = position_nudge(x = 0,y = .3),na.rm = TRUE) + 

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

解决方法

将您希望框位于y的{​​{1}}内的aes周围的值映射。例如:

geom_boxplot

enter image description here

另外,请勿尝试躲避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)