我用来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)
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)
| 归档时间: |
|
| 查看次数: |
1521 次 |
| 最近记录: |