Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Wrong evaluation environment for expressions in aes() #743

Closed
wch opened this Issue · 2 comments

3 participants

@wch
Collaborator

Expressions in aes() are evaluated in the global environment, but they should be evaluated in the calling environment. Example:

library(ggplot2)

foo <- 4
ggplot(mtcars, aes(x = wt + foo, y = mpg)) +
  geom_point()
# Works


f <- function() {
  foo2 <- 4
  ggplot(mtcars, aes(x = wt + foo2, y = mpg)) +
    geom_point()
}

f()
# Error in eval(expr, envir, enclos) : object 'foo2' not found

It can be worked around by using environment=environment():

g <- function() {
  foo3 <- 4
  ggplot(mtcars, aes(x = wt + foo3, y = mpg),
         environment = environment()) +
    geom_point()
}

g()
# Works

I think that should be the default behavior. @hadley, is the current behavior a bug or a feature?

The problem is the definition of ggplot.data.frame in plot.r:

ggplot.data.frame <- function(data, mapping=aes(), ...,
  environment = globalenv())

Changing it to use parent.env() fixes the problem:

ggplot.data.frame <- function(data, mapping=aes(), ...,
  environment = parent.env())
@wch wch referenced this issue from a commit in wch/ggplot2
@wch wch Evaluate aes() in calling environment. Fixes #743 b6eb8f8
@hadley
Owner

It's a bug, but I don't think we can fix it now.

@hadley hadley closed this
@tomhopper

Hadley, is there a way to note the work-around in the documentation for aes()?

@tsibley tsibley referenced this issue from a commit in tsibley/ggplot2
@wch wch Evaluate aes() in calling environment. Fixes #743 a0f5ffe
@tonyfujs tonyfujs referenced this issue from a commit in thelayc/laycEnrollment
tonyfujs fixed bug: hadley/ggplot2#743 c5d5c14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.