R:使用geom_line访问函数内的列名

时间:2015-04-21 15:50:54

标签: r ggplot2

我有以下使用lapply生成的图表列表。在函数subsetaes_string中,我似乎无法传递对象i(列名称):

require(ggplot2)

cols <- colnames(mtcars)
lapply(cols[2:length(cols)], 
       function(i) {
         ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
           geom_histogram() # +
#            geom_vline(aes(xintercept=mean(get(i), na.rm=T)),
#                       color="red", linetype="dashed", size=1)

         }
       )

然而,如果我取消注释geom_line,我会收到以下错误

## Error in get(i) : object 'i' not found

2 个答案:

答案 0 :(得分:4)

不幸的是xintercept无法在aes中工作,因此该对象在geom_vline的环境中确实不存在。

您可以将其用作快速修复:

cols <- colnames(mtcars)
lapply(cols[2:length(cols)], 
       function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
           ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
               geom_histogram()  +
                       geom_vline(xintercept=Mean,
                                  color="red", linetype="dashed", size=1)

       }
)

答案 1 :(得分:1)

您可以像使用aes_string美学

一样使用x
lapply(cols[2:length(cols)], function(i) {
    ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
        geom_histogram() +
        geom_vline(
            aes_string(xintercept = paste0("mean(", i, ", na.rm = TRUE)")),
            color = "red", linetype="dashed", size = 1)
})