我有一个密度图,每个组具有不同的颜色,我想在顶部的每个组中添加一个边际箱线图。但是在盒图中,分组没有正确完成,都显示相同的数据。
set.seed(123)
library(ggplot2)
library(ggExtra)
library(data.table)
Data <- data.table(x = rnorm(100),
group = rep(c("group1", "group2"), times = c(30, 70)))
Data[group == "group1", x := x + 3]
p <-
ggplot(Data, aes(x = x, fill = group, colour = group)) +
geom_density(alpha = 0.5)
p %>% ggMarginal(type = "boxplot",
margins = "x",
size = 5,
groupColour = TRUE,
groupFill = TRUE)
更新: 使用geom_point可以正常工作:
p <-
ggplot(Data, aes(x = x, y = x, fill = group, colour = group)) +
geom_point(alpha = 0.5)
p %>% ggMarginal(type = "boxplot",
margins = "x",
size = 5,
groupColour = TRUE,
groupFill = TRUE)
那么,为什么它不能与geom_density
一起使用?
答案 0 :(得分:1)
如?ggMarginal
的帮助文件中所述,该函数期望p
中有一个ggplot2散点图。
以下将起作用:
p2 <- ggplot(Data, aes(x = x, fill = group, colour = group)) +
geom_point(aes(y = 0.1), alpha = 0) + # add an invisible scatterplot geom as the first layer
geom_density(alpha = 0.5)
p2 %>% ggMarginal(type = "boxplot",
margins = "x",
size = 5,
groupColour = TRUE,
groupFill = TRUE)