2

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 v3variable 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)
ah bon
  • 9,293
  • 12
  • 65
  • 148
user3375672
  • 3,728
  • 9
  • 41
  • 70
  • Edit: p should be given to the plotlist argument in multiplot - but it still wont work – user3375672 Jan 09 '15 at 21:32
  • 1
    What's the problem with your multiplot solution? I don't know what you mean by "gives the plots separately but doesn't merge them". I get no console output when I run your code. And you should load `plyr` for `dlply`, not `dplyr`. – Gregor Thomas Jan 09 '15 at 22:10
  • @Gregor: I was to fast with the (d)plyr; they are always loaded (so it worked), and of cause it need be plyr. The 3 plots show in the graphics device (RStudio) but separate (one by one). Then after reading your comment, I restarted Rstudio, sourced multiplot(), and out of nowhere it worked. Have no idea what that was. Happy (+1) for your comment, then. – user3375672 Jan 09 '15 at 22:24
  • Glad you got it working! I am going to vote to close your question though as it is no longer a reproducible problem. – Gregor Thomas Jan 09 '15 at 23:22
  • 1
    One other comment: if you don't want to keep `source`ing it, the `multiplot` function is provided in several packages, e.g., `Rmisc` and `blowtorch`. I like the `wq::layOut` for being more flexible [as I show here](http://stackoverflow.com/a/22999237/903061). – Gregor Thomas Jan 09 '15 at 23:28
  • Ah, interesting, didnt know this pckg! I will take a look – user3375672 Jan 09 '15 at 23:30

1 Answers1

4

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()
Community
  • 1
  • 1
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • Yes, its along the way. But I hoped to get all (three) plots into one page instead of one subplot pr page in several (3) pages. Could you put a comment on the invisible(....) stuff (although it clearly implies that you print "inside") – user3375672 Jan 09 '15 at 21:42