Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create lists of ggplot

Tags:

r

ggplot2

I have been trying to create functions that return a list of ggplot and am having various problems. Fundamentally however, I do not understand why this is TRUE

"data.frame" == class(c(qplot(1:10,rnorm(10)))[[1]])

when this is [TRUE,TRUE]

c('gg','ggplot') == class(qplot(1:10,rnorm(10))) 

I havent seen any questions similar to this. I see various questions that are solved by things like

lapply(someList, function(x) {
  #make ggplot, then use print(...) or whatever
  })

So I am guessing there is something about passing ggplot objects out of functions or between environments or something. Thanks for any clues about the ggplot or R that I am missing.

like image 681
Alan Berezin Avatar asked Apr 02 '14 16:04

Alan Berezin


1 Answers

library(ggplot2)
p = c(qplot(1:10,rnorm(10)))
p2 = qplot(1:10,rnorm(10))

p[[1]] (same as p[['data']])) is supposed to be a dataframe. It usually holds the data for the plot.

p is a list because you used the c function.

p2 is a ggplot because that's what qplot returns.

Take a look at the attributes of each object.

attributes(p)
# $names
# [1] "data"        "layers"      "scales"      "mapping"     "theme"       "coordinates"
# [7] "facet"       "plot_env"    "labels"  

attributes(p2)
# $names
# [1] "data"        "layers"      "scales"      "mapping"     "theme"       "coordinates"
# [7] "facet"       "plot_env"    "labels"     
# 
# $class
# [1] "gg"     "ggplot"

To store many ggplot objects, use list.

ggplot.objects = list(p2,p2,p2)

The c help file shows that ggplot is not a possible output. It also states that

c is sometimes used for its side effect of removing attributes except names, for example to turn an array into a vector

If you wanted c to return ggplot objects, then you could try defining your own c.ggplot function. You'll have to read a good deal about S3 and S4 functions to understand what's going on.

like image 154
kdauria Avatar answered Oct 19 '22 19:10

kdauria