Home > Software engineering >  Automating plot generation from multiple data frames in R
Automating plot generation from multiple data frames in R

Time:12-28

I'm fairly new to R.

I have four data frames that I want to get the same plots for.

df_wspr_40 df_wspr_60 df_wspr_80 df_wspr_160

I have a an additional one that list the numeric portion of the names.

> band 
[[1]]
[1] 40

[[2]]
[1] 60

[[3]]
[1] 80

[[4]]
[1] 160 

I'm trying to use a for loop to generate the plots I can't seem to figure out how to get the correct data frame to be used by ggplot. This is the closest I've gotten and still not a win.

for (x in band) {
  current.df = paste("df_wspr_", x, sep="")

  plot.subtitle = paste(x,"m Band from ",first_row," to ",last_row, sep = "")
    
  pl_dis_wspr <- ggplot(data=current.df, aes(y=avg_distance,x=date_120_min_interval))  
    geom_bar(stat="identity", width = 0.5, position = position_dodge (0.8))  
    geom_smooth(aes(group = 1), linewidth = 1, method = "loess", se = TRUE)  
    labs(x="Date & Time", y = "Distance Km", title = "120 minute Average Distance", subtitle = plot.subtitle)  
    theme(axis.text.x = element_blank())
  pl_dis_wspr
  
} 

I'm sure it's something simple that I'm missing, once I get this figured out I have several other plots that will be generated in the same loop using the same data frames.

Thanks

CodePudding user response:

This example code below may be helpful to you, which uses the mtcar dataset to generate plots automatically:

1. Create plots

plots <- mtcars %>%
  split(.$cyl) %>% 
  map(~ ggplot(., aes(x = mpg, 
                      y = wt))  
        geom_point()  
        labs(title = paste0("Automating plot generation"))
             ))

2. Define plot name (this example uses .png)

paths <- str_c(names(plots), ".png")

3. Using pwalk() to save each plot with the given name:

pwalk(list(paths, plots), ggsave)

Please play around and see how each part works, and then substitute your own data (they need to be merged as one dataset, and split by their id) to generate plots in one go. Hope it is helpful.

Update

If you'd like to make the title update automatically, please use this code to replace step 1 above:

plots <- mtcars %>%
  split(.$cyl) %>% 
  
  map(~ ggplot(., aes(x = mpg, y = wt))  
        geom_point()  
        
        labs(title = paste0("Automating plot generation:", .[[1, 2]])  # note
             ))

note: Here I call the value from the 1st row, 2nd column of each split dataset as part of the title. (It's also why I used paste0() before - just in case you need to update titles as well :))

  • Related