[R] placing rectangle behind plot

Paul Murrell p.murrell at auckland.ac.nz
Mon Jul 31 01:13:59 CEST 2006


Hi


Gabor Grothendieck wrote:
> I am trying to create a lattice plot and would like to later, i.e. after
> the plot is drawn, add a grey rectangle behind a portion of it.
> The following works except that the rectrangle is on top of and
> obscures a portion of the chart.  I also tried adding col = "transparent"
> to the gpar list but that did not help -- I am on windows and
> perhaps the windows device does not support transparency?


Correct.


> At any rate, how can I place the rectangle behind the plotted
> points without drawing the rectangle first?
> 
> library(lattice)
> library(grid)
> trellis.unfocus()
> x <- 1:10
> xyplot(x ~ x | gl(2,1), layout = 1:2)
> trellis.focus("panel", 1, 1)
> grid.rect(w = .5, gp = gpar(fill = "light grey"))
> trellis.unfocus()


The user-interface is a little rough, but this can be done by accessing
the underlying grid objects.  Here's an example, with explanatory bits
interspersed ...

# "grab" the lattice plot as a grid gTree
# There are warnings, but they are ignorable
latticeplot <- grid.grabExpr(print(xyplot(x ~ x | gl(2,1),
                                          layout = 1:2)))

# Demonstrate that the gTree faithfully replicates the
# original lattice plot (not necessary, just to to what's going on)
grid.newpage()
grid.draw(latticeplot)

# Explore the gTree (just to to show what's going on)
# Better user-interface would be nice here ...
childNames(latticeplot)
# Identify which children are which
# (appropriate grob names would be nice here)
lapply(latticeplot$children, class)
# Identify where each child is drawn
latticeplot$childrenvp
lapply(latticeplot$children, "[[", "vp")

# Add a rect (starts off on top of everything else)
# NOTE that rect has to have correct vpPath
plotwithrect <- addGrob(latticeplot,
                        rectGrob(w = .5, gp = gpar(fill = "light grey"),
                                 vp=vpPath("plot1.toplevel.vp",
                                           "plot1.panel.1.1.vp")))

# Check this draws what we expect (just to show what's going on)
grid.newpage()
grid.draw(plotwithrect)

# Reorder children to put rect at back
# Appropriate user-interface would be nice here ...
nc <- length(plotwithrect$childrenOrder)
plotwithrect$childrenOrder <-
    plotwithrect$childrenOrder[c(nc, 1:(nc - 1))]

# Final result
grid.newpage()
grid.draw(plotwithrect)

Paul
-- 
Dr Paul Murrell
Department of Statistics
The University of Auckland
Private Bag 92019
Auckland
New Zealand
64 9 3737599 x85392
paul at stat.auckland.ac.nz
http://www.stat.auckland.ac.nz/~paul/



More information about the R-help mailing list