Accesing a variable in a ggplot function

前端 未结 1 1000
渐次进展
渐次进展 2020-12-20 01:36

I have a sample data below

data <- data.frame(yr=c(1999,2000,2001,2002,2003,2004,2005,2006,2007,2009,2010,2011,2012), 
                   ntemp =c(11,12,         


        
相关标签:
1条回答
  • 2020-12-20 02:17

    aes only looks at the variables in data argument. If you would like to pass variable as an argument to FUN by its character name, use aes_string:

    FUN <- function(data, x, y) {
      ggplot(data, aes_string(x=x, y=y)) + geom_point()
    }
    
    FUN(data, y="ntemp", x="yr")
    

    A small correction: variable inside aes call should be defined in the scope where the ggplot object is evaluated, so technically a variable is looked up in data first, then in global environment (by default). See this and this questions.

    0 讨论(0)
提交回复
热议问题