c - Plotting a segmented line with segments coloured based on a variable -


i'm trying draw plot (in r or gnuplot) x axis represent single sample , y axis segmented represented different portions of time. each line segment (or box) coloured depending on third variable (yes, no, or unknown)

sampleid   y1    y1(answer) y2        y2(answer)  y3      y3(answer)  sample 1   0-50  yes        51-60     no          61-85   yes sample 2   0-40  yes        41-60     no          61-86   no sample 3   0-45  unknown    46-69     yes         70-85   unknown 

where colour yes=green, no=red; , unknown=grey

can suggest solution? keep running in same problem, assigning colour based on third variable segment causes difficulty.

some other forum users seem running in same problem yet haven't seen easy workaround. suggest doing multiple plots , overlaying them. wonder if there way of rethinking problem, or reformatting data might help?

i'm not sure mean, best guess. (actually guess want flip x , y axes, should give start.)

data:

dd <- read.table(text=" sampleid   y1    y1(answer) y2        y2(answer)  y3      y3(answer)  sample_1   0-50  yes        51-60     no          61-85   yes sample_2   0-40  yes        41-60     no          61-86   no sample_3   0-45  unknown    46-69     yes         70-85   unknown", header=true) 

rearrange data long format:

library(reshape2) dd2 <- melt(dd,id.var=1) dd2 <- transform(dd2,                  var2=substr(as.character(variable),1,2),                  type=ifelse(grepl("\\.",as.character(variable)),"answer","range")) dd2 <- subset(dd2,select=-variable) dd3 <- dcast(dd2,sampleid+var2~type) library("stringr") dd3 <- transform(dd3,start=as.numeric(str_extract(range,"^[0-9]+")),                  end=as.numeric(str_extract(range,"[0-9]+$")),                  answer=factor(answer,levels=c("yes","no","unknown"))) 

picture:

library("ggplot2") ggplot(dd3)+     geom_segment(aes(x=start,xend=end,y=sampleid,yend=sampleid,colour=answer))+     scale_colour_manual(values=c("red","green","gray"))+     theme_bw() 

you last bit segments() well.

enter image description here


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -