I would like to have multiple ggplots plots in a single plot.
ISSUE: When trying to create a list of plots (to be used later in grid.arrange) using a for-loop, the list is returned empty.
I used these two posts:
1)create figures in a loop
2)use grid.arrange to save in a single fig
to come up with the following code (simpler version)* to plot probability density curves:
#models = 33 obs of 1 variable
plotlist = list()
for (i in 1:33)
{
modname = models$col1[i]
p<- ggplot() + geom_line(aes(xi,yi)) + geom_line(aes(ai,bi)) +
ggtitle(modname) ## the x,y,a,b are just illustrative.
#In reality, each pair is produced using fitdist and dgamma functions for
# data (single column) from separate .csv
ggsave(outpath)
plotlist[[i]] = p
}
main <- grid.arrange(grobs=plotlist,ncol=6)
main
ggsave("bigplot.png",p)
ISSUE (further explanation): plotlist
shows up as an empty list. As a result, grid.arrange just plots the subplot created in the last loop 33 times. But, what is strange is that the grid.arrange plot has the correct title for all subplots (assigned using modname)!!! In the attached picture, you will see that all subplots are the same except for the title. Since I save individual subplots as well, I know that the issue is not with the data/code for subplots.
I am fairly new to R and this is my first ggplot2 (* excuse the multiple geom_line()). As a result, it has taken me a while to figure out how to fit distributions and plot them (Thanks, stackoverflow!!) in the first place. So, any help here will be much appreciated.
Update: I was able to accomplish the above using PIL
package in python . However, I would really like to be able to do this in R.
If I have understood you correctly (and I am not sure), this is simply about saving your plot files.
I think the problem is simply that grid.arrange()
does not work with last_plot()
, which is what ggsave
apparently uses. So it is best to be explicit about what plot you want it to save.
Here is a simple working example, with less plots and no regression models, just a few random plots:
library(ggplot2)
library(gridExtra)
plotlist = list()
n <- 100
for (i in 1:9)
{
df <- data.frame(x=rnorm(n),y=rnorm(n))
pname <- paste0("Plot-",i)
p<- ggplot(df) + geom_point(aes(x,y)) + ggtitle(pname)
ggsave(paste0(pname,".png"),p)
plotlist[[i]] = p
}
p <- grid.arrange(grobs=plotlist,ncol=6)
ggsave("bigplot.png",p)
The text output:
Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image Saving 4.76 x 5.28 in image > p <- grid.arrange(grobs=plotlist,ncol=3) > ggsave("bigplot.png",p) Saving 4.76 x 5.28 in image
And the final plot:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With