I would like to create plots of line segments by looping over different data-sets, with the values of the scale for linetype set manually. However, using the for loop, only the scale of the last plot in the loop is used for all the other plots, despite defining a separate scale for each plot.
The behavior appears in the following minimal example:
library(ggplot2)
DF <- list(
DF1 = data.frame(x=1:10, y=1:10, type=as.factor(c(rep(0,5),rep(1,5)))),
DF2 = data.frame(x=1:10, y=1:10, type=as.factor(sort(rep(1:5,2))))
)
linetype <- list(
linetype1 <- 4:5,
linetype2 <- 1:5
)
plotlist <- list()
for(i in 1:2){
plotlist[[i]] <- ggplot(DF[[i]], aes(x, y, linetype=type)) +
geom_line() +
scale_linetype_manual(values=linetype[[i]])
}
Then, when printing the plot
plotlist[[1]]
it shows the lines of the first plot with the linetype values of the second plot.
The plot I am after is:
which can be created using the same code outside the for loop:
i <- 1
plotlist[[i]] <- ggplot(DF[[i]], aes(x, y, linetype=type)) +
geom_line() +
scale_linetype_manual(values=linetype[[i]])
Where does this behavior come from? Is there any way around it? I'm at a loss here, thanks for your help!
Edit:
I can get the expected list using lapply:
plotlist <- lapply(1:2, function(i){
ggplot(DF[[i]], aes(x, y, linetype=type)) +
geom_line() +
scale_linetype_manual(values=linetype[[i]]
})
But I still do not understand why the expected behavior doesn't happen in the for loop. My guess is that the scale value is only evaluated when the graph is printed; and at that time, only the last scale is available in the environment. This is hardly a good explanation at all and I would like to know the details of this behavior.