0

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')
Phil
  • 7,287
  • 3
  • 36
  • 66
Madalyn
  • 15
  • 3
  • Welcome to SO! Would you mind providing [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. To post your data type `dput(NAME_OF_DATASET)` into the console and copy & paste the output starting with `structure(....` into your post. If your dataset has a lot of observations you could do e.g. `dput(head(NAME_OF_DATASET, 10))` for the first 10 rows of data. – stefan Dec 10 '21 at 20:54

1 Answers1

0

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]]

stefan
  • 90,330
  • 6
  • 25
  • 51