Ggplot2: adding lines to the loop and saving color mappings

When I execute the following two parts of the code, I suddenly get different results. I need to add lines in a loop, as in EX2, but all lines have the same color. Why is this?

EX1

economics2 <- economics
economics2$unemploy <- economics$unemploy + 1000
economics3 <- economics
economics3$unemploy <- economics$unemploy + 2000
economics4 <- economics
economics4$unemploy <- economics$unemploy + 3000
b <- ggplot() +
 geom_line(aes(x = date, y = unemploy, colour = as.character(1)), data=economics2) +
 geom_line(aes(x = date, y = unemploy, colour = as.character(2)), data=economics3) +
 geom_line(aes(x = date, y = unemploy, colour = as.character(3)), data=economics4)
print(b)

EX1

EX2

#economics2, economics3, economics4 are reused from EX1.
b <- ggplot()
econ <- list(economics2, economics3, economics4)
for(i in 1:3){
  b <- b + geom_line(aes(x = date, y = unemploy, colour = as.character(i)), data=econ[[i]])
}
print(b)

EX2

+1
source share
1 answer

This is not a good way to use ggplot. Try as follows:

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 economicsin a single data.frame file in a long format (all the data is in 1 column with the second column, catin this example, identifying the source). As soon as you do, ggplottake care of the rest. No cycles.

, , , aes(...) ggplot, print(...). i 3.

, data=..., - :

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)

- ggplot.

+3

All Articles