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.
%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.
You may notice that we sometimes reference 'ggplot2' and sometimes 'ggplot'. To clarify, 'ggplot2' is the name of the most recent version of the package. However, any time we call the function itself, it's just called 'ggplot'.
ggplot only works with data frames, so we need to convert this matrix into data frame form, with one measurement in each row. We can convert to this “long” form with the melt function in the library reshape2 . Notice how ggplot is able to use either numerical or categorical (factor) data as x and y coordinates.
ggproto implements a protype based OO system which blurs the lines between classes and instances. It is inspired by the proto package, but it has some important differences. Notably, it cleanly supports cross-package inheritance, and has faster performance.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With