在ggplot函数中访问一个变量 [英] Accesing a variable in a ggplot function

查看:123
本文介绍了在ggplot函数中访问一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个样本数据在

  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))

当我尝试运行此函数时,要访问ggplot中的变量

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

FUN(data,ntemp ,yr)

我得到一个 eval中的错误(expr,envir,如何在R3.02上解决这个问题?

$ b $:找到对象'fun.y'



b

解决方案

aes 只查看 data FUN ,请使用 aes_string

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

FUN(data,y =ntemp,x =yr)

一个小的更正:在 aes 调用中的变量应该在ggplot对象被评估的范围中定义,所以在技术上首先在数据中查找变量,然后在全局环境中(默认情况下)查找变量。请参阅这个问题。


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?

解决方案

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.

这篇关于在ggplot函数中访问一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆