Fixed "number" of charts using facet_wrap

If I have data.frame dat and you want to display data groups 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) 

It looks great and works as expected. However, if I built the following set of z on a new chart:

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

I no longer have three rows and 3 columns. I can correct the proportions of the graphs using opts(aspect.ratio = 1) , but I still have them differently, which is my previous plot. I would like it to look as if there are always 9 graphs on the page, even if there are 6 or 1. Is this possible?

+7
source share
2 answers

Try it,

 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) 
+9
source

library(cowplot) provides a convenient plot_grid function that we can use to organize the list of graphs.

First, create a list of individual graphs:

 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) 

enter image description here

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

enter image description here

+1
source

All Articles