How to put two 'vcd' grid graphics in a single plot?

1k views Asked by At

I would like to place two (somewhat non-standard) grid graphics in a single plot in R.

Try:

require(vcd)
mosaic(Titanic)
assoc(Titanic)

The trouble is that these aren't lattice graphics, and to my knowledge do not come with a layout argument or similar. And since these are grid graphs, they're impervious to base graph tricks like par(mfrow=c(1,2)).

How can I place the two graphs above in a single plot, with both graphs on the same line?

I already tried the suggestions in How to plot grid plots on a same page?, but they don't seem to work for vcd plots. Ultimately I would like to obtain something similar to:

enter image description here

3

There are 3 answers

2
user20650 On

Neither plot seems to return any object and I cant see how to grab the grobs from looking at grid.ls(). So using the idea from this answer

library(vcd) 
library(gridGraphics)
library(gridExtra)

mosaic(Titanic)  
m <- grid.grab()  

assoc(Titanic)  
a <- grid.grab()

grid.newpage()
grid.arrange(m, a, ncol=2)

enter image description here

Im sure there will be a more grid-like approach but ...

0
doncherry On

Another option is vcd’s mplot() function (for details, see ?vcd::mplot):

library(vcd)
mplot(
  mosaic(Titanic, return_grob = TRUE),
  assoc(Titanic, return_grob = TRUE),
  keep_aspect_ratio = FALSE
)

output

0
Achim Zeileis On

Something similar to the solution in How to plot grid plots on a same page? can also be used for vcd displays. The difference is that you need to set newpage = FALSE (to prevent opening a new display) and you need to push and pop the viewport yourself (which can be handy when re-using vcd graphics in more complicated displays such as partykit trees).

The mosaic and association display for the Titanic data can be visualized as:

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))

pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1))
mosaic(Titanic, newpage = FALSE)
popViewport()

pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2))
assoc(Titanic, newpage = FALSE)
popViewport()

yielding

Mosaic and association display