rggplot2linelong-format-data

Multiple line plots in one graph from long format


I have 100 individuals with each 3 points of a variable (after 0,6, and 12 months). I sorted them by variable in ascending order at Time = 0 and used the vector "c" for this.

    PatID pDC_of_lymphocytes_percentage Time c
2   001-502                         0.000    0 1
3   001-502                         0.051    6 1
1   001-502                         0.880   12 1
19  001-518                         0.000    0 2
20  001-518                         0.250    6 2
21  001-518                         0.210   12 2
87  021-503                         0.000    0 3
86  021-503                         0.350    6 3
85  021-503                         1.510   12 3
104 025-501                         0.000    0 4
103 025-501                         0.030    6 4
105 025-501                         0.000   12 4

Now I try to plot line plots for each of them, but the line plots should be:

I have tried with the pull function, but it only plots me one line in each graph, since only 1 ID is pulled at a time.

pdf(paste("pDCoflymphocytespercentage.pdf",sep = ""), width = 15)
l_ply(pDC.frame.plot %>% distinct(PatID) %>% pull(), function(patID) {
  patDF <- pDC.frame.plot %>% filter(PatID == patID)
  patDF$Time <- as.numeric(patDF$Time)
  
  print(
    ggplot(patDF, aes(x=Time)) +  
      
      geom_line(aes(y=pDC_of_lymphocytes_percentage, linetype="solid", group=1),colour = "steelblue",size=2,name="") +
      scale_linetype(name="") +
      

      )
  )
  
}, .progress = "text")
dev.off()

any solution how I can get multiple line plots in one graph, with one for each PatID at Time 0,6,12?

Thanks in advance.


Solution

  • Is this what you are looking for?

    library(ggplot2)
    df<- tibble::tribble(
      ~PatID, ~pDC_of_lymphocytes_percentage, ~Time,
      "001-502", 0.000, 0,
      "001-502", 0.051, 6,
      "001-502", 0.880, 12,
      "001-518", 0.000, 0,
      "001-518", 0.250, 6,
      "001-518", 0.210, 12,
      "021-503", 0.000, 0,
      "021-503", 0.350, 6,
      "021-503", 1.510, 12,
      "025-501", 0.000, 0,
      "025-501", 0.030, 6,
      "025-501", 0.000, 12
    )
    
    df |> 
      ggplot(aes(x = Time, y = pDC_of_lymphocytes_percentage)) +
      geom_line() +
      facet_wrap(~PatID)
    

    Created on 2022-10-26 with reprex v2.0.2