Merging or overlaying xyplots in a lattice panel

Bryan picture Bryan · Oct 22, 2013 · Viewed 7.6k times · Source

Trying to figure out how to add points or a data series to an existing lattice panel once it's been created. Does this have something to do with plot.points and/or the update function?

# Initialize first plot
library(lattice)
a <- xyplot(Sepal.Length~Sepal.Width, groups=Species, data=iris
            , subset=Species %in% levels(Species)[1:2])
print(a) 

# Create second plot to overlay or merge with the first plot
b <- xyplot(Sepal.Length~Sepal.Width, groups=Species, data=iris
            , subset=Species %in% levels(Species)[3])

# Initial attempt at merging plots:
library(latticeExtra)
print(c(a,b)) # this displays the data in an adjacent second panel
print(c(a,b,layout=c(1,1))) # and this only shows series "b"

Note: in this example, both plots "a" and "b" come from the original iris dataframe, but ideally, the solution would work with distinct dataframes.

Any ideas? Thanks!
Bryan

Answer

Aaron left Stack Overflow picture Aaron left Stack Overflow · Oct 22, 2013

You're looking for as.layer, I think; try this. It's in the latticeExtra library as well.

library(latticeExtra)
a + as.layer(b)

See documentation here: http://latticeextra.r-forge.r-project.org/#as.layer