4

This seems like an issue many people would face, along the lines of the Don't Repeat Yourself (DRY) principle. I couldn't find the answer anywhere, perhaps I've been searching for the wrong terms, which means my question title probably isn't very good. If people have better suggestions of how to title the question that would be appreciated.

I have several ggplot2 plots, and they all have some commands in common, as well as other commands that vary too much, so it is not worthwhile writing them altogether as a loop/function.

How can I include the common commands in a neat, one-liner?

An example would probably explain more clearly:

common.lines <- "theme_bw() +
                geom_point(size = 2) +
                stat_smooth(method = lm, alpha = 0.6) +
                ylab("Height")"

my.plot <- ggplot(data = my_df, aes(x = "Length", y = "Height")) +
             common.lines

jim.plot <- ggplot(data = jim_df, aes(x = "Width", y = "Height")) +
              common.lines

My question is, how do I construct common.lines? Making a string like the above doesn't work. I also tried making a vector and then pasteing with + as a separator.

Any suggestions?

Cheers

Samuel Tan
  • 1,700
  • 5
  • 22
  • 35
  • Even less redundancy if you make a function like [this](http://stackoverflow.com/questions/15458526/r-pass-variable-column-names-to-ggplot2/15458593#15458593) – Henrik May 25 '15 at 09:42
  • @Henrik thanks, I was aware of that, and I can do that sometimes to some degree, but like I said sometimes all the variation cannot be accounted for in a function form – Samuel Tan May 26 '15 at 04:25

1 Answers1

6

You could put the commands in a list.

my_df <- data.frame(Length=rnorm(100, 1:100), Height=rnorm(100, 1:100))
jim_df <- data.frame(Width=rnorm(100, sin(seq(1,4*pi,len=100))),
                     Height=rnorm(100, 1:100))
common.lines <- list(theme_bw(), geom_point(size = 2), 
                     stat_smooth(method = lm, alpha = 0.6), ylab("Special Label"))

my.plot <- ggplot(data = my_df, aes(Length, Height)) + common.lines
jim.plot <- ggplot(data = jim_df, aes(Width, Height)) + common.lines
jim.plot
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Thanks! That works. Now I wonder if there is a better title for this question so that others kind find it by searching for the relevant terms... – Samuel Tan May 26 '15 at 04:30