ggplot2 geom_tile对角线叠加 [英] ggplot2 geom_tile diagonal line overlay

查看:63
本文介绍了ggplot2 geom_tile对角线叠加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用 geom_tile 绘制的图中从单元格的左下角到右上角的斜线的方法.

I'm looking for a way to produce a diagonal slash from the bottom left the to top right corner of a cell within a plot made using geom_tile.

输入是具有两个分类因子列(样本基因)的融合数据框.我想使用 geom_segment 之类的东西,但是我无法指定小数增量.关于实现此目标的最佳方法的任何想法吗?

The input is a melted data frame with two categorical factor columns, sample and gene. I'd like to use something like geom_segment, but I'm not able to specify fractional increments. Any ideas on the best way to accomplish this?

这是一个可复制的示例,我不能从自己的数据中共享一个,因为它是受保护的患者信息.

edit: Here is a reproducible example, I can't share one from my own data, as it's protected patient information.

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

我正在寻找什么:

推荐答案

一种方法:

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

在您的示例中,还可以依赖于像这样的因子水平的索引:

In your example, could also rely on the indices of the factor levels like this:

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 ,这样两列都成为因素.)

(Note that I used data.frame and not dplyr::data_frame, so that both columns become factors.)

如果您想要图例:

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

这篇关于ggplot2 geom_tile对角线叠加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆