R-如何将变量传递给ggplot

时间:2020-08-25 07:04:08

标签: 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)

鉴于此,想在上面将其概括为一个带有以下参数的函数

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

  # How should I use the variables passed into the function above within ggplot
}

这样我就可以如下调用函数

scatterWithRegLine(df, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))

2 个答案:

答案 0 :(得分:3)

不建议使用aes_string,可以将sym!!结合使用:

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

然后用

调用
scatterWithRegLine(mtcars, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))

答案 1 :(得分:1)

免责声明:aes_string()有效,但是现在已不推荐使用。有关最新方法,请参阅@ ronak-shah的答案。


您可以使用aes_string()代替aes()并将参数作为字符串传递。

require(ggplot2)

fun = function(dat, x, y, method) {
  ggplot(dat, aes_string(x = x, y = y)) +
    geom_point() +
    geom_smooth(method = method)
}

fun(iris,
    x = 'Sepal.Length', 
    y = 'Sepal.Width',
    method = 'loess')