Wrong evaluation environment for expressions in aes() #743

Closed
wch opened this Issue Dec 20, 2012 · 2 comments

Comments

Projects
None yet
3 participants
@wch
Collaborator

wch commented Dec 20, 2012

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())
@hadley

This comment has been minimized.

Show comment
Hide comment
@hadley

hadley Feb 24, 2014

Member

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

Member

hadley commented Feb 24, 2014

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

@hadley hadley closed this Feb 24, 2014

@tomhopper

This comment has been minimized.

Show comment
Hide comment
@tomhopper

tomhopper Feb 25, 2014

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

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

tsibley added a commit to tsibley/ggplot2 that referenced this issue Jul 1, 2014

tonyfujs pushed a commit to thelayc/laycEnrollment that referenced this issue Mar 15, 2015

@lock lock bot locked as resolved and limited conversation to collaborators Jun 20, 2018

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.