重构重复的ggplot代码

Mar*_*ijn 2 r ggplot2

我正在使用R和ggplot2来分析篮球比赛中的一些统计数据.我是R和ggplot的新手,鉴于我有限的经验,我喜欢我得到的结果.但随着我的进展,我发现我的代码重复了; 我不喜欢.

我创建了几个与此类似的图:

按有效实地目标百分比计算的净额

码:

efgPlot <- ggplot(gmStats, aes(EFGpct, Nrtg)) + 
  stat_smooth(method = "lm") + 
  geom_point(aes(colour=plg_ShortName, shape=plg_ShortName))  + 
  scale_shape_manual(values=as.numeric(gmStats$plg_ShortName))
Run Code Online (Sandbox Code Playgroud)

只有图之间的差异是x值; 下一个情节将是:

orPlot <- ggplot(gmStats, aes(ORpct, Nrtg)) + 
  stat_smooth(method = "lm") + ...  # from here all is the same
Run Code Online (Sandbox Code Playgroud)

我怎么能重构这个,这样我就可以这样做:

efgPlot <- getPlot(gmStats, EFGpct, Nrtg))
orPlot  <- getPlot(gmStats, ORpct, Nrtg))
Run Code Online (Sandbox Code Playgroud)

更新

我认为我的重构方式不是真正的"R-ish"(或者如果你愿意,那就是ggplot-ish); 根据下面的baptiste的评论,我解决了这个问题而没有将任何东西重构成函数; 请参阅下面的答案.

jor*_*ran 6

这种事情的关键是使用aes_string而不是aes(当然未经测试):

getPlot <- function(data,xvar,yvar){
    p <- ggplot(data, aes_string(x = xvar, y = yvar)) + 
            stat_smooth(method = "lm") + 
            geom_point(aes(colour=plg_ShortName, shape=plg_ShortName))  + 
            scale_shape_manual(values=as.numeric(data$plg_ShortName))
    print(p)
    invisible(p)
}
Run Code Online (Sandbox Code Playgroud)

aes_string允许您将变量名称作为字符串而不是表达式传递,这在编写函数时更方便.当然,您可能不希望硬编码颜色和形状比例,在这种情况下,您可以aes_string再次使用它们.