我正在尝试制作一个图形,该图形在底部有密度图,在密度图上方有相应的箱线图。我的密度图和箱线图由分类变量填充/着色。我无法找到一种方法使箱线图高于密度图并且也被躲避。这是我到目前为止所能得到的:
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_boxplot
的 aes
内。例如:
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_密度
。
关于r - 有没有办法在 ggplot2 中手动设置水平箱线图的高度? (垂直闪避),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64431976/