Duplicate commands in different ggplot2 plots

This is similar to the problem many people face with the Do Not Repeat Yourself (DRY) principle. I couldn't find the answer anywhere, maybe I was looking for the wrong conditions which means my question is probably not very good. If people have better suggestions on how to name the question that will be appreciated.

I have several graphs ggplot2

, and they all have common commands in common, as well as other commands that change too much, so it's not worth writing them as a loop / function at all.

How do I turn common commands into a neat one-liner?

An example will 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 should I build common.lines

? Making a string like this above doesn't work. I also tried making a vector and then paste

ing with +

as delimiter.

Any suggestions?

Greetings

+3


source to share


1 answer


You can put commands on 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

      

+4


source







All Articles