向数据表示函数

时间:2018-05-06 16:35:29

标签: r loops plot

我有这个工作数据集:

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)

我的目的是表示每个IID的数据$ pos1和data $ pos2之间的部分。我使用以下脚本来完成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)
}

结果如下:

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

enter image description here

但是我想修改并添加一个新变量。在那个确切的图(chr = 1)中,我想根据因子数据$ fam改变线条的颜色。例如,我想iid = sc1和sc2(fam = 1)的红线iid = sc3和sc4(fam = 2)的蓝线和iid = sc5(fam = 3)的绿线。每次我尝试修改脚本时,我都会遇到错误。

1 个答案:

答案 0 :(得分:2)

您可以使用命名向量定义颜色映射:

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)

结果:

enter image description here