This is not a good way to use ggplot. Try this way:
econ <- list(e1=economics2, e2=economics3, e3=economics4)
df <- cbind(cat=rep(names(econ),sapply(econ,nrow)),do.call(rbind,econ))
ggplot(df, aes(date,unemploy, color=cat)) + geom_line()
This puts your three versions of economics
into a single data.frame, in long format (all the data in 1 column, with a second column, cat
in this example, identifying the source). Once you've done that, ggplot
takes care of everything else. No loops.
The specific reason your loop failed, as pointed out in the comment, is that using aes(...)
stores the expression in the ggplot object, and that expression is evaluated when you call print(...)
. At that point i
is 3.
Note that this does not apply to the data=...
argument, so you could have done something like this:
b=ggplot()
for(i in 1:3){
b <- b + geom_line(aes(x=date,y=unemploy,colour=cat),
data=cbind(cat=as.character(i),econ[[i]]))
}
print(b)
But, this is still the wrong way to use ggplot.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…