R - save multiplot to file

I’d really appreciate your help with the following problem. I know several ways to save a single plot to a file. My question is: How do I correctly save a multiplot to a file?

To begin with, I’m not an experienced R user. I use ggplot2 to create my plots, and another thing I should probably mention is that I use the RStudio GUI. Using an example from the R Cookbook, I'm able to create multiple plots in one window.

I would like to save this so-called multiplot to a file (preferably as jpeg), but somehow fail to do this.

I’m creating the multiplot as follows:

##define multiplot function
    multiplot <- function(..., plotlist=NULL, cols) {
        require(grid)

        # Make a list from the ... arguments and plotlist
        plots <- c(list(...), plotlist)

        numPlots = length(plots)

        # Make the panel
        plotCols = cols                          # Number of columns of plots
        plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols

        # Set up the page
        grid.newpage()
        pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
        vplayout <- function(x, y)
            viewport(layout.pos.row = x, layout.pos.col = y)

        # Make each plot, in the correct location
        for (i in 1:numPlots) {
            curRow = ceiling(i/plotCols)
            curCol = (i-1) %% plotCols + 1
            print(plots[[i]], vp = vplayout(curRow, curCol ))
        }

    }

## define subplots (short example here, I specified some more aesthetics in my script)
plot1a <- qplot(variable1,variable2,data=Mydataframe1)
plot1b <- qplot(variable1,variable3,data=Mydataframe1)  
plot1c <- qplot(variable1,variable2,data=Mydataframe2)
plot1d <- qplot(variable1,variable3,data=Mydataframe2)  

## plot in one frame
Myplot <- multiplot(plot1a,plot1b,plot1c,plot1d, cols=2)

This gives the desired result. The problem arises when I try to save to a file. I can do this manually in RStudio (using Export -> Save plot as image), but I would like to run everything in a script. I manage to save only subplot1d (which is last_plot()), and not the complete multiplot.

What I’ve tried so far:

  1. Using ggsave

    ggsave(filename = "D:/R/plots/Myplots.jpg")
    

    This results in only subplot 1d being saved.

  2. Using jpeg(), print() and dev.off()

    jpeg(filename = "Myplot.jpg", pointsize =12, quality = 200, bg = "white", res = NA, restoreConsole = TRUE)
    print(Myplot)
    dev.off()
    

    This results in a completely white image (just the background I assume). print(Myplot) returns NULL.

Not sure what I’m doing wrong here. My lack of understanding R is the reason I am stuck trying to find a solution. Can anyone explain what I’m doing wrong and perhaps suggest a way to solve my problem(s)?

Answers


Its because Myplot is the returned value from your multiplot function, and it returns nothing (its job is to print the graphs). You need to call multiplot with the jpeg device open:

jpeg(filename = "Myplot.jpg", pointsize =12, quality = 200, bg = "white", res = NA, restoreConsole = TRUE)
multiplot(plot1a,plot1b,plot1c,plot1d, cols=2)
dev.off()

should work.


Using the example code (R cookbook), it works for me

png("chickweight.png")
multiplot(p1, p2, p3, p4, cols=2)
dev.off()


And for completeness sake, ggsave does not work as it only saves the last printed ggplot object, which in your case is just the last plot. This is caused by the fact that multiplot creates the plot by drawing the ggplot objects onto different subsets of the total graphics device. An alternative is to create the plot by combining the ggplot objects into one big ggplot object, and then printing the object. This would be compatible with ggsave. This approach is implemented by arrangeGrob in the gridExtra package.


Need Your Help

Jquery - Simple Array, pushing item in if its not there already, removing item if it is there

jquery arrays filter

I'm building a simple filtering system, I simply want to add a string to an array and remove it if its already there on click of a link. I'll try to explain the best I can..

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

sql sql-server sql-server-2005 optimization sql-execution-plan

I'm trying to determine the relative performance of two different queries and have two ways of measuring this available to me: