2

我正在使用 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))

这些图之间的唯一区别是 x 值;下一个情节是:

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

我怎么能重构这个,这样我就可以做类似的事情:

efgPlot <- getPlot(gmStats, EFGpct, Nrtg))
orPlot  <- getPlot(gmStats, ORpct, Nrtg))

更新

我认为我的重构方式并不是真正的“R-ish”(或者 ggplot-ish,如果你愿意的话);根据下面巴蒂斯特的评论,我在没有将任何东西重构为函数的情况下解决了这个问题;请参阅下面的答案

4

2 回答 2

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)
}

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

于 2012-05-31T12:30:41.897 回答
1

虽然 Joran 的回答对我帮助很大(而且他准确地回答了我的问题),但我最终还是按照 baptiste 的建议解决了这个问题:

# get the variablesI need from the stats data frame:
forPlot <- gmStats[c("wed_ID","Nrtg","EFGpct","ORpct","TOpct","FTTpct",
                     "plg_ShortName","Home")] 
# melt to long format:
forPlot.m <- melt(forPlot, id=c("wed_ID", "plg_ShortName", "Home","Nrtg"))
# use fact wrap to create 4 plots:
p <- ggplot(forPlot.m, aes(value, Nrtg)) +
  geom_point(aes(shape=plg_ShortName, colour=plg_ShortName)) + 
  scale_shape_manual(values=as.numeric(forPlot.m$plg_ShortName)) +
  stat_smooth(method="lm") +
  facet_wrap(~variable,scales="free")

这给了我:

净评级作为四个绩效指标的函数

于 2012-06-02T13:43:40.020 回答