1

I am trying to mass-produce plots with ggplot2. That is, because I do not want to copy and paste the same lines of code 35 times with some little edits.

To achieve this, I set up a for-loop that creates 35 different plots (by using data from a different variable each loop-cycle). The resulting plots are then stored in a list that already has the length of 35. Now, when I look at the different elements of said list, it shows the exact same plot in all elements of the list i tried so far. I know for sure, e.g., that in spot no. 1 of the list, there should be a different plot than there currently is.

I already creates some individual plots, e.g. like this:

p1 <- ggplot(predval, aes(x = theta, y = predval[,2])) +
    geom_line() +
    coord_cartesian(ylim = c(0,1)) +
    theme(axis.title.x = element_blank(),
          axis.title.y = element_blank(),
          legend.position = "none") +
    scale_y_continuous(labels = scales::percent)

(Note: I use column 2 of my dataset "predval" to plot the y-axis, because column one contains the "theta"-variable used for the x-axis. That is why I use column 2 for plot no. 1.)

This work just fine. To save myself from doing this 35 times, I tried to create a loop (see below). However, when I run the loop, the list is filled with 35 copies of the same plot. Why does it do that and how can I fix it?

plotlist[[1]] <- NA           # to create the plotlist
for (i in 1:35){
  plotlist[[i]] <- NA           # give it length 35
}

for (i in 1:35){              # 35 cycles for 35 plots
  plotlist[[i]] <- ggplot(predval, aes(x = theta, y = predval[,i+1])) +
                     geom_line() +
                     coord_cartesian(ylim = c(0,1)) +
                     theme(axis.title.x = element_blank(),
                           axis.title.y = element_blank(),
                           legend.position = "none") +
                     scale_y_continuous(labels = scales::percent)
}

I expect to receive a list full of different ggplots I can use for ggarrange's "plotlist"-argument.

## EDIT

qdread's advice worked perfectly well for me! Thank you very much! :D

Firefly05
  • 11
  • 2
  • 3
    This may be because `aes` is using non-standard evaluation. Try to replace your call to `aes` with `aes_string(x = 'theta', y = names(predval)[i+1])` – qdread Oct 21 '19 at 15:03

0 Answers0