Nuhash
Nuhash

Reputation: 21

for loop using ggplot for longitudinal data

I am trying to visualize my longtudinal data by graphs using ggplot through for loop.

for(i in colnames(dat_longC)[c(3,5:10,14,17:19,30:39)]){
print(ggplot(dat_longC, aes(x = exam, y = i, group = zz_nr))+ geom_point()+  
  geom_line() + xlab("Examination") + ylab(i))}
}

when I use the ggplot command in a for loop, I only get a line extending between examination times. If I use the same command on a single variable, it works and gives me trajectory graphs. What do you think could be the problem?

Upvotes: 2

Views: 51

Answers (2)

Nuhash
Nuhash

Reputation: 21

for(i in colnames(dat_longC)[c(3,5:10,14,17:19,30:39)]){
print(ggplot(dat_longC, aes_string(x = "exam" , y = i, group = "zz_nr"))+ geom_point()+  
  geom_line() + xlab("Examination") + ylab(i))}
}

Thank you very much for your reply! I just used aes_string and added quote to the variable names and it worked out.

Upvotes: 0

AndS.
AndS.

Reputation: 8110

Your problem is that you are using i to indicate the column. That is just an index, so it does not know what you are actually trying to plot. you really want colnames(dat_longC)[i]. Unfortunately, that will still not work because you are using a string as a variable name, which does not work for ggplot2. Instead, you will likely need !!sym(colnames(dat_longC)[i]). I can't really test without your data, but here is some example code to help guide you.

library(tidyverse)


map(colnames(mtcars)[2:4],
    \(x) ggplot(mtcars, aes(!!sym(x), mpg))+
      geom_point()+
      ggtitle(x))
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

Upvotes: 1

Related Questions