2
votes

My goal is to write a function that produces plots with ggplot2 and then use the multiplot function (http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/) to combine the function-generated plots with other plots. (I know how to use facets in ggplot2, but that is not what I want to do here). I have found that when I write a function to produce plots, multiplot no longer works. Here is a simplified example using the data set mtcars.

Using ggplot regularly works well with multiplot:

   p1<-ggplot((subset(mtcars, gear==4)), aes(x=mpg, y=hp)) +geom_point() +
            ggtitle("4 gears")
    p2<-ggplot((subset(mtcars, gear==3)), aes(x=mpg, y=hp)) +geom_point() +
            ggtitle("3 gears")
    multiplot(p1, p2, cols=2)

However, multiplot doesn't work if the same plots are generated using a function. The plots are displayed individually instead of in a matrix.

plot_fun <-function(data_frame, title) {
        print((ggplot(data_frame, aes(x=mpg, y=hp)) + 
                      geom_point() +
                      ggtitle(title)) ) }

p3 <-plot_fun((subset(mtcars, gear==4)), "4 gears")
p4 <-plot_fun((subset(mtcars, gear==3)), "3 gears")
multiplot(p3, p4, cols=2)

Clearly there is something I don't understand about what my function outputs and/or the input required by multiplot. What am I doing wrong? I appreciate the help.

1
Get rid of the print(...) call in the function. You need to return a ggplot object to pass to multiplot(...).jlhoward

1 Answers

3
votes

Turning my comment into an answer: multiplot(...) takes as arguments ggplot objects, but your plot_fun(...) does not return ggplot objects. Get rid of the call to print(...).

plot_fun <-function(data_frame, title) {
  ggplot(data_frame, aes(x=mpg, y=hp)) + 
           geom_point() +
           ggtitle(title) }

p3 <-plot_fun((subset(mtcars, gear==4)), "4 gears")
p4 <-plot_fun((subset(mtcars, gear==3)), "3 gears")
multiplot(p3, p4, cols=2)