ggplot2 : printing multiple plots in one page with a loop

帅比萌擦擦* 提交于 2019-12-05 13:44:55

Your error comes from indexing a list with [[:

consider

pl = list(qplot(1,1), qplot(2,2))

pl[[1]] returns the first plot, but do.call expects a list of arguments. You could do it with, do.call(grid.arrange, pl[1]) (no error), but that's probably not what you want (it arranges one plot on the page, there's little point in doing that). Presumably you wanted all plots,

grid.arrange(grobs = pl)

or, equivalently,

do.call(grid.arrange, pl)

If you want a selection of this list, use [,

grid.arrange(grobs = pl[1:2])
do.call(grid.arrange, pl[1:2])

Further parameters can be passed trivially with the first syntax; with do.call care must be taken to make sure the list is in the correct form,

grid.arrange(grobs = pl[1:2], ncol=3, top=textGrob("title"))
do.call(grid.arrange, c(pl[1:2], list(ncol=3, top=textGrob("title"))))
Metrics
library(gridExtra) # for grid.arrange
library(grid) 
grid.arrange(pltList[[1]], pltList[[2]], pltList[[3]], pltList[[4]], ncol = 2, main = "Whatever") # say you have 4 plots

OR,

do.call(grid.arrange,pltList)

I wish I had enough reputation to comment instead of answer, but anyway you can use the following solution to get it work.

I would do exactly what you did to get the pltList, then use the multiplot function from this recipe. Note that you will need to specify the number of columns. For example, if you want to plot all plots in the list into two columns, you can do this:

print(multiplot(plotlist=pltList, cols=2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!