Home > Mobile >  Using for loop to create multiple graphs with ggplot in R
Using for loop to create multiple graphs with ggplot in R

Time:02-13

I have data that looks similar to this:

Criteria         Person A      Person B     Person C      Person D
A                    10           15           12           11 
B                    50           55           40           37
C                    10           2             5           3 
D                    15           18           22           30 
E                    40           25           18           32
F                    12           35           10           12

I need to create a ggplot column graph for each of the criteria, but I want to use a for loop to make it more efficient (or any other strategy). One graph for the criteria A, one for the B, and so on. The desired output should be something like:

 ggplot(aes(x = person, y = n))   geom_col() #for the criteria A
 ggplot(aes(x = person, y = n))   geom_col() #for the criteria B
 ggplot(aes(x = person, y = n))   geom_col() #for the criteria C
(...)

where x is person A, B, C, and D, and n is the count (10, 15, 12...). The idea is to automatically create one graph for each of the criteria, without the need to manually create and adjust them using filter().

I have found a few options using facet_wrap but it is not exactly what I am looking for. Melt from reshape2 is not an option in this case too, as I want to create different graphs for each criteria.

Any suggestions?

CodePudding user response:

This makes a plot for each "Criteria"

library(tidyverse)

sample_df <- data.frame(
  stringsAsFactors = FALSE,
  check.names = FALSE,
          Criteria = c("A", "B", "C", "D", "E", "F"),
          `Person A` = c(10L, 50L, 10L, 15L, 40L, 12L),
          `Person B` = c(15L, 55L, 2L, 18L, 25L, 35L),
          `Person C` = c(12L, 40L, 5L, 22L, 18L, 10L),
          `Person D` = c(11L, 37L, 3L, 30L, 32L, 12L)
)

sample_df %>% 
    pivot_longer(cols = -Criteria,
                 names_to = "person",
                 names_prefix = "Person\\s",
                 values_to = "n") %>% 
    group_nest(Criteria) %>% 
    mutate(plot = map(data, ~ggplot(.x, aes(x = person, y = n))   geom_col())) %>% 
    pull(plot)
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

#> 
#> [[4]]

#> 
#> [[5]]

#> 
#> [[6]]

Created on 2022-02-11 by the reprex package (v2.0.1)

  • Related