Monday, May 22, 2017

fixed “number” of plots using facet_wrap

Leave a Comment

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?

2 Answers

Answers 1

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) 

Answers 2

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) 

enter image description here

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

enter image description here

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment