Search code examples
rgraphtime-seriesstacked

how to make a graph from time series with numerical outcome and multiple treatment groups with colors coding for treatment


I need to make a graph from a time series which has in the first column a group variable with 2 levels, in the second another group variable (smaller group) with 22 levels, followed by 427 variables that code for days with a numeric outcome. Something like this:

VT  Medication V1 V2 V3 V4 V5 V6 V7 V8 
1           1   0  1  1  1  3  3  3  3 
1           2   0  1  1  1  2  1  1  1 
1           3   0  2  2  2  0  0  0  0 
1           4   1  1  4  5  6  4  0  0
2           1   1  1  3  3  3  3  3  3
2           2  etc
2           3
2           4

now I want to make two plots, one with from the VT group 1, and the second from VT group 2 with the numeric outcome on the y-axis and the days on the x-axis. I also want it to be a cumulative graph, distinguishing the contribution to the graph by color. I was thinking that it would look almost the same as doing stacked columns per day and putting them next to one another. however if possible i would want it to be smooth lines, like stacking lines of an interaction plot on top of another.

it would have to look like a graph with 22 layers with different colors coding for the 22 "medication" -groups.

I hope it's somewhat clear what i want from this description. Dirk


Solution

  • I usually convert my data to long format when I do plots like this. The ggplot2 package is a good choice to produce grouped plots of various kind.

    library(reshape)
    library(ggplot2)
    
    data <- read.table(header=TRUE, text=
    "VT  Medication V1 V2 V3 V4 V5 V6 V7 V8
    1           1   0  1  1  1  3  3  3  3
    1           2   0  1  1  1  2  1  1  1
    1           3   0  2  2  2  0  0  0  0
    1           4   1  1  4  5  6  4  0  0
    2           1   1  1  3  3  3  3  3  3")
    
    data <- melt(data, id.vars=c("VT","Medication"), variable_name="Day")
    data$VT <- as.factor(data$VT)
    data$Medication <- as.factor(data$Medication)
    data$Day <- as.numeric(data$Day)
    plot.data <- data[data$VT==1,]
    
    ggplot(plot.data, aes(,x=Day, y=value, colour=Medication)) +
      geom_line() +
      scale_colour_manual(values=c("red","blue","green","black"))
    

    enter image description here