R - 将文件中的间隔绘制为2D矩阵

时间:2014-09-09 12:02:50

标签: r graph

在我的问题中,有一个较大区域的子区域可以归类为正面或负面。我有几个不同分类的文件,格式如下:

开始|结束 10 | 20个
60 | 120个
178 | 220

它们是有序的,它们只有正的子区域,其余的都是负的。

我想在R中的2D图形中表示这些数据,但我不知道应该使用哪种类型的图形。它是这样的:

http://i.imgur.com/VaSvEKr.jpg

1 个答案:

答案 0 :(得分:0)

这种图表被称为“甘特图”,这是在基础R中绘制它的可能方法:

# input example
DF <- 
read.csv(text=
'"file","start","end"
"file1",10,20
"file1",60,120
"file1",178,220
"file2",10,20
"file2",25,100
"file2",130,140
"file2",190,210
"file3",0,50
"file3",55,400',stringsAsFactors=F)


minval <- min(DF$start) # or different if you know the limits
maxval <- max(DF$end)   # or different if you know the limits

files <- rev(unique(DF$file))
nfiles <- length(files)

# empty plot to make space for everything
filehigh <- 1.0
plot(c(minval,maxval),c(filehigh/2,nfiles+filehigh/2),type='n', xlab='Time',ylab=NA,yaxt='n' )

# add y labels
axis(side=2,at=1:nfiles,labels=files,las=1)

# plot the rectangles
negcolor <- 'red'
poscolor <- 'green'

for(i in 1:nfiles){
   file <- files[i]
   subDF <- DF[DF$file == file,]
   lastend <- minval
   for(r in 1:nrow(subDF)){
     yTop <- i+(filehigh/2)
     yBottom <- i-(filehigh/2)
     start <- subDF[r,'start']
     end <- subDF[r,'end']

     if(start > lastend){
       rect(lastend,yBottom,start,yTop,col=negcolor )
     }
     rect(start,yBottom,end,yTop,col=poscolor)
     lastend <- end
   }
   if(lastend < maxval){
     rect(lastend,yBottom,maxval,yTop,col=negcolor )
   }
}

结果:

enter image description here