1

I have this working dataset:

chr<-c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2)
iid<-c("sc1","sc1","sc2","sc2","sc3","sc3","sc4","sc4","sc5","sc5","sc1","sc2","sc3","sc4","sc5","sc6")
pos1<-c(2,34,7,56,12,67,11,34,2,67,23,56,12,11,12,43)
pos2<-c(23,54,12,98,54,79,22,67,43,98,23,54,65,32,54,57)
fam<-c(1,1,1,1,2,2,2,2,3,3,1,2,3,4,5,6)
data<-data.frame( iid,chr,pos1,pos2,fam)

My intention is to represent the sections between data$pos1 and data$pos2 of each IID. I use the following script to do it by chr:

plot_chr<-function(f,descn,chr){
  a<-f[f$chr==chr,]
  iids_num<-as.character(unique(a$iid))
  nsamps<-length(iids_num)
  xlimi<-c(0,max(a$pos2))
  plot(NULL,xlim=xlimi,ylim=c(0,nsamps),main=descn,xlab="Physical Position",ylab="Subject")
  for (id_no in 1:nsamps) {
    plot_dat<-a[which(a$iid==iids_num[id_no]),]
    if (length(plot_dat$iid) > 0) {
      for (roh_n in 1:length(plot_dat$iid)) {
        x<-c(plot_dat[roh_n,"pos1"],plot_dat[roh_n,"pos2"])
        y<-  c(id_no,id_no)
        lines(x,y,lw=2,lend=2,col="red")
      }
    }
  }
  return(a)
}

Here is the outcome:

windows()
plot_chr(data,"data",1)

enter image description here

However I want to modify and add a new variable. In that exact plot (chr=1) I would like to change the colors of the lines according to the factor data$fam. For example I would like a red line for iid=sc1 and sc2 (fam=1) a blue line for iid=sc3 and sc4 (fam=2) and green line for iid=sc5 (fam=3). Every time I try to modify the script I end up having errors.

1 Answer 1

2

You could define the color mapping using a named vector :

plot_chr<-function(f,descn,chr,colorsByFam){
  a<-f[f$chr==chr,]
  iids_num<-as.character(unique(a$iid))
  nsamps<-length(iids_num)
  xlimi<-c(0,max(a$pos2))
  plot(NULL,xlim=xlimi,ylim=c(0,nsamps),main=descn,xlab="Physical Position",ylab="Subject")
  for (id_no in 1:nsamps) {
    plot_dat<-a[which(a$iid==iids_num[id_no]),]
    if (length(plot_dat$iid) > 0) {
      for (roh_n in 1:length(plot_dat$iid)) {
        x<-c(plot_dat[roh_n,"pos1"],plot_dat[roh_n,"pos2"])
        y<-  c(id_no,id_no)
        # here we're getting the color corresponding to fam
        # note that as.character is necessary, otherwise it will use plot_dat$fam
        # as index of colorsByFam vector and not as a name
        color <- colorsByFam[as.character(plot_dat$fam)] 
        lines(x,y,lw=2,lend=2,col=color)
      }
    }
  }
  return(a)
}

colorsByFam <- c('1'='red','2'='blue','3'='green')
# or equivalently : 
# colorsByFam <- c('red','blue','green')
# names(colorsByFam) <- c(1,2,3)
plot_chr(data,"data",1,colorsByFam)

Result :

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.