Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

r - Accesing a variable in a ggplot function

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,13,14,15,16,17,18,19,20,21,12,23))

When I try running this function, to access the variable inside a ggplot function.

FUN<-function(data, fun.y,yr) {
  fun.data <- data     
  ggplot(fun.data,aes(yr, fun.y))+geom_point()+scale_y_continuous(fun.y)    
}

FUN(data, "ntemp", yr)

I get an Error in eval(expr, envir, enclos) : object 'fun.y' not found

How can I solve this on R3.02?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...