Ian Fiddes
Ian Fiddes

Reputation: 3011

R lattice levelplot - combine many plots together with one color key on same scale

I am trying to plot a 3x3 grid of levelplots which are all on the same color scale with one combined color key.

I have found latticeExtra and its ability to override c and combine trellis objects together, with the merge.legends flag. However, when I do this I get multiple color keys.

is a picture of what it looks like with only three of the plots. Here And here is the code where I do this:

t1 <- levelplot(counts[[1]], main="", col.regions=colorRampPalette(c("white","red"))(256))
t2 <- levelplot(counts[[2]], main="", col.regions=colorRampPalette(c("white","red"))(256))
t3 <-  levelplot(counts[[3]], main="", col.regions=colorRampPalette(c("white","red"))(256))

plots <- c(t1, t2, t3, merge.legends=T)
print(plots)

I also would ideally like to not have to manually make each trellis object its own variable, but rather a member of a list:

plots <- list()
for (i in 1:length(counts)){
  if (i %% 3 == 0) {
    plots[[i]] <- levelplot(counts[[i]], main="", col.regions=colorRampPalette(c("white","red"))(256))
  }
}
plots <- c(unlist(plots), merge.legends=T)

But when I try to do this it seems that the c function is not overridden correctly. I have tried not using unlist, as well as making plots a vector, and they do not work.

Upvotes: 1

Views: 3075

Answers (1)

fdetsch
fdetsch

Reputation: 5308

Note that merge.legends = TRUE results in separate legends per plot. If you want to merge single legends using c.trellis, you have to set merge.legends = FALSE (somewhat counter-intuitive, I know...). Based on a levelplot example from ?c.trellis:

# Levelplot
levObj <- levelplot(prop.table(WorldPhones, 1) * 100)

# Combination via `c.trellis`
comb_levObj <- c(levObj, levObj, layout = c(1, 2), merge.legends = FALSE)
print(comb_levObj)

c.trellis

Upvotes: 3

Related Questions