Bryan
Bryan

Reputation: 933

Adding marginal histograms (or boxplots) to xyplot using lattice

Similar to this question, I'd like to to add marginal histograms or boxplots to a xyplot or densityplot using lattice. Is there a way to replace the right and/or top axes with these plots instead?

Something like:

library(lattice)
x <- rnorm(100)
y <- rnorm(100)
xyplot(x~y, 
       x.top  = histogram(~x), # desired 
       y.right = bwplot(~y)    # desired
       )

How could I do this?

Upvotes: 1

Views: 651

Answers (1)

Bryan
Bryan

Reputation: 933

Using ggplot2 with ggExtra works.

library(ggplot2)
library(ggExtra)

p <- ggplot(cars, aes_string('speed', 'dist')) +
  geom_point() + theme_bw(15)

ggExtra::ggMarginal(
  p,
  type = 'boxplot',
  margins = 'both',
  size = 5,
  color = "black",
  fill  = "darkgrey"
)

See: https://daattali.com/shiny/ggExtra-ggMarginal-demo/

Upvotes: 2

Related Questions