4

I have an input data frame with 4 columns.

test <- head(mtcars[,c(1,2,8,9)])
test
                   mpg cyl vs am
Mazda RX4         21.0   6  0  1
Mazda RX4 Wag     21.0   6  0  1
Datsun 710        22.8   4  1  1
Hornet 4 Drive    21.4   6  1  0
Hornet Sportabout 18.7   8  0  0
Valiant           18.1   6  1  0

With a for loop, I would like to plot mpg vs cyl, then mpg vs vs, then mpg vs am, producing 3 distincts plots on the same page.

my code (inspired from Multiple ggplots on one page using a for loop and grid.arrange and ggplot2 : printing multiple plots in one page with a loop):

library(ggplot2)
library(gridExtras)

plot_list <- list()
for(i in 2:ncol(test)){
   plot_list[[i]] <- ggplot(test, aes(x=test[,i], y=mpg, fill=test[,i])) + 
   geom_point()
}
grid.arrange(grobs=plot_list)

Output:

Error in gList(list(wrapvp = list(x = 0.5, y = 0.5, width = 1, height = 1,  :
  only 'grobs' allowed in "gList"
user31888
  • 421
  • 6
  • 13

1 Answers1

4

The canonical way is faceting:

test <- head(mtcars[,c(1,2,8,9)])
library(reshape2)
test <- melt(test, id.vars = "mpg")
library(ggplot2)
ggplot(test, aes(x = value, y = mpg, fill = value)) +
  geom_point() +
  facet_wrap(~ variable, ncol = 1)

If you are set on your way:

library(gridExtra)
plot_list <- list()
test <- head(mtcars[,c(1,2,8,9)])
for(i in 2:ncol(test)){
    plot_list[[i-1]] <- ggplotGrob(ggplot(test, aes(x=test[,i], y=mpg, fill=test[,i])) + 
    geom_point())
}
do.call(grid.arrange, plot_list)
Roland
  • 127,288
  • 10
  • 191
  • 288
  • Works ! One bracket is missing after `geom_point()` though. Also, why when I invoke `ggsave("my_plot.pdf")` right after the `do.call()`, I only get the last plot in the file and not the 3? – user31888 May 16 '18 at 13:32
  • You cannot use `ggsave` with the second method. You must use `pdf`. – Roland May 16 '18 at 13:42
  • I am missing something. I placed `pdf("My_3_plots.pdf")` before the `for loop` and `dev.off()` after the `do.call`, but the pdf file generated is blank (i can open it without errors). – user31888 May 16 '18 at 13:55
  • Call `dev.off()` multiple times until you get `Error in dev.off() : cannot shut down device 1 (the null device)` and try again. You can place `pdf("My_3_plots.pdf")` before `do.call`. – Roland May 16 '18 at 13:58