R:ggplot_build包含在函数中

时间:2015-11-09 17:17:51

标签: r

我将尝试在函数内运行ggplot_build并返回错误: eval中的错误(expr,envir,enclos):找不到对象'myData' 这是代码:

   # Summarise number of movie ratings by year of movie
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
  nums <- tapply(df$length, df$year, length)
  data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)), number=as.vector(nums))
}))

p <- ggplot(mry, aes(x=year, y=number, group=rating))
p + geom_line()

function_mm <- function(myData){
    for(j in 1:2){ 
      p1 <- ggplot(myData, aes(x=myData[,2], y=myData[,3])) + geom_line()
      g1 <- ggplot_gtable(ggplot_build(p1))
    }
  return(p1)
}
Q1 <- function_mm(mry) 

代码在函数外部时正确运行:

for(j in 1:2){ 
          p1 <- ggplot(myData, aes(x=myData[,2], y=myData[,3])) + geom_line()
          g1 <- ggplot_gtable(ggplot_build(p1))
        }

提前致谢!

1 个答案:

答案 0 :(得分:3)

当您使用aes时,您犯了使用aes_string(及其非标准评估)的经典错误:

function_mm <- function(myData){
  for(j in 1:2){ 
    xy <- names(myData)[c(2, 3)]
    p1 <- ggplot(myData, aes_string(x=xy[1], y=xy[2])) + geom_line()
    g1 <- ggplot_gtable(ggplot_build(p1))
  }
  return(p1)
}
Q1 <- function_mm(mry) 
#works