I have a density plot with different colors per group, where I would like to add a marginal boxplot per group at the top. But the grouping is not done correctly in the boxplots, both show the same data.
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)
UPDATE: With geom_point it does work:
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)
So, why is it not working with geom_density
?