Search code examples
rmatrixggplot2levelplot

Plotting matrices of different sizes in one window (in R)


I’m trying to create color matrices to illustrate the change in the standardized values of several variables over 25 years. I’ve divided up the variables into a few subcategories and want to show the results for each subcategory in different plots in one window with one colorkey and title. I tried to do this using reshape and ggplot2 using the following code. Because each of the categories have a different number of variables, however, this produces a lot of empty space in the plots.

library(reshape)
library(ggplot2)

v1 <- replicate(7,rnorm(25))
v2 <- replicate(15, rnorm(25))
v3 <- replicate(11, rnorm(25))
v4 <- replicate(9, rnorm(25))
v5 <- replicate(9, rnorm(25))

v <- list(v1,v2,v3, v4, v5)

ggplot(melt(v), aes(x=X1, y=X2)) + facet_wrap(~ L1, ncol=1) +
geom_tile(aes(fill=value)) + ggtitle("Title") + 
theme(plot.title = element_text(lineheight=2, face="bold"))

What is a better way of producing plots I need in one window without all the unnecessary blank space? Note that I originally tried to do this using the levelplot function in the lattice package. However, the only way I could figure out was to print each individual levelplot, which produced a color key and title for each plot (not what I wanted).


Solution

  • Is this what you are looking for??

    You can get rid of the blank space using scales="free_y" in the call to facet_wrap(...). This forces each facet to have it's own y-axis, but does not force the display of a separate x-axis on each facet. I also added a different color scale (take it out if you prefer the default).

    library(ggplot2)
    library(reshape2)
    library(RColorBrewer)
    
    ggplot(melt(v), aes(x=X1, y=X2)) + 
      facet_wrap(~ L1, ncol=1,scales="free_y") +
      geom_tile(aes(fill=value)) + ggtitle("Title") + 
      scale_fill_gradientn(colours=rev(brewer.pal(9,"Spectral")))+
      theme(plot.title = element_text(lineheight=2, face="bold"))