2011-12-09 58 views
2

重疊位置我有這樣R中一個數據幀:繪圖中的R

dat = data.frame(Sample = c(1,1,2,2,3), Start = c(100,300,150,200,160), Stop = c(180,320,190,220,170)) 

我想繪製它使得x軸是位置和y軸是樣本的數目在那個位置,每個樣品都有不同的顏色。因此,在上面的例子中,您將有一些高度爲1的位置,其中一些高度爲2,另一個區域的高度爲3.目標是找到存在大量樣本的區域以及該區域中有哪些樣本。

即是這樣的:

 & 
    --- 
********- --  ** 

,其中* =樣品1, - =樣品2和& =樣品3

回答

1

這個破解可能是你正在尋找的,但是我已經大大增加了數據幀的大小,以利用geom_histogram的堆棧優勢。

library(ggplot2) 
dat = data.frame(Sample = c(1,1,2,2,3), 
       Start = c(100,300,150,200,160), 
       Stop = c(180,320,190,220,170)) 

# Reformat the data for plotting with geom_histogram. 
dat2 = matrix(ncol=2, nrow=0, dimnames=list(NULL, c("Sample", "Position"))) 

for (i in seq(nrow(dat))) { 
    Position = seq(dat[i, "Start"], dat[i, "Stop"]) 
    Sample = rep(dat[i, "Sample"], length(Position)) 
    dat2 = rbind(dat2, cbind(Sample, Position)) 
} 

dat2 = as.data.frame(dat2) 
dat2$Sample = factor(dat2$Sample) 

plot_1 = ggplot(dat2, aes(x=Position, fill=Sample)) + 
     theme_bw() + 
     opts(panel.grid.minor=theme_blank(), panel.grid.major=theme_blank()) + 
     geom_hline(yintercept=seq(0, 20), colour="grey80", size=0.15) + 
     geom_hline(yintercept=3, linetype=2) + 
     geom_histogram(binwidth=1) + 
     ylim(c(0, 20)) + 
     ylab("Count") + 
     opts(axis.title.x=theme_text(size=11, vjust=0.5)) + 
     opts(axis.title.y=theme_text(size=11, angle=90)) + 
     opts(title="Segment Plot") 

png("plot_1.png", height=200, width=650) 
print(plot_1) 
dev.off() 

請注意,我已經重新格式化數據幀的方法是有點難看,而且不會很好地擴展(例如,如果你有百萬段和/或大的起始和終止位置)。

enter image description here

+0

謝謝。這看起來非常好。這是基因組數據,所以有很大的開始和停止位置,但也許我可以重新調整它,以100個間隔或類似的東西大塊。 – yoda230

2

我第一次嘗試:

dat$Sample = factor(dat$Sample) 
ggplot(aes(x = Start, y = Sample, xend = Stop, yend = Sample, color = Sample), data = dat) + 
    geom_segment(size = 2) + 
    geom_segment(aes(x = Start, y = 0, xend = Stop, yend = 0), size = 2, alpha = 0.2, color = "black") 

enter image description here

我在這裏結合了兩個分段幾何。一個繪製彩色豎條。這些顯示樣品已經被測量。第二個幾何圖形在下面顯示樣本密度的灰色欄中繪製。任何意見,以改善這個快速黑客?

+0

可能的工作,謝謝你,但我真的喜歡它,如果Y軸是在特定的區域,即在1號線,你可以有不止一個類型的樣品總數。這樣你就可以很容易地看到對於普通區域至少有3個樣本的截止點。 – yoda230