Most up to date way to use ggpot with variables representing strings?

I frequently need to use ggplot "programmatically" and always have trouble taking a plot I wrote in global scope and putting it into a function.

  pop_compare_plot = econ_df %>%
    ggplot(aes(x = R_data_hat, y = R_sim_hat)) + 
    geom_point() + 
    geom_smooth()

Now, I want to use other data besides R. I want to turn this into a function where I can specify a different series.

make_plot = function(df, xvar, yvar){
  pop_compare_plot = econ_df %>%
    ggplot(aes(x = xvar, y = yvar)) + 
    geom_point() + 
    geom_smooth()
}

The above doesn't work, of course, due to tidy evaluation.

I really don't want to use quo and enquo since I cant guarantee other people working on the project understand the details of that behavior.

It seems like aes_string is being deprecated as well.

What is the correct way to do this? Can I use {...} inside ggplot? I think things have changed since I last tried this and I'm wondering what current best practices are.

1 Like

This is the simplified version of the tidy evaluation:

make_plot = function(df, xvar, yvar){
  pop_compare_plot = df %>%
    ggplot(aes(x = {{xvar}}, y = {{yvar}})) + 
    geom_point() + 
    geom_smooth()
}

Thank you! Do you know the version bounds required for this?

It's been around for a while now. I think this is where it was introduced:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.