Search code examples
rplotcategorical-datar-gridmosaic-plot

Using grid to modify vcd::mosaic plots


I want to use grid to modify mosaic plots that I create with the vcd package. Specifically, I want to add precisely positioned line segments. Here is a minimal example:

library(vcd)
myDF <- expand.grid(fac1 = c('a', 'b', 'c', 'a'), fac2 = c('y', 'z'))
mosaic(fac2 ~ fac1, data = myDF, pop = FALSE)

The result is this plot:

minimal mosaic plot

I would like to use grid.segments() to draw a horizontal segment under the "fac2" label and as wide as the plotted cells. This would be simple if I could use seekViewport() to navigate to the viewport that holds the "fac2" label. But I can't. Here is the problem:

> getNames()
> [1] "rect:fac1=a,fac2=y" "rect:fac1=a,fac2=z" "rect:fac1=b,fac2=y" "rect:fac1=b,fac2=z" 
  [5] "rect:fac1=c,fac2=y" "rect:fac1=c,fac2=z" "GRID.text.1"        "GRID.text.2"        
  [9] "GRID.text.3"        "GRID.text.4"        "GRID.text.5"        "GRID.text.6"        
 [13] "GRID.text.7" 

When I run seekViewport("cell:GRID.text.2") or anything like it, I get an error message:

Error in grid.Call.graphics(L_downviewport, name$name, strict) : 
  Viewport 'cell:GRID.text.2' was not found

(The "cell:" prefix is part of the vcd viewport-naming scheme. And by contrast, commands like seekViewport("cell:fac1=a,fac2=y") work perfectly.)

Is there a way to navigate to the viewport that holds the "fac2" label? And if not, what is the best way to precisely position a line segment below that label?


Solution

  • In a comment above, @user20650 provides the necessary information. Among other things, the code in my original post was problematic because getNames() returns grob names, not viewport names.

    The simplest way to draw the line segment is to draw the figure as above, and then

    nn <- seekViewport("margin_top")  ## Drill down to the viewport[margin_top]
    grid.segments(0, .5, 1, .5)
    upViewport(nn)                    ## Return to top level viewport, here viewport[ROOT]
    

    The result is this plot:

    mosaic plot with line segment between x–axis labels