R: multiple ggplot2 plot using d*ply
I know variations on this question have been up several times, but couldn't figure out how to apply those solutions to this particular challenge:
I would like to use ggplot inside a d*ply call to plot the data (data frame dat
below) broken up by the v3
variable and display a numeric variable v2
for the 3 conditions in v1
. I want to have the plots in one page (pdf), so thought I could use dlply to contain resulting plots in a list that then could be fed to the multiplot wrapper function for ggplot2 found in 'Cookbook for R' here
# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols: Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
require(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
Here is a toy data frame:
set.seed(999)
dat <- data.frame(
v1 = rep(c("A","B","C"),25),
v2 = runif(75,-1,2),
v3 = sample(c("hippo", "smoke", "meat"), 75, replace=T))
Here is the best I could come up with - it gives the plots separately but doesnt merge them, and gives a strange output in console. Note that any solution not using multiplot()
is just as good for me.
require(dplyr)
require(ggplot2)
p <- dlply(dat, .(v3), function(x){
ggplot(x,aes(v1, v2)) +
geom_point()})
multiplot(plotlist=p, cols=2)
Solution 1:
Here's a different way that avoids multiplot()
and uses techniques shown here and here:
library(ggplot2)
library(dplyr)
results <- dat %>%
group_by(v3) %>%
do(plot = ggplot(., aes(v1, v2)) + geom_point())
pdf('all.pdf')
invisible(lapply(results$plot, print))
dev.off()