Home > Net >  Spaghetti plot in R with different measurement times
Spaghetti plot in R with different measurement times

Time:06-07

This is my data set of repeated measures. score is the dependent variable, exposure is the main fixed factor in my mixed model.

structure(list(ID = c(50L, 50L, 60L, 60L, 60L, 60L, 70L, 70L), 
    Time = c(1L, 2L, 1L, 2L, 3L, 4L, 1L, 2L), Score = c(100L, 
    150L, 100L, 400L, -205L, -601L, 100L, 226L), exposure = c(1L, 
    1L, 1L, 1L, 1L, 1L, 2L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))

I'd like to do a spaghetti plot to illustrate each participants scores trends over time as the effect of the exposure levels they have. I want to produce plot that illustrate each participants score trend over time while they group according to their exposure group. The image I attached is an example of spaghetti plot without the grouping thing

So far this is my code:

ggplot ( DB, aes ( x= Time, Y= Score, group_by=exposure, color = ID) 
geom_points() 
geom_line() 
theme_bw()

I want something like this, but also divided by exposure levels

CodePudding user response:

Aside from some spelling mistakes, I think you might want to group by ID to make one line per participant, and then colour by exposure. If exposure doesn't have discrete levels, you might want to leave out the factor() bit in the code below.

library(ggplot2)

df <- structure(list(
  ID = c(50L, 50L, 60L, 60L, 60L, 60L, 70L, 70L), 
  Time = c(1L, 2L, 1L, 2L, 3L, 4L, 1L, 2L), 
  Score = c(100L, 150L, 100L, 400L, -205L, -601L, 100L, 226L), 
  exposure = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L)
), class = "data.frame", row.names = c(NA, -8L))

ggplot(df, aes(Time, Score, group = ID, color = factor(exposure)))  
  geom_point()  
  geom_line()  
  theme_bw()

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

  • Related