aes中的局部变量 [英] Local Variables Within aes

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

问题描述

当我使用ggplot绘图时,我试图在 aes 中使用局部变量。这是我的问题归结为本质:

  xy < -  data.frame(x = 1:10,y = 1:10)

plotfunc < - 函数(Data,YMul = 2){
ggplot(Data,aes(x = x,y = y * YMul))+ geom_line
}

plotfunc(xy)

这会导致以下错误:

  eval(expr,envir,enclos)中的错误:object'YMul'not found 
code>

好像我不能在 aes 。当局部变量超出范围时,是否会由于 aes 的内容稍后执行而发生?我怎样才能避免这个问题(除了不使用 aes 中的局部变量)?

解决方案

我会捕获本地环境,

  xy < -  data.frame(x = 1:10) ,y = 1:10)

plotfunc< - function(Data,YMul = 2){
.e < - environment()
ggplot(Data,aes x = x,y = y * YMul),environment = .e)+ geom_line()
}

plotfunc(xy)
pre>

I'm trying to use a local variable in aes when I plot with ggplot. This is my problem boiled down to the essence:

xy <- data.frame(x=1:10,y=1:10)

plotfunc <- function(Data,YMul=2){
    ggplot(Data,aes(x=x,y=y*YMul))+geom_line()
}

plotfunc(xy)

This results in the following error:

Error in eval(expr, envir, enclos) : object 'YMul' not found

It seems as if I cannot use local variables (or function arguments) in aes. Could it be that it occurrs due to the content of aes being executed later when the local variable is out of scope? How can I avoid this problem (other than not using the local variable within aes)?

解决方案

I would capture the local environment,

xy <- data.frame(x=1:10,y=1:10)

plotfunc <- function(Data, YMul = 2){
    .e <- environment()
    ggplot(Data, aes(x = x, y = y*YMul), environment = .e) + geom_line()
}

plotfunc(xy)

这篇关于aes中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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