I have a sample dataset with the columns: PATIENTID (IDs of patients), VISITNUMBER (their number of visits to the hospital), TIME (time in years since first visit), HEALTH (their health status). I am trying to plot HEALTH over time.
This is my code in R:
# data structure
PATIENTID <- c(126, 126, 126, 255, 255, 389, 389, 389, 389, 389, 470, 470, 470)
VISITNUMBER <- c(1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3)
TIME<- c(0, 4, 6, 0, 3, 0, 1, 2, 3, 4, 0, 1, 2)
HEALTH <- c(0.333, 0.452, 0.468, 0.571, 0.522, 0.444, 0.452, 0.431, 0.510, 0.532, 0.214, 0.333, 0.400)
mydata <- data.frame(PATIENTID, VISITNUMBER, TIME, HEALTH)
# converting patient ID and visit number to factor
mydata$PATIENTID <- factor(mydata$PATIENTID)
mydata$VISITNUMBER <- factor(mydata$VISITNUMBER)
# creating a spagetti plot of health over time
sp_HEALTH <- ggplot(data = mydata, aes(TIME, HEALTH, group=PATIENTID))
sp_HEALTH +
geom_line() +
stat_smooth(aes(group=1), method = "lm", se = FALSE) +
stat_summary(aes(group=1), geom = "point", fun.y = mean,
shape = 17, size = 3, col = "red")
This is my plot that's generated as a result of this code:
My issue is that I am trying to figure out a way to connect the mean points (shown in red in the above link) using a blue line that goes from point to point but I get this straight regression type of line. I want it to be like how a regular line plot connects points using lines (please click link below). How do I insert a line that connects the mean points?
Thank you!
question from:
https://stackoverflow.com/questions/66057114/connecting-mean-points-of-a-line-plot-in-ggplot2