首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用ggplot2绘制重叠范围

如何用ggplot2绘制重叠范围
EN

Stack Overflow用户
提问于 2014-02-02 03:36:33
回答 1查看 1.6K关注 0票数 8

我正试着把我的头放在ggplot2上。特别是,我试图找出是否有一种更好(更优雅、更简单)的方法来创建Bioconductor IRanges包中的情节(发现这里,第12页上的图,第11页上的代码)。

在小插曲中,情节由以下代码生成:

代码语言:javascript
复制
plotRanges <- function(x, xlim = x, main = deparse(substitute(x)),
+ col = "black", sep = 0.5, ...) +{
+ height <- 1
+   if (is(xlim, "Ranges"))
+     xlim <- c(min(start(xlim)), max(end(xlim)))
+   bins <- disjointBins(IRanges(start(x), end(x) + 1))
+ plot.new()
+   plot.window(xlim, c(0, max(bins)*(height + sep)))
+   ybottom <- bins * (sep + height) - height
+   rect(start(x)-0.5, ybottom, end(x)+0.5, ybottom + height, col = col, ...)
+   title(main)
+ axis(1) +}

ir <- IRanges(c(1, 8, 14, 15, 19, 34, 40),
+   width = c(12, 6, 6, 15, 6, 2, 7))

plotRanges(ir)

事实上,堆叠的条形是通过绘制矩形来创建的,并且必须计算每个矩形的角点、高度和宽度,这让我觉得不是很优雅,ggplot2有一种更优雅的方法吗?我知道“优雅”并不是一个非常精确的描述,但我希望你能理解我的意思(如果不是,我会努力解释得更好)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-02 04:02:49

下面是一种使用ggplot2生成类似图的方法。我使用IRanges的示例数据。

代码语言:javascript
复制
library(IRanges)   

# example data
ir <- IRanges(c(1, 8, 14, 15, 19, 34, 40),
              width = c(12, 6, 6, 15, 6, 2, 7))
# IRanges of length 7
#     start end width
# [1]     1  12    12
# [2]     8  13     6
# [3]    14  19     6
# [4]    15  29    15
# [5]    19  24     6
# [6]    34  35     2
# [7]    40  46     7    

bins <- disjointBins(IRanges(start(ir), end(ir) + 1))
# [1] 1 2 1 2 3 1 1

dat <- cbind(as.data.frame(ir), bin = bins)

library(ggplot2)
ggplot(dat) + 
         geom_rect(aes(xmin = start, xmax = end,
                       ymin = bin, ymax = bin + 0.9)) +
  theme_bw()

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21506724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档