Skip to content

Wrong evaluation environment for expressions in aes() #743

@wch

Description

@wch

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions