R - 如何将变量传递给ggplot

use*_*440 0 r ggplot2

我用来ggplot生成带有拟合线的散点图,如下所示

ggplot(df, aes(x=colNameX, y=colNameY)) + 
    geom_point() +
    geom_smooth(method=loess, se=T, fullrange=F, size=1) + ylim(0,5)
Run Code Online (Sandbox Code Playgroud)

鉴于此,想要将上面概括为一个采用以下参数的函数

scatterWithRegLine = function(df, xColName, yColName, regMethod, showSe, showFullrange, size, yAxisLim) {

  # How should I use the variables passed into the function above within ggplot
}
Run Code Online (Sandbox Code Playgroud)

这样我就可以按如下方式调用该函数

scatterWithRegLine(df, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 8

aes_string不推荐使用 of ,您可以使用symwith !!

library(ggplot2)
library(rlang)

scatterWithRegLine = function(df, xColName, yColName, regMethod, showSe, showFullrange, size, yAxisLim) {
  
  ggplot(df, aes(x = !!sym(xColName), y = !!sym(yColName))) + 
    geom_point() +
    geom_smooth(method= regMethod, se=showSe, fullrange=showFullrange, size=size) + ylim(yAxisLim)
}
Run Code Online (Sandbox Code Playgroud)

然后用

scatterWithRegLine(mtcars, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))
Run Code Online (Sandbox Code Playgroud)

  • 是的,我知道。但我认为“aes_string”是那些比它的后继者更容易使用的函数之一。 (3认同)