Home > Blockchain >  Refer to a function param in ggplot
Refer to a function param in ggplot

Time:09-16

Attempt of a function:

plot_eval <- function(data, metric) {
  data |> 
    ggplot(aes(x = cut, y = metric))  
    geom_point()  
    ggtitle(metric)
}

Tried with diamonds data set e.g:

plot_eval(diamonds, price)
Error in dots_list(..., title = title, subtitle = subtitle, caption = caption, :
object 'price' not found

I would like the function to run in the following way, here I create the plot directly outside of a function:

diamonds |> 
  ggplot(aes(x = cut, y = price))  
  geom_point()  
  ggtitle('price')

Produces a plot: enter image description here

CodePudding user response:

You could do:

library(ggplot2)

plot_eval <- function(data, metric) {
  
  metric <- enquo(metric)
  
  data |> 
    ggplot(aes(x = cut, y = !!metric))  
    geom_point()  
    ggtitle(metric)
}

plot_eval(diamonds, price)

Created on 2022-09-15 with reprex v2.0.2

  • Related