Drew
Drew

Reputation: 593

Creating a list of plots using a for loop

I'm having trouble with creating a list of plots using for loops, and I don't know why.

Here's the code that doesn't work (i.e. returns aplotfinal as an empty list)


aplotfinal <- list()
for(i in 1:length(Rlist)){
  a <- Rlist[[i]] %>%
    select(Frame_times, average)
  del <- 0.016667
  x.spec <- spectrum(a$average, log = "no", plot = FALSE)
  spx <- x.spec$freq/del
  spy <- 2*x.spec$spec
  aplotfinal[[i]] <- plot(spy~spx, main = names(Rlist)[i], xlab = "frequency", ylab = "spectral density", type = "l")
}

The plot function works, I just want to apply it for a list of dataframes that I have (i.e. Rlist). Thank you!

Upvotes: 2

Views: 1663

Answers (2)

slava-kohut
slava-kohut

Reputation: 4233

Here is an example you can use to tweak your code. Plots get saved to the plot_list variable and then to pdf residing at path/to/pdf. Note that you have to initiate a device first (in my case, pdf).

library(ggplot2)
library(dplyr)

df <- data.frame(country = c(rep('USA',20), rep('Canada',20), rep('Mexico',20)),
                 wave = c(1:20, 1:20, 1:20),
                 par = c(1:20 + 5*runif(20), 21:40 + 10*runif(20), 1:20 + 15*runif(20)))

countries <- unique(df$country)

plot_list <- list()
i <- 1

for (c in countries){
  pl <- ggplot(data = df %>% filter(country == c)) +
    geom_point(aes(wave, par), size = 3, color = 'red') +
    labs(title = as.character(c), x = 'wave', y = 'value') +
    theme_bw(base_size = 16)

  plot_list[[i]] <- pl
  i <- i + 1
}

pdf('path/to/pdf')
pdf.options(width = 9, height = 7)
for (i in 1:length(plot_list)){
  print(plot_list[[i]])
}
dev.off()

Upvotes: 2

StupidWolf
StupidWolf

Reputation: 46978

the base R plot() does not return an object, it just draws on the device. So you have to do a multiplot or save onto a pdf to have a record of the plots.

To store it in a list, I guess you need something like ggplot, for example:

library(ggplot2)
library(gridExtra)

Rlist = lapply(1:5,function(i){
data.frame(Frame_times = seq(0,1,length.out=100),average=runif(100))
})
names(Rlist) = letters[1:5]

aplotfinal <- lapply(1:length(Rlist),function(i){
  a <- Rlist[[i]] %>% select(Frame_times, average)
  del <- 0.016667
  x.spec <- spectrum(a$average, log = "no", plot = FALSE)
  spx <- x.spec$freq/del
  spy <- 2*x.spec$spec
  aplotfinal[[i]] <- qplot(y = spy,x=spx,geom="line") + 
  ggtitle(names(Rlist)[i]) + 
   xlab("frequency")+ylab("spectral density")
})

grid.arrange(grobs=aplotfinal,ncol=5)

enter image description here

Upvotes: 3

Related Questions