display ggplots created in loop together

41 views
Skip to first unread message

Jan Vanaverbeke

unread,
Dec 3, 2015, 3:48:11 PM12/3/15
to ggplot2
loDear List!

I am creating several ggplots in a loop. All of them have the same dependent variable, but different independent variables. All independent variables and the dependent variable are stored in a single dataframe.   I would like to plot all the plots together on 1 page. Using the code below, the  plots are  wrong: the x-axis for all the plots is the same, and taken from the final plot. However, axis and plot titles are correct. When I use print(ggplot(...)) I get correct plots, but I can't find a way to plot these together on one page. Anyway, I would like to find the correct way to store the plots in a list, and use the list to plot them on a single pagen.
Anyone who could provide a solution for this problem?

here is my code, but using a fake dataframe.

library(ggplot2)
library(grid)
library(gridExtra)

a=1:10
b=11:20
c=21:30
y=41:50
df=data.frame(a,b,c,y)


names=colnames(df)

plot_list=list()  
for (i in 1:3)
{
 
 
  plot_list[[i]]= ggplot(data = df, aes(x = df[,i], y=y)) + geom_point() +
    geom_smooth(method="lm", se=F, colour="black")  +
    xlab(names[i:i])+
    labs(title=names[i:i]) +
    theme_bw() +                              
    theme(panel.grid.minor = element_blank(),
    panel.grid.major=element_blank())+
    theme(plot.title=element_text(face="bold", size=20))
 
 
}
plot_list
plot_grid(plotlist=plot_list)





Thanks a lot,

Jan


-- 
Dr. Jan Vanaverbeke
Royal Belgian Institute of Natural Sciences, Operational Directorate Natural Environment (OD Nature)
Marine Ecology and Management
Gulledelle 100, 1200 Brussels, Belgium

Website http://www.naturalsciences.be; http://www.odnature.be

Brandon Hurr

unread,
Dec 3, 2015, 4:05:54 PM12/3/15
to Jan Vanaverbeke, ggplot2
Jan, 

Maybe this doesn't do what you really want, but have you considered faceting? 
require(tidyr)
require(dplyr)
require(ggplot2)

a=1:10
b=11:20
c=21:30
y=41:50
df=data.frame(a,b,c,y)

gather(df, alpha, value, -y) %>%
 ggplot(., aes(x=value, y = y)) +
 geom_smooth(method="lm", se=FALSE, colour = "black") +
 facet_grid(alpha~.)

Jan Vanaverbeke

unread,
Dec 7, 2015, 4:36:27 AM12/7/15
to Brandon Hurr, ggplot2
thanks!

this indeed provides a nice workaround.

all the best,

Jan
Reply all
Reply to author
Forward
0 new messages