Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat ggplot using different data without typing out the whole code

Tags:

r

ggplot2

Is a way to re-plot something but using a subsetted dataset without writing the entire code out again?

maybe something like last_plot() but allow one to specific the data.frame to use?

like image 863
Buthetleon Avatar asked Oct 23 '12 14:10

Buthetleon


2 Answers

You can use the %+% operator:

##Two data sets:
R> dd = data.frame(x = runif(10), y=runif(10))
R> dd_new = data.frame(x = runif(10), y=runif(10))

R> g = ggplot(dd, aes(x,y)) + geom_point() 
R> g
R> g %+% dd_new
like image 91
csgillespie Avatar answered Sep 30 '22 12:09

csgillespie


Although I feel that Csgillespie's answer is complete. I'd like to add a secondary method that I personally use quite frequently, but rarely see out in the wild. It's great for applying corporate/personal themes and avoiding retyping one's work.

You can save ggplot2 elements as a list, just as though you were writing them with ... + ... +

default.point <- list(geom_point(), 
coord_flip(),
theme(
axis.text.x=element_text(size=12
)))

ggplot(diamonds,aes(carat, price, colour=cut)) + default.point
like image 43
Brandon Bertelsen Avatar answered Sep 30 '22 12:09

Brandon Bertelsen