Marginal boxplots not aligned by group in R

2019-08-26 10:06发布

问题:

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?

回答1:

As noted in the help file for ?ggMarginal, the function expects a ggplot2 scatterplot in p.

The following would work:

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)



标签: r ggplot2