在ggplot中添加第二个geom_tile图层

时间:2017-03-07 05:50:07

标签: r ggplot2 heatmap

我在ggplot2中使用geom_tile有一个相对简单的热图。它只是一个连续数据的小矩阵,作为彩色框(df1),我想覆盖第二个逻辑geom_tile,它概述了TRUE值(df2)。可以这样做吗?我知道将两张热图加在一起似乎很难看,但这些都是小而简单的事情。

library(ggplot2)
n <- 4
df1 <- data.frame(x = rep(letters[1:n], times = n),
                  y = rep(1:n, each = n),
                  z = rnorm(n ^ 2)) 

df2 <- data.frame(x = rep(letters[1:n], times = n),
                  y = rep(1:n, each = n),
                  z = FALSE) 
df2$z[c(2,14)] <- TRUE

p1 <- ggplot(df1, aes(x = x, y = y))
p1 <- p1 + geom_tile(aes(fill = z), colour = "grey20")
p1 <- p1 + scale_fill_gradient2(low = "darkgreen", 
                                mid = "white", 
                                high = "darkred",
                                breaks = c(min(df1$z), max(df1$z)),
                                labels = c("Low", "High"))
p1
# overlay df2 to outline the TRUE boxes or dim the FALSE boxes with alpha?
# p1 <- p1 + geom_tile(data = df2, aes(fill = z), colour = "grey20")

2 个答案:

答案 0 :(得分:2)

我对@JasonWang采用了类似的方法,但我设置了边框的颜色和大小。

p1 + geom_tile(data=df2, aes(colour=factor(z, c(TRUE, FALSE)), size=factor(z, c(TRUE, FALSE))), alpha=0) + 
  scale_colour_manual("z", values=c("blue4", "white")) + 
  scale_size_manual("z", values=c(3, 0))

enter image description here

答案 1 :(得分:1)

只需将两个数据集合并为一个,这样就可以将第一个z值映射到填充,另一个映射到alpha:

ggplot(merge(df1, df2, by = c('x', 'y')), aes(x = x, y = y)) + 
    geom_tile(aes(fill = z.x, alpha = z.y), colour = "grey20") + 
    scale_fill_gradient2(low = "darkgreen", 
                         mid = "white", 
                         high = "darkred",
                         breaks = c(min(df1$z), max(df1$z)),
                         labels = c("Low", "High"))

plot with fill and alpha

您可以使用笔触颜色而不是Alpha,但笔划部分由geom_tile覆盖:

ggplot(merge(df1, df2, by = c('x', 'y')), aes(x = x, y = y)) + 
    geom_tile(aes(fill = z.x, colour = z.y), size = 2) + 
    scale_fill_gradient2(low = "darkgreen", 
                         mid = "white", 
                         high = "darkred",
                         breaks = c(min(df1$z), max(df1$z)),
                         labels = c("Low", "High")) + 
    scale_color_manual(values = c('#00000000', 'blue'))

outlined tiles

所以为了让它正确地绘图,你必须通过一层填充来填充它,然后用一层填充明确的轮廓:

ggplot(merge(df1, df2, by = c('x', 'y')), aes(x = x, y = y)) + 
    geom_raster(aes(fill = z.x)) +
    geom_tile(aes(colour = z.y), fill = '#00000000', size = 2) + 
    scale_fill_gradient2(low = "darkgreen", 
                         mid = "white", 
                         high = "darkred",
                         breaks = c(min(df1$z), max(df1$z)),
                         labels = c("Low", "High")) + 
    scale_color_manual(values = c('#00000000', 'blue'))

properly outlined raster