2

我在 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

4

2 回答 2

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")

在此处输入图像描述

我在这里结合了两个段几何。一个绘制彩色垂直条。这些显示样品的测量位置。第二个几何图形在显示样本密度的下方绘制灰色条。有什么意见可以改进这个快速破解吗?

于 2011-12-09T13:29:56.187 回答
1

这个 hack 可能是您正在寻找的,但是我已经大大增加了数据框的大小,以便利用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()

请注意,我重新格式化数据框的方式有点难看,并且无法很好地扩展(例如,如果您有数百万个段和/或大的开始和停止位置)。

在此处输入图像描述

于 2011-12-09T21:22:50.433 回答