ggplot2: Create an independent copy from an ggplot-Object
ggplot2, oop, r
Solution
Personally, I think that @Joshua's answer is too complicated (if I'm understanding what you want to do).
I don't think it makes any sense to change the data frame stored in the plot object, since ggplot2 has a special infix operator that is specifically designed to apply a new data frame to a given plot object: `%+%`.
dat <- data.frame(x=runif(10),y=runif(10))
g <- ggplot(dat, aes(x,y)) + geom_point()
g
#Change the data frame
dat$y <- rexp(10)
#Replot g using the altered data frame
g %+% dat
This works, of course, with not just altered versions of the original data frame, but an entirely new data frame, provided it has all the required variables in it (and they are named the same).
Problem
I'm not sure how to put this in OO-Speech. But when you are creating a ggplot it will be dependent from the source data.frame. So how can you save a ggplot without that dependency? ``` dat <- data.frame(x=runif(10),y=runif(10)) g <- ggplot(dat, aes(x,y)) + geom_point() g dat <- NULL g ``` The second $g$ won't produce a plot hence dat is $NULL$. How can I save $g$ so that dat can be changed? I know it is not good practice but I got some very long code on which I don't want to fiddle about.