[R] Plotting patient drug timelines using ggplot2 (or some other means) -- Help!!!

Paul Miller pjmiller_57 at yahoo.com
Wed Mar 28 19:19:56 CEST 2012


Hello All,

Figured out how to get the gaps in the bars when a drug stops and the starts again (see below). Made the graph overlaid/superimposed/stacked and got the desired result. Not sure this is how an expert would do it. But it's simple and it works. 

Paul


setwd("N:/Regimen Coding/0906/Plots Test")
getwd()

connection <- textConnection("
1/1/1/Drug A/ Begin (A), Begin (B), End (B), End (A)/0.0000/21.000
1/1/1/Drug B/ Begin (A), Begin (B), End (B), End (A)/0.7143/18.000
1/2/1/Drug A/ Begin (A, B, C), End (A, B), End (C)/0.0000/20.000
1/2/1/Drug B/ Begin (A, B, C), End (A, B), End (C)/0.0000/20.000
1/2/1/Drug C/ Begin (A, B, C), End (A, B), End (C)/0.0000/36.000
2/1/1/Drug A/ Begin (A, B), End (A, B), Begin (C), End (C), Begin (D), End (D)/0.0000/7.429
2/1/1/Drug B/ Begin (A, B), End (A, B), Begin (C), End (C), Begin (D), End (D)/0.0000/7.429
2/1/1/Drug C/ Begin (A, B), End (A, B), Begin (C), End (C), Begin (D), End (D)/14.5714/21.857
2/1/1/Drug D/ Begin (A, B), End (A, B), Begin (C), End (C), Begin (D), End (D)/25.4286/231.286
2/2/1/Drug A/ Begin (A, B), End (A, B)/0.0000/35.286
2/2/1/Drug B/ Begin (A, B), End (A, B)/0.0000/35.286
3/1/1/Drug B/Begin (A, B, C), End (A, B, C), Begin (C), Begin (D), End (C, D)/0/17.0000
3/1/1/Drug A/Begin (A, B, C), End (A, B, C), Begin (C), Begin (D), End (C, D)/0/17.0000
3/1/1/Drug C/Begin (A, B, C), End (A, B, C), Begin (C), Begin (D), End (C, D)/0/17.0000
3/1/1/Drug D/Begin (A, B, C), End (A, B, C), Begin (C), Begin (D), End (C, D)/20/32.8571
3/1/2/Drug C/Begin (A, B, C), End (A, B, C), Begin (C), Begin (D), End (C, D)/18/32.8571
")

TestData <- data.frame(scan(connection, list(profile_key=0, line=0, instance=0, drug="", pattern="", start_drug=0, stop_drug=0), sep="/"))
closeAllConnections()

TestData

require(reshape)
TestData <- melt(TestData, measure.vars = c("start_drug", "stop_drug"))
TestData$drug <- factor(TestData$drug, levels = c("Drug D", "Drug C", "Drug B", "Drug A"))
TestData$key_line <- with(TestData,paste(profile_key, line, sep = ""))
TestData

require(ggplot2)

temp <- TestData
TempData <- split(TestData, TestData$key_line)

for(temp in TempData){

png(filename = paste("plot", unique(temp$key_line), ".png", sep = ""), width=600, height=300)

p <- ggplot(temp, aes(value, drug, fill = factor(instance))) + geom_line(size = 6) + xlab("\n Time (Weeks)") + ylab("") + theme_bw() +  
     opts(title = paste("Pattern = ", unique(temp$pattern), " \n (profile_key = ", unique(temp$profile_key), ", line = ", unique(temp$line), ") \n", sep = "")) + 
     opts(legend.position="none")  
print(p)
dev.off()
}



More information about the R-help mailing list