Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Multiple lattice levelplots from matrices

My goal is to construct a levelplot (from the lattice package) with 4 or more individual plots sharing the same colorkey. While this appears to be relatively simple using functions, I haven't been able to find a solution using data matrices. An example of a working levelplot with just one matrix:

d <- replicate(10,rnorm(10))
levelplot(d)

I have found partial solutions using print and split to show all 4 levelplots on the same screen, but these would require me to either turn off the colorkey, or show it on every plot. Neither solution is completely satisfactory.

If I use the layout-option in levelplot, like so:

levelplot(d, layout=c(2,2))

, I get the desired layout, with one large colorkey, main and xlab/ylab, but only one levelplot prints.

I have been trying to construct a formula that yields the desired result, but I'm afraid my understanding of data frames, arrays and matrices is not deep enough to do so. If anyone knows of a working solution, I would be very grateful. What I imagine is something along the line of (not working code):

d1 <- replicate(10,rnorm(10))
d2 <- replicate(10,rnorm(10))
d3 <- replicate(10,rnorm(10))
d4 <- replicate(10,rnorm(10))

d <- list(d1,d2,d3,d4)
di <- c(1,2,3,4)

levelplot(x ~ y | di, data = d, layout=c(2,2))

NB! Avoiding the matrices is not an option. Some of them are obtained from raw text files.

Thank you in advance,

-JP

like image 962
ipoga Avatar asked Aug 26 '12 12:08

ipoga


1 Answers

Using ggplot and reshape along with your list d:

require(reshape)
require(ggplot2)

ggplot(melt(d), aes(x=X1, y=X2)) +
  facet_wrap(~ L1, ncol=2) +
  geom_tile(aes(fill=value)) +
  coord_equal()

Which gives:

enter image description here

like image 93
Andy Avatar answered Oct 18 '22 05:10

Andy