0

R studio (ggplot) question: I need to prepare a plot with age on X-axis with each subject represented with one dot per session (baseline and followup) with a line drawn between them (spaghetti plot). preferably sorting them by age at baseline.. can anyone help me?

I want to plot the lines horizontally along the x-axis (from Age at Timepoint 1 to AgeTp2), and the y-axis can represent some index based on a sorted list of individuals based on AgeTp1 (so just a pile of horizontal lines, really)

IMAGE OF DATASET

Community
  • 1
  • 1
  • can you give a small example of what your data looks like? and maybe add (a link to) an image of how you want the plot to appear? see also https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – MartijnVanAttekum Jun 06 '18 at 10:56
  • @MartijnVanAttekum okay I've edited the post to have a link to an image of the data at the bottom... to clarify, I basically have people that have been in at two time points.. I want the age they were at each time point to be represented on a graph by dots and a line connecting the dots of the same participant (between TP1 and 2).. the X axis needs to be Age.. so that each line can be seen horizontally.. been struggling for a couple of days to get this plot right and it's really stressing me – earl learman Jun 06 '18 at 14:03

1 Answers1

0

Here is a simple example that you can modify to suit your purposes...

df <- data.frame(ID=c("A","A","B","B","C","C"),
                 age=c(20,25,22,27,21,28))

library(dplyr)
library(ggplot2)

#sort by first age for each ID
df <- df %>% group_by(ID) %>% 
  mutate(index=min(age)) %>% 
  ungroup() %>% 
  mutate(index=rank(index))

ggplot(df,aes(x=age,y=index,colour=ID,group=ID))+
  geom_point(size=4)+
  geom_line(size=1)

enter image description here

Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32
  • 1
    thank you so much for the help, I managed to eventually use this as a format to edit my script from and eventually got the plot to show what I needed – earl learman Jun 12 '18 at 16:53