删除线覆盖在ggplot2中热图的特定单元格上

时间:2020-10-11 22:31:08

标签: r ggplot2

我想生成一个热图,其中的特定单元格具有重叠的删除线或该单元格上的其他一些简单图案。我希望获得与该问题(ggplot2 geom_tile diagonal line overlay)相同的结果,但是我无法重现此解决方案,因为在geom_segment()之后,我非常努力地遵循该解决方案的代码。

以下是数据框的一些示例数据:

GN  a   b
willy   -1.58215    -2.53036
wee 0.611129    0.485053
waffy   1.580719    0.857198

和热图代码:

library(tidyr)
library(ggplot2)
legend_title <- "log(z/w)"
pivot_longer(df, 2:3) %>%
    ggplot(aes(name, GN, fill=value)) +
    geom_tile(color = 'black') +
    scale_x_discrete(expand = c(0, 0)) +
    scale_y_discrete(expand = c(0, 0)) + 
    coord_equal() +
    theme(axis.title.x = element_blank(),
          axis.title.y = element_blank(),
          axis.ticks.x = element_blank(),
          axis.text.x = element_blank(),
          axis.text.y = element_text(color = 'black', face = 'bold')) +
    scale_fill_gradient2(legend_title, low = "blue", mid = "white", high = "red")

这将产生以下热图:

enter image description here

例如,我希望能够指定行waffy的左侧单元格和要打击的wee的右侧单元格。如果有设计选项可以更好,例如具有三个彩色对角线删除线。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

从原始图p开始。

library(tidyverse)

df <- tibble(
  GN = c("willy", "wee", "waffy"),
  a = c(-1.58215, 0.611129, 1.580719),
  b = c(-2.53036, 0.485053, 0.857198)
)


p <-
  ggplot(pivot_longer(df, 2:3), aes(name, GN, fill=value)) +
  geom_tile(color = 'black') +
  scale_x_discrete(expand = c(0, 0)) +
  scale_y_discrete(expand = c(0, 0)) + 
  coord_equal() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_text(color = 'black', face = 'bold')) +
  scale_fill_gradient2("log(z/w)", low = "blue", mid = "white", high = "red")

add_strikes进行绘图并向指定的单元格添加警示。

add_strikes <- function(p, cell, color, n_lines, thickness) {
  strike_df <- tibble(cell, color, n_lines, thickness)
  
  data <-
    ggplot_build(p)$data[[1]] %>%
    rownames_to_column("cell") %>%
    inner_join(uncount(strike_df, n_lines)) %>%
    group_by(cell) %>%
    mutate(
      x = pmax(xmin - (xmax - xmin) + row_number() * 2 * (xmax - xmin) / (n() + 1), xmin),
      y = pmax(ymax - row_number() * 2 * (ymax - ymin) / (n() + 1), ymin),
      xend = pmin(xmin + row_number() * 2 * (xmax - xmin) / (n() + 1), xmax),
      yend = pmin(ymax + (ymax - ymin) - row_number() * 2 * (ymax - ymin) / (n() + 1), ymax)
    )
  p + geom_segment(
    data = data, 
    aes(x, y, xend = xend, yend = yend, color = I(color), size = I(thickness)), 
    inherit.aes = FALSE,
    show.legend = FALSE
  )
}

指定希望罢工的外观。

add_strikes(
  p,
  cell = c("4", "5"),
  color = c("black", "#ebb734"),
  n_lines = c(3, 6),
  thickness = c(0.8, 0.2)
)

strikes