0

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?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

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.