Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a function that returns a vector of ggplot2 graphs

Tags:

r

ggplot2

I have this project where I want to make the same plots for a variety of different data frames. I was thinking I could do this by writing a function that takes a data frame as an input and then returns a vector of plots---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'd like to do this:

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

getting the same results as if I had done:

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

As you'll see, this doesn't work---it seems to print out the data frame that the plot is based on (?). My guess is that I'm misunderstanding something pretty basic about how objects work in R or the nature of ggplot2 plots. Thanks for any advice (or perhaps recommendations on better ways to do what I'm trying to do).

like image 968
John Horton Avatar asked Oct 04 '11 22:10

John Horton


2 Answers

There are several ways you could approach this sort of thing, but one trick you may not be aware of is that ggplot2 has a special operator for this sort of purpose, i.e. creating the same graph 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)

So the %+% operator will plug in the data frame d2 into the plot structure defined by p. That way you can create the plot once and then apply it to different data frames.

To more directly address the use you outline in your question, once you create the first plot, p, you can lapply this plot structure along 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 plots stored in rs.

like image 116
joran Avatar answered Oct 26 '22 04:10

joran


Store the objects in a list instead of a vector:

plot.list <- function(df){
  g1 <- qplot(x, y, data = df)
  g2 <- qplot(x, x + y, data = df)
  list(g1, g2) 
}
like image 37
Chase Avatar answered Oct 26 '22 03:10

Chase