[Solved]-Passing variables to a function using ggplot in r-R

Without having your data, here’s a simplified example of your function using some base R datasets. I think you’re having a quosure problem: you can’t directly access columns just by using the string that corresponds to a column name. Instead, you want to use something like q_var <- quo(var), and then !!q_var in referring to the column by its bare name. I have a fair amount of trouble with writing functions like this, but see the “Programming with dplyr” vignette for more explanation.


make_plot <- function(full_df, var1, var2) {
    # use quo to access the values in the strings var1, var2
    quo_var1 <- quo(var1)
    quo_var2 <- quo(var2)

    df <- full_df %>% rownames_to_column("name") %>% select(name, x = !!quo_var1, y = !!quo_var2)

    ggplot(df, aes(x = x, y = y)) +
        geom_text(aes(label = name), size = 2.5) +
        # still have var1, var2 strings--can use as labels
        labs(x = var1, y = var2)

make_plot(mtcars, "mpg", "disp")

make_plot(mtcars, "hp", "qsec")

make_plot(as.data.frame(state.x77), "Income", "Life Exp")

Created on 2018-04-20 by the reprex package (v0.2.0).

Read more here: Source link