Is it possible to have two different types of marginal distribution with ggExtra::ggMarginal()?

Viewed 115

Is it possible to have two different types of marginal distribution in ggMarginal()? E.g., density for x and histogram for y?

library(ggExtra)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()

# Histogram for both x and y
ggMarginal(p, type = "histogram")

# Density for x
ggMarginal(p, type = "density", margins = "x")
# Histogram for y
ggMarginal(p, type = "histogram", margins = "y")

Basically, I would like the two marginal distributions shown below on the same plot. enter image description here

I tried having both types in a list ( ggMarginal(p, type = list("density", "histogram"))), but that type must be of length 1.

Thanks in advance for your help!

1 Answers

I think you need to create both plots and swap their upper margin grobs:

library(ggExtra)
library(ggplot2)

p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()

ph <- ggMarginal(p, type = "histogram")
pd <- ggMarginal(p, type = "density")

ph$grobs[ph$layout$name == "topMargPlot"] <- 
  pd$grobs[ph$layout$name == "topMargPlot"]

ph

Created on 2022-03-09 by the reprex package (v2.0.1)

Related