Prepare ggplot settings before calling

I'm new to RStudio and have made great progress so far, in no small part thanks to this forum. I haven't found (or recognised) an answer to this, hence the question.

I see that a ggplot call can be built up like this

p <- ggplot(df_sc_t5_zoom, aes(x = date_notified, y = value)) 
  p + geom_line(aes(color = variable)) + theme_light() 
  p + facet_wrap(~ variable, ncol=1, scales = "free_y")

# Then call the plot by 

Is it possible to define the settings first and add them to a ggplot call later?
This doesn't work but illustrates what I mean.

 pls <- geom_line(aes(color = variable)) + theme_light()
 pls + facet_wrap(~ variable, ncol=1, scales = "free_y")
# other things happen...
# Then call the plot by 
ggplot(df_sc_t5_zoom, aes(x = date_notified, y = value)) + pls

Thanks in advance


1 Like

I never thought to try it but this seems to work

dat1  <-  data.frame(xx = 1:20, yy = 20:1)

p1  <-  geom_line(colour = "red")

p2  <-  ggplot(dat1, aes(xx, yy))

p2 + p1

It looks like the "ggplot" command must be first .

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Thanks @jrkrideau
So, I learn more. If I set up as below

dat1  <-  data.frame(xx = 1:20, yy = 20:1)

pset1  <-  geom_line(colour = "red")
pset2 <-  theme_light() 

p  <-  ggplot(dat1, aes(xx, yy))

I can declare pset1, pset2 and more anywhere in the code as long as it is before I attempt to use them.

What cannot be done is to combine them.

# All these are invalid
pset1  <-  geom_line(colour = "red") +  theme_light() 

pset_all = pset1 + pset2

pset_all <- pset1 + pset2

All of these give the error Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

But this works

p + pset1 + pset2

So, back to my original question. I can create plot settings in advance and apply them when I call a plot. The reason I couldn't get it to work is that I was trying to combine multiple settings.
This achieves what I wanted to do, which is to have a library of plot settings that I can apply to each relevant plot.
The benefits are tidier code and the ability to change multiple plots with a small code change.