[R] Drawing rectangles in multiple panels

hadley wickham h.wickham at gmail.com
Thu Jul 12 06:39:14 CEST 2007


On 7/12/07, Stephen Tucker <brown_emu at yahoo.com> wrote:
> Not that Trellis/lattice was entirely easy to learn at first. :)
>
> I've been playing around with ggplot2 and there is a plot()-like wrapper for
> building a quick plot [incidentally, called qplot()], but otherwise it's my
> understanding that you superpose elements (incrementally) to build up to the
> graph you want. Here is the same plot in ggplot2:
>
> rectInfo <-
>     list(matrix(runif(4), 2, 2),
>          matrix(runif(4), 2, 2),
>          matrix(runif(4), 2, 2))
>
> library(ggplot2)
> ggopt(grid.fill = "white") # just my preference
> ## original plot of points
> p <-
> qplot(x,y,data=data.frame(x=runif(30),y=runif(30),f=gl(3,30)),facets=f~.)
> # print(p)
>
> ## external data (rectangles) -> in coordinates for geom_polygon
> x <- do.call(rbind,
>              mapply(function(.r,.f)
>                     data.frame(x=.r[c(1,1,2,2),1],y=.r[c(1,2,2,1),2],f=.f),
>                     .r=rectInfo,.f=seq(along=rectInfo),SIMPLIFY=FALSE))
> ## add rectangle to original plot of points
> p+layer(geom="polygon",data=x,mapping=aes(x=x,y=y),facets=f~.)
> # will print the graphics on my windows() device

You should be able to simplify this line to:
p+geom_polygon(data=x)
because all the other information is already contained in the plot object.

> Though lattice does seem to emphasize the 'chart type' approach to graphing,
> in a way I see that it provides a similar flexibility - just that the
> specifications for each element are contained in functions and objects that
> are ultimately invoked by a high-level/higher-order function, instead of
> being combined in the linear fashion of ggplot2.

I tend to think in very data centric approach, where you first
generate the data (in a data frame) and then you plot it.  There is
very little data creation/modification during the plotting itself - I
think this is different to lattice, where you often do more data
manipulation in the panel function itself.  I don't think one is
better or worse, just different.

Hadley



More information about the R-help mailing list