Home > Back-end >  Plot List of Data Frames in R
Plot List of Data Frames in R

Time:11-16

I have data frames in a list that corresponds to several variables from a same survey. For example, the dataframe that corresponds to the first variable looks like:

Value = c(10, 12, 14, 11)
Quarter = c(1, 2, 3, 4)
dt = as.data.frame(cbind(Quarter, Value))
dt
Value Quarter
 10     1
 12     2
 14     3
 11     4

The subsequent follows the same pattern. The plot for a single element of the list was created using ggplot2:

ggplot(data = dt, aes(x=Quarter, y=Value))
geom_line()

Now, I need to create one plot like above for each element(variable) in my list and save them on my disk. Is it possible to do this using R?

Regards,

CodePudding user response:

Yes. The most direct way is a for loop:

for(i in seq_along(your_list)) {
  p = ggplot(data = your_list[[i]], aes(x=Quarter, y=Value))  
    geom_line()  
    labs(title = paste("Plot", names(your_list)[i])
  ggsave(
    paste0("plot_", i, ".png"),
    plot = p
  )
}

You can, of course, customize as much as you'd like.

  • Related