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,749
  • 15
  • 75
  • 132

2 Answers2

7

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
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Wasn't aware of that. So much change happening in the tidyverse.. – andschar Aug 25 '20 at 07:13
  • 3
    Yeah...I know. But I think `aes_string` was one of those function which was much simpler to use than it's successor. – Ronak Shah Aug 25 '20 at 07:16
  • All of this "tidyeval" stuff is getting ridiculous. It feels like functions get deprecated every month and replaced with something more opaque and less useful. – Darren Jul 12 '23 at 03:37
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
  • 3,504
  • 2
  • 27
  • 35