1

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?

Community
  • 1
  • 1
Bryan
  • 933
  • 1
  • 7
  • 21
  • I don't think the "it would be nice if I could use the function like this: `automatic_awesome_plot(x)`" is actually showing much effort – rawr Jul 31 '15 at 16:10
  • I'm really just asking if it is possible to replace axes with arbitrary marginal plots in `lattice`. Without knowing more about how axes are drawn in `lattice`, I don't have much to go on, and if it's simply not possible, I'd rather know that before investing loads of time learning the internal mechanics of the axis functions. A solution using `panel.plots`, which is where I'd normally start, doesn't seem appropriate here. – Bryan Jul 31 '15 at 16:25
  • Lattice plots are also grid plots so using `gridExtra` is still an option for laying out plots. There is no mechanism inside the standard `xyplot` function for adding plots at the margin. You'd need to do a lot of grob re-arranging yourself. – MrFlick Jul 31 '15 at 18:02

1 Answers1

2

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/

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Bryan
  • 933
  • 1
  • 7
  • 21