fixed "number" of plots using facet_wrap

If I have a data.frame dat and want to plot groups of data using facet_wrap:

dat <- data.frame(x = runif(150), y = runif(150), z = letters[1:15])

ggplot(dat[dat$z %in% letters[1:9], ], aes(x, y)) +
  geom_point() +
  facet_wrap( ~ z, ncol = 3, nrow = 3)

This looks great and performs as expected. However, if I plot the next set of z on a new plot:

ggplot(dat[dat$z %in% letters[10:15], ], aes(x, y)) +
  geom_point() +
  facet_wrap( ~ z, ncol = 3, nrow = 3)

I no longer have 3 rows and 3 columns. I can fix the aspect ratios of the plots using opts(aspect.ratio = 1) but I still have them laid out differently that my previous plot. I'd like it to appear as though there are always 9 plots on the page even if there are 6 or 1. Is that possible?

Answers


Try this,

library(ggplot2)
library(plyr)
library(gridExtra)

dat <- data.frame(x=runif(150), y=runif(150), z=letters[1:15])

plotone = function(d) ggplot(d, aes(x, y)) + 
  geom_point() + 
  ggtitle(unique(d$z))

p = plyr::dlply(dat, "z", plotone)
g = gridExtra::marrangeGrob(grobs = p, nrow=3, ncol=3)
ggsave("multipage.pdf", g)

library(cowplot) provides a handy function plot_grid that we can use to arrange a list of plots.

First, lets construct the list of individual plots:

p = lapply(unique(dat$z), function(i){
      ggplot(dat[dat$z == i, ], aes(x, y)) +
        geom_point() +
        facet_wrap(~z)
        })

Now we can arrange the panels using plot_grid:

plot_grid(plotlist = p[1:9], nrow = 3, ncol = 3)

plot_grid(plotlist = p[10:15], nrow = 3, ncol = 3)


Need Your Help

Gin / Gwt / Eclipse: com.google.gwt.inject.Inject cannot be resolved to a type

eclipse gwt dependency-injection guice gin

I'm trying to use GIN (Guice for GWT) within eclipse. The tutorial says to add a line to my module xml file:

NullReferenceException was unhandled, Object Reference not set to an instance of an object

c# exception reference null instance

Whenever I run my program, I get: NullReferenceException was unhandled, Object Reference not set to an instance of an object.