onhalu
onhalu

Reputation: 745

Loop with two variables in ggplot 2

I have this dataframe

   DF
   Person      Day    Activity       Count
   <chr>      <chr>   <chr>          <dbl>
 1 Per. 1      Mon    Eat              2
 2 Per. 1      Thu    Sleep            1
 3 Per. 1      Sat    Work             6
 4 Per. 2      Mon    Eat              2
 5 Per. 2      Thu    Sleep            3
 6 Per. 2      Sat    Work             2
 7 Per. 3      Mon    Eat              4
 8 Per. 3      Thu    Sleep            4
 9 Per. 3      Sat    Work             3

I would like to plot a bar plot with Activity looped over Person and Day to get 9 plots. (Person 1 - Mon, Person 1 - Thu, Person 1 - Sat, Person 2 - Mon etc.)

Firstly, I have two lists with unique values

Person <- unique(DF$Person)
Day <- unique(DF$Day)

Secondly, loop

 for (i in seq_along(Person[i] )) { 
        for (j in seq_along(Day[j] )) {
  plot <-  ggplot(subset(DF, DF$Person==Person[i]),DF$Day==Day[j]),
                    aes(Activity, Count)) }}

But this doesn't work. Is there a solution?

Upvotes: 0

Views: 328

Answers (1)

stefan
stefan

Reputation: 125547

Try this. There are several issues with your code, starting with the lacking geom, some bugs in your subsetting command, ...

The following code will loop over your two vars and put the single plots inside a list:

library(ggplot2)

Person <- unique(DF$Person)
Day <- unique(DF$Day)

plots <- list()
for (i in Person) { 
  for (j in Day) {
    plot <- ggplot(subset(DF, Person == i & Day == j), aes(Activity, Count)) + 
      geom_col() +
      labs(title = paste0("Person: ", i, " Day: ", j))
    plots <- c(plots, list(plot))
  }
}
plots[[1]]

DATA

DF <- read.table(text = "  Person      Day    Activity       Count
     1 'Per. 1'      Mon    Eat              2
     2 'Per. 1'      Thu    Sleep            1
     3 'Per. 1'      Sat    Work             6
     4 'Per. 2'      Mon    Eat              2
     5 'Per. 2'      Thu    Sleep            3
     6 'Per. 2'      Sat    Work             2
     7 'Per. 3'      Mon    Eat              4
     8 'Per. 3'      Thu    Sleep            4
     9 'Per. 3'      Sat    Work             3", header = TRUE)

Upvotes: 1

Related Questions