Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse ggplot layers in multiple plots

Tags:

r

ggplot2

I am plotting tons of graphs which essentially use the same type of formatting. Just wondering if it possible to store these layers in a variable and reuse them.

Approach 1 (does not work)

t <- layer1() + layer2()
ggplot(df,aes(x,y)) + t

Approach 2 (works but not very elegant)

t <- function(x) x + layer1() + layer2()
t(ggplot(df,aes(x,y))

Any suggestion along the lines of approach 1?

Thanks!

like image 841
jamborta Avatar asked Sep 11 '13 16:09

jamborta


1 Answers

While I wait for some clarification, here are a few examples that demonstrate how to add previously created layers to an existing plot:

p <- ggplot(mtcars,aes(x = cyl,y = mpg)) + 
        geom_point()    
new_layer <- geom_point(data = mtcars,aes(x = cyl,y = hp),colour = "red")
new_layer1 <- geom_point(data = mtcars,aes(x = cyl,y = wt),colour = "blue")

p + new_layer

p + list(new_layer,new_layer1)
like image 124
joran Avatar answered Sep 28 '22 00:09

joran