我正在尝试制作一个图形,该图形的底部有密度图,密度图上方有相应的箱线图。我的密度图和箱线图由分类变量填充/着色。我想不出一种方法让箱线图高于密度图并且也被躲避。这是我到目前为止能够得到的:
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 = …
Run Code Online (Sandbox Code Playgroud)