2015-05-25 19 views
3

這似乎是許多人將面臨的問題,沿着不重複自己(DRY)原則的方向行事。我無法在任何地方找到答案,也許我一直在尋找錯誤的術語,這意味着我的問題標題可能不是很好。如果人們有更好的關於如何標題的建議,那將是值得讚賞的。在不同的ggplot2圖中重複命令

我有幾個ggplot2圖,他們都有一些共同的命令,以及其他命令變化太大,所以它不值得將它們寫成循環/函數。

如何在普通的命令中包含一個簡潔的單線?

一個例子可能會更清楚地解釋:

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 

我的問題是,我該如何構建common.lines?製作像上面這樣的字符串不起作用。我也嘗試製作一個矢量,然後用+作爲分隔符。

有什麼建議嗎?

乾杯

+0

即使較少的冗餘,如果你做出這樣[這](http://stackoverflow.com/questions/15458526/r-pass-variable-column-names-to-ggplot2/15458593#15458593) – Henrik

+0

功能@Henrik謝謝,我意識到這一點,而且我可以在某種程度上做到這一點,但就像我說過的,有時候所有的變體都不能用函數形式來解釋 –

回答

4

您可以將這些命令放在列表中。

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 
+0

謝謝!這樣可行。現在我想知道這個問題是否有更好的標題,以便其他人通過搜索相關術語來找到它... –