Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plot List of Data Frames in R

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Regards,

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading