2

ggplot postpones the evaluation of aes until the graph is plotted. This is a known problem if ggplot is used in a local environment to define the graph, but later in the global environment to plot the graph. But even in the global environment this may cause a problem, if one uses temporary variables in aes which later change their values or do not exist anymore. Here is an example:

df <- data.frame( a  = 1:100,
                  b1 = sin(0.1*(1:100)),
                  b2 = cos(0.1*(1:100)) )

v <- c( "curve 1", "curve 2" )

plt <- ggplot( NULL ) +
  geom_line( data = df,
             size = 1.5,
             aes( x=a, y=b1, colour=v[1] ) ) +
  geom_line( data = df,
             size = 1.5,
             aes( x=a, y=b2, colour=v[2] ) ) +
  theme( legend.title = element_blank(),
         legend.text=element_text(size=30) )

So far plt shows the graph as expected. But if v is removed, the following error occurs:

> rm(v)
> plt
Error in eval(expr, envir, enclos) : object 'v' not found
> 

Capturing the (global) environment doesn't help in this case. The only solution I have found so far is the following:

library(ggplot2)

df <- data.frame( a  = 1:100,
                  b1 = sin(0.1*(1:100)),
                  b2 = cos(0.1*(1:100)) )

v <- c( "curve 1", "curve 2" )

aes1 <- aes( x=a, y=b1, colour=v[1] )
aes2 <- aes( x=a, y=b2, colour=v[2] )

aes1$colour <- v[1]
aes2$colour <- v[2]

plt <- ggplot( NULL ) +
  geom_line( data=df, size=1.5, aes1 ) +
  geom_line( data=df, size=1.5, aes2 ) +
  theme( legend.title = element_blank(),
         legend.text=element_text(size=30) )

Now almost everything can be removed:

> rm(v,aes1,aes2,df)
> plt
> 

enter image description here

Is there a more elegant way to fix this problem?

Community
  • 1
  • 1
mra68
  • 2,960
  • 1
  • 10
  • 17
  • 2
    Aesthetics are supposed to be maps from the variables in your data set to features of the plot. Just put the values of v in your data set. I can't think of a situation where you would *have* to do this the way you are trying to do it. The right way to do your example isn't with two geom_lines. You should rbind two copies of your data together and add a column for v and one call to geom_line with a group or colour aesthetic pointing to the v column. – Matthew Plourde Nov 24 '15 at 18:36

0 Answers0