There are several ways in which you could approach such things, but one trick that you might not suspect is that ggplot2 has a special operator for this kind of purpose, i.e. creating the same graph with using different data frames:
d1 <- data.frame(x=1:10,y=rnorm(10)) d2 <- data.frame(x=20:29,y=runif(10)) p <- ggplot(data = d1, aes(x = x, y = y)) + geom_point() print(p) print(p %+% d2)
Thus, the %+% operator will connect the data frame d2 to the graph structure defined by p . This way you can create a graph once and then apply it to different data frames.
In order to more directly address the use that you outline in your question, after creating the first graph p you can lapply build this structure from a list of data frames:
d3 <- data.frame(x = 1:10, y = rexp(10)) rs <- lapply(list(d1,d2,d3),FUN = function(x,p){p %+% x},p=p)
And then you have three graphs saved in rs .
source share