0

I'm using ggplot to generate a scatter plot with a fitted line as follows

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

Given this, want to generalize above into a function that takes the following arguments

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

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

Such that I can call the function as follows

scatterWithRegLine(df, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))
user3206440
  • 4,229
  • 11
  • 59
  • 107

2 Answers2

3

Using of aes_string is deprecated, you can use sym with !! :

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

and then call it with

scatterWithRegLine(mtcars, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
1

DISCLAIMER: aes_string() works, however it is soft-deprecated now. Refer to @ronak-shah s answer, for a more up to date approach.


You could use aes_string() instead of aes() and pass the arguments as strings.

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')
andschar
  • 2,731
  • 1
  • 23
  • 32