让geom_tile绘制正方形而不是矩形单元格

时间:2016-10-04 18:35:52

标签: r ggplot2 heatmap

我尝试使用heatmap' ggplot生成geom_tile图。我的数据行数多于列数。

  set.seed(1)
  df <- data.frame(val=rnorm(100),gene=rep(letters[1:20],5),cell=c(sapply(LETTERS[1:5],function(l) rep(l,20))))

运行:

library(ggplot2)
ggplot(df,aes(y=gene,x=cell,fill=val))+geom_tile(color="white")

生产: enter image description here

如何让heatmap单元格具有对称尺寸 - 正方形而不是矩形(高度=宽度)?不会扭曲图形的尺寸。

2 个答案:

答案 0 :(得分:10)

选项是添加coord_equal

  

默认值,ratio = 1,确保x轴上的一个单位是   与y轴上的一个单位相同的长度

ggplot(df, aes(y = gene, x = cell, fill = val)) +
  geom_tile(color = "white") +
  coord_equal()

enter image description here

答案 1 :(得分:3)

调整比例如下

set.seed(1)
df <- data.frame(val=rnorm(100),gene=rep(letters[1:20],5),
             cell=c(sapply(LETTERS[1:5],function(l) rep(l,20))))

library(ggplot2)
p <- ggplot(df,aes(y=gene,x=cell,fill=val))+geom_tile(color="white")
p <- p + coord_fixed(ratio = 0.7)
p

enter image description here