1

I'm trying to create a loop in ggplot as follows:

LEDnum = c(1,2,3,4,5)

for (i in 1:length(LEDnum))
{
ggplot(LEDref,aes(x=sample1))+
  geom_line(aes(y=assign(paste("LEDrefLED",LEDnum[i],sep="")))) +
  ggtitle(paste("LED ref + LED ",LEDnum[i],sep=""))
  }

I have already existing objects (numeric lists) named LEDrefLED1,LEDrefLED2, etc. However, when I run this code it doesn't recognise the geom_line data as being my existing variable. I assume this is because paste() creates a character string but as I am new to R I don't know how to make it recognise it as the preexisting object.

  • I suggest checking `help(assign)`. It does not `get` the variable it `assign`s a variable to a name. To get a variable you would need to use `get` og `mget` for multiple variables simultaniously. More likely what you would want is to store your data in a `list` and reference the `list` with `i`. Try checking [this question](https://stackoverflow.com/q/26034177/10782538) and the first answer. Or search the forum for `[ggplot][for-loop]`. [This question](https://stackoverflow.com/questions/57108021/repeat-loop-100-times-adding-regression-lines-to-same-plot-for-each-iteration) might help too. – Oliver Oct 29 '19 at 14:08

1 Answers1

1

you can use aes_string, I do not have your dataset so I simulated the values for LEDrefLED1. Also if the dataset is not too big, store the plots inside a list

library(gridExtra)
library(reshape2)

LEDref = data.frame(matrix(rnorm(100),20,5))
colnames(LEDref) = paste("LEDrefLED",1:5,sep="")
LEDref$sample1 = 1:20

LEDnum = c(1,2,3,4,5)
plots = vector("list",5)
for (i in 1:length(LEDnum))
{
plots[[i]] = ggplot(LEDref ,aes(x=sample1))+
  geom_line(aes_string(y=paste("LEDrefLED",LEDnum[i],sep=""))) +
  ggtitle(paste("LED ref + LED ",LEDnum[i],sep=""))
  }
do.call(grid.arrange,plots)

Most of the time, maybe there's a better way to organize your data. So you can always pivot the data frame you had, and do a facet grid like below, that way you avoid the string and looping..

dat=melt(LEDref,id.vars="sample1")
colnames(dat)[2:3] = c("LEDnum","value")
ggplot(dat,aes(x=sample1,y=value))+ 
geom_line()+
facet_wrap(~LEDnum)
StupidWolf
  • 45,075
  • 17
  • 40
  • 72