Buthetleon
Buthetleon

Reputation: 1305

repeat ggplot using different data without typing out the whole code

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?

Upvotes: 7

Views: 1678

Answers (2)

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44648

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

Upvotes: 6

csgillespie
csgillespie

Reputation: 60462

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

Upvotes: 14

Related Questions