Write a function that returns the graph vector ggplot2

I have this project where I want to make the same graphs for different different data frames. I thought I could do this by writing a function that takes a data frame as input and then returns a graph vector --- something like this:

df <- data.frame(x = runif(100), y = runif(100)) plot.list <- function(df){ g1 <- qplot(x, y, data = df) g2 <- qplot(x, x + y, data = df) c(g1, g2) } 

And I would like to do this:

 print(plot.list(df)[1]) 

get the same results as me:

 print(qplot(x,y, data = df)) 

As you will see, this does not work. It seems to be printing a data frame on which the graph is based (?). I suppose I misunderstand something pretty general about how objects work in R or about the nature of ggplot2 plots. Thanks for any advice (or maybe recommendations on the best ways to do what I'm trying to do).

+4
source share
3 answers

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 .

+13
source

Store objects in list instead of vector:

 plot.list <- function(df){ g1 <- qplot(x, y, data = df) g2 <- qplot(x, x + y, data = df) list(g1, g2) } 
+8
source

Here's another way to create multiple graphs from different data frames that have the same column names.

 d1 = data.frame(x = 1:10, y = rexp(10)) d2 = data.frame(x = 5:20, y = rnorm(16)) d3 = data.frame(x = 21:30, y = rpois(10, 4)) plots = llply(list(d1, d2, d3), `%+%`, p = qplot(x, y)) 
+4
source

All Articles