Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for your help!

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading