1

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?

1
  • What is your desired output? Save all the graphs in a list? Output them individually using ggsave? Plot them together in a single graph? Commented Feb 12, 2022 at 2:19

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.