1

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.

Plot 1 created within the for loop: it uses the scale linetype2.

The plot I am after is:

Plot 1 as I would like to appear: using the scale linetype1.

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.

wiwh
  • 71
  • 1
  • 5
  • I think you are right, the scale value is added when printing. If you `print` your plots in the for loop will work: `for(i in 1:2){ plotlist[[i]] <- print(ggplot(DF[[i]], aes(x, y, linetype=type)) + geom_line() + scale_linetype_manual(values=linetype[[i]])) }` – S Rivero Jul 20 '17 at 14:22
  • Possible duplicate of [Storing ggplot objects in a list from within loop in R](https://stackoverflow.com/questions/31993704/storing-ggplot-objects-in-a-list-from-within-loop-in-r) – F. Privé Jul 20 '17 at 20:00

0 Answers0