Home > OS >  How can you make a loop so that you are creating this same graph over and over but for a different v
How can you make a loop so that you are creating this same graph over and over but for a different v

Time:12-11

This is the coding that I have right now that creates the graph that I want. This is only for well 'aa1' though, and I want to learn how to make a loop so that I can make this graph for all of my wells. Any ideas?

longer_raindata %>% 
  select(well, metal, level, smpl_mth) %>% 
  filter(well == 'aa1') %>% 
  ggplot(aes(metal, level, fill = smpl_mth)) 
  scale_fill_manual(values = c('plum', 'lightsteelblue', 'darkolivegreen', 'indianred')) 
  geom_col(position = "dodge") 
  labs(title = 'Metals in Well AA1',
       x = 'Metals',
       y = 'µg/l')

CodePudding user response:

One option to achieve your desired result would be to put your code into a plotting function which takes one argument .well and adjust your filter statement to filter your data for that .well.

Then you could use e.g. lapply to loop over the unique wells in your dataset to get a list of plots for each well.

Using some fake example data:

library(ggplot2)
library(dplyr)

longer_raindata <- data.frame(
  metal = LETTERS[1:3],
  level = 1:6,
  well = rep(c("aa1", "aa2"), each = 6),
  smpl_mth = rep(letters[1:2], each = 3)
)

plot_fun <- function(.well) {
  longer_raindata %>% 
    select(well, metal, level, smpl_mth) %>% 
    filter(well == .well) %>% 
    ggplot(aes(metal, level, fill = smpl_mth)) 
    scale_fill_manual(values = c('plum', 'lightsteelblue', 'darkolivegreen', 'indianred')) 
    geom_col(position = "dodge") 
    labs(title = paste0('Metals in Well ', toupper(.well)),
         x = 'Metals',
         y = 'µg/l')  
}

lapply(unique(longer_raindata$well), plot_fun)
#> [[1]]

#> 
#> [[2]]

  • Related