Explain quosure to a dummy

172 views Asked by At

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

There are 3 answers

0
Ronak Shah On BEST ANSWER

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)
}
0
Konrad Rudolph On

Replace aes_string by aes.

aes_string was the old way of using computed variables with ‘ggplot2’. Quosures (used inside a regular aes call) are the new way. You can’t mix the two.

0
akrun On

We can convert the string to symbol and use !!

make_plot <- function(data, plot_var) {
       ggplot(data,  aes(x = !! rlang::sym(plot_var)) + geom_area(alpha = 0.5)
  }