Search code examples
rggplot2shinyquosure

Explain quosure to a dummy


I'm trying to make a function that will produce a plot when given passed a variable to plot. The variable is selected from a dropdown - hence aes_string.

make_plot <- function(data, plot_var) {
          plot_var <- enquo(plot_var)
          ggplot(data) +
            aes_string(x = !!plot_var) +
            geom_area(alpha = 0.5)
          }
        
make_plot(my_data, variable_i_want_to_plot)

I get this error:

Error: Quosures can only be unquoted within a quasiquotation context.
# Bad: list(!!myquosure) # Good: dplyr::mutate(data, !!myquosure)

Solution

  • aes_string has been deprecated. Try this function :

    make_plot <- function(data, plot_var) {
      ggplot(data) + aes(x = .data[[plot_var]]) + geom_area(alpha = 0.5)
    }