0
filtered_el
       Site Sample       Ca         P        Si       Mg     Sr       Fe       K       Al
1      Cave    s13 233483.7   6653.86  85458.49  6822.14 236.12 25002.51 9914.30 16847.06
2      Cave    s16 332549.4  24779.57  53839.66  6446.35 194.78 18383.66 7091.86 12103.81
3      Cave    s20 163451.6   4747.33  91317.05    < LOD 169.51 31466.12 7770.19 17776.28
4      Cave    s57 122560.3   5875.81 166865.47  8755.55  98.73 56692.94 7945.62 38946.29
5      Cave    s58 137458.0   6670.85 107911.59 11751.76  98.94 42549.91 5910.46 28895.68
6      Cave    s59 130964.9   4770.85 113553.15 11785.28  89.14 41131.11 5646.92 30437.12
7  Open_air   s105 145151.6   5607.23 151926.88     5124 315.54 28692.23 6454.71 20931.17
8  Open_air   s106 182335.1   4101.98 123296.37  7797.72 506.27 24175.82 6372.62 13815.11
9      Cave   s110 287127.3  31762.59  79184.64  7702.34 160.78 24570.66 7442.22 20492.54
10     Cave   s112 346025.4 121520.34  20302.76    < LOD 274.24  6798.99 1972.50  6099.50

I want to use the for loop to create a scatterplot for each variable and then arrange all plots together.

variables <- list('Ca', 'P', 'Si', 'Mg', 'Sr', 'Fe', 'K', 'Al')

for (i in variables){
  plot <-  ggplot(filtered_el, aes(x = Sample, y = filtered_el[ , i])) +
    geom_point(aes(color = Site), size =2, show.legend = FALSE) + 
    ylab(colnames(filtered_el[i])) + theme_bw() 
  print(plot)
}

I have tried using ggarrange but I am not sure how to use it inside the loop. I am open to any suggestion that can create a single image with all the plots.

Thanks

Valentina
  • 47
  • 4

1 Answers1

0

No loop required I think. First tidy your data

df %>%  
  mutate(across(Ca:Al, as.numeric)) %>% 
  pivot_longer(-c(Site, Sample))

# A tibble: 80 × 4
   Site  Sample name    value
   <chr> <chr>  <chr>   <dbl>
 1 Cave  s13    Ca    233484.
 2 Cave  s13    P       6654.
 3 Cave  s13    Si     85458.
 4 Cave  s13    Mg      6822.
 5 Cave  s13    Sr       236.
 6 Cave  s13    Fe     25003.
 7 Cave  s13    K       9914.
 8 Cave  s13    Al     16847.
 9 Cave  s16    Ca    332549.
10 Cave  s16    P      24780.
# … with 70 more rows
# ℹ Use `print(n = ...)` to see more rows

df %>%  
  mutate(across(Ca:Al, as.numeric)) %>% 
  pivot_longer(-c(Site, Sample)) %>% 
  ggplot() + 
  aes(x = Sample, y = value, col = name) + 
  geom_point() + 
  theme_bw() + 
  facet_wrap(vars(name))

enter image description here

In the same graph

df %>%  
  mutate(across(Ca:Al, as.numeric)) %>% 
  pivot_longer(-c(Site, Sample)) %>% 
  ggplot() + 
  aes(x = Sample, y = value, col = name) + 
  geom_point() + 
  theme_bw()

enter image description here

Chamkrai
  • 5,912
  • 1
  • 4
  • 14