ggplot2 geom_tile对角线覆盖

时间:2016-05-11 22:30:14

标签: r ggplot2

我正在寻找一种方法,使用geom_tile从一个单元格的左下角到右上角生成斜线斜杠。

输入是一个融合的数据框,有两个分类因子列,样本基因。我想使用类似geom_segment的内容,但我无法指定小数增量。有关实现这一目标的最佳方法的任何想法吗?

编辑:这是一个可重复的例子,我不能从我自己的数据中共享一个,因为它是受保护的患者信息。

df <- data_frame( gene     = c('TP53','TP53','MTOR','BRACA1'),
                  sample   = c('A','B','A','B'),
                  diagonal = c(FALSE,TRUE,TRUE,FALSE),
                  effect   = c('missense', 'nonsense', 'missense', 'silent') )

 ggplot(df, aes(sample, gene)) + geom_tile(aes(fill = effect))

example no diagonal

我正在寻找的东西:

example no diagonal

3 个答案:

答案 0 :(得分:1)

一种方法:

library(ggplot2)
df <- data.frame(
  x = rep(c(2, 5, 7, 9, 12), 2),
  y = rep(c(1, 2), each = 5),
  z = factor(1:10),
  w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2)
)
p <- ggplot(df, aes(x, y)) + geom_tile(aes(fill = z))
gb <- ggplot_build(p)
p + geom_segment(data=gb$data[[1]][1:2, ], 
                 aes(x=xmin, xend=xmax, y=ymin, yend=ymax), 
                 color="white")

enter image description here

在您的示例中,还可以依赖于因子级别的索引,如下所示:

library(ggplot2)
df <- data.frame( gene     = c('TP53','TP53','MTOR','BRACA1'),
                  sample   = c('A','B','A','B'),
                  diagonal = c(FALSE,TRUE,TRUE,FALSE),
                  effect   = c('missense', 'nonsense', 'missense', 'silent') )
df$cross <- c(F,T,T,F)
ggplot(df, aes(sample, gene)) + 
  geom_tile(aes(fill = effect)) + 
  geom_segment(data=transform(subset(df, !!cross), sample=as.numeric(sample), gene=as.numeric(gene)), 
               aes(x=sample-.49, xend=sample+.49, y=gene-.49, yend=gene+.49), 
               color="white", size=2)

(请注意,我使用的是data.frame而不是dplyr::data_frame,因此这两列都会成为因素。)

enter image description here

如果你想要一个传奇:

ggplot(df, aes(sample, gene)) + 
  geom_tile(aes(fill = effect)) + 
  geom_segment(data=transform(subset(df, !!cross), sample=as.numeric(sample), gene=as.numeric(gene)), 
               aes(x=sample-.49, xend=sample+.49, y=gene-.49, yend=gene+.49, color=cross), 
               size=2) + 
  scale_color_manual(values=c("TRUE"="white", "FALSE"=NA))

enter image description here

答案 1 :(得分:0)

您可以使用geom_abline。您可以调整interceptslope来获得您想要的内容。更多信息和示例here

ggplot(df, aes(sample, gene)) + 
  geom_tile(aes(fill = effect)) +
  geom_abline(intercept = 1, slope = 1, color="white", size=2)

enter image description here

答案 2 :(得分:0)

如果您实际上不需要特定的线条,而只是要突出显示,则可以简单地绘制点:

ggplot(df, aes(sample, gene)) + geom_tile(aes(fill = effect)) +
    geom_point(aes(sample, gene))

您可以将其做成 行:geom_point(aes(sample, gene), shape='/', size=10, color='white')

要使线条仅在某些图块上,只需将具有这些坐标的行仅传递到geom_pointgeom_point(data=filter(df, diagonal), aes(sample, gene))

或者,您也可以使用手动形状标尺对其进行修改:geom_point(aes(sample, gene, shape=diagonal)) + scale_shape_manual(values=c(' ', '/'))