Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Create an independent copy from an ggplot-Object

Tags:

oop

r

ggplot2

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.

like image 427
jakob-r Avatar asked Jul 11 '12 11:07

jakob-r


People also ask

What does %>% do in ggplot?

%>% 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.

Is ggplot2 different from ggplot?

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'.

Can you use ggplot without a Dataframe?

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.

What is Ggproto R?

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.


1 Answers

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

enter image description here

#Change the data frame
dat$y <- rexp(10)
#Replot g using the altered data frame
g %+% dat

enter image description here

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).

like image 122
joran Avatar answered Oct 01 '22 17:10

joran