[R] two lattice graphs in one object

Deepayan Sarkar deepayan.sarkar at gmail.com
Tue Sep 2 21:43:16 CEST 2008

On Tue, Sep 2, 2008 at 6:24 AM, Andreas Krause <andreas at elmo.ch> wrote:
> When I create a lattice/Trellis type graph, I typically write a function that returns the graph, as in
> do.graph <- function(x, y, ...)
>  {
>    require(lattice)
>    return(xyplot(y~x, ...))
>  }
> My question today is this:
> If I want two graphs on one page, one way of achieving it is to print the objects into defined areas, as in
> gr1 <- xyplot(rnorm(111) ~ runif(111))
> gr2 <- xyplot(runif(111) ~ runif(111))
> print(gr1, pos=c(0, 0, 1, 0.5), more=T)
> print(gr2, pos=c(0, 0.5, 1, 1), more=F)
> Instead of using the print method, can I create a single trellis object that contains those two "sub-graphs"?
> I do not think so, given what I know about the design of these objects.
> I am hoping for a pleasant surprise though.

Well, you cannot return it as a single "trellis" object. However, you
could always return it as a list with multiple "trellis" objects, and
they will just get printed one by one. You can attach print()
arguments to the objects themselves, so that takes care of the layout.
For example, try

plist <- {
    gr1 <-
        xyplot(rnorm(111) ~ runif(111), main = "Plot A",
               plot.args = list(position = c(0, 0, 1, 0.5), more = TRUE))
    gr2 <-
        xyplot(runif(111) ~ runif(111), main = "Plot B",
               plot.args = list(position = c(0, 0.5, 1, 1), more = FALSE))
    list(gr1, gr2)


Actually you will see some output on the console:

> print(plist)


This is from the print method for lists. If you want to avoid that,
you can always set a class on the list you return and write a
corresponding print() method.


More information about the R-help mailing list