PDG
PDG

Reputation: 287

How to return ggplot2 base object composition

I have saved my work space and in it there were base objects for a ggplot2 plot example

basep <- ggplot(data=dat, aes(x=Week, y=corr, color=Stream))

If I close and open R and load the workspace, basep is in the environment.

Is there a way to return the composition of basep (i.e.: ggplot(data=dat, aes(x=Week, y=corr, color=Stream))) so that I can use that for other graphs?

I know the best way is to save it in a script file but I want to know if I can return this in case I get only a workspace file from someone else.

Upvotes: 1

Views: 55

Answers (1)

Jaap
Jaap

Reputation: 83255

You can use basep for different kind of plots. A few examples:

basep + geom_point()

or:

basep + geom_bar()

or:

basep + geom_boxplot()

When you want to know what the code behind basep was, you can use str() to see what is stored in basep. An example:

# create example dataframe
dat <- data.frame(Week=c(1,1,2,2,3,3), corr=c(0.5,0.6,0.1,0.4,0.9,0.7), Stream=rep(c("a","b"),3))
# create basep
basep <- ggplot(data=dat, aes(x=Week, y=corr, color=Stream))

Whith str(basep) you get:

> str(basep)
List of 9
 $ data       :'data.frame':    6 obs. of  3 variables:
  ..$ Week  : num [1:6] 1 1 2 2 3 3
  ..$ corr  : num [1:6] 0.5 0.6 0.1 0.4 0.9 0.7
  ..$ Stream: Factor w/ 2 levels "a","b": 1 2 1 2 1 2
 $ layers     : list()
 $ scales     :Reference class 'Scales' [package "ggplot2"] with 1 field
  ..$ scales: NULL
  ..and 21 methods, of which 9 are  possibly relevant:
  ..  add, clone, find, get_scales, has_scale, initialize, input, n, non_position_scales
 $ mapping    :List of 3
  ..$ x     : symbol Week
  ..$ y     : symbol corr
  ..$ colour: symbol Stream
 $ theme      : list()
 $ coordinates:List of 1
  ..$ limits:List of 2
  .. ..$ x: NULL
  .. ..$ y: NULL
  ..- attr(*, "class")= chr [1:2] "cartesian" "coord"
 $ facet      :List of 1
  ..$ shrink: logi TRUE
  ..- attr(*, "class")= chr [1:2] "null" "facet"
 $ plot_env   :<environment: R_GlobalEnv> 
 $ labels     :List of 3
  ..$ x     : chr "Week"
  ..$ y     : chr "corr"
  ..$ colour: chr "Stream"
 - attr(*, "class")= chr [1:2] "gg" "ggplot"

Now, if want to know for example what the aes was:

> basep$mapping
List of 3
 $ x     : symbol Week
 $ y     : symbol corr
 $ colour: symbol Stream

Upvotes: 3

Related Questions