Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Refer to a function param in ggplot

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Produces a plot:
enter image description here

How can I call my function to get the same result:

plot_eval(diamonds, price)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading