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
>
Is there a more elegant way to fix this problem?