在 geom_tile() 中将组标签添加到 x 轴

Adding a Group Label to x-axis in geom_tile()

我想在 geom_tile() 的 x 轴上为变量添加一个总体分组标签。

这与我正在寻找的结果相似:

然而,我能想到的最好的方法(不使用 geom_text() 并在 x 轴变量上方手动添加第 1 组、第 2 组和第 3 组)就是这个,它只是创建一个新的包含两条信息的变量:

set.seed(1)
df <- expand.grid(group = c("Group 1", "Group 2", "Group 3"), 
                  xVar = c("A", "B"), 
                  yVar = c("x","y","z")) %>% 
  mutate(fillValue = factor(sample(c(0,1), 18, TRUE))) %>%
  mutate(group_and_xVar = paste(group, xVar, sep = "\n"))


ggplot(df, aes(x = group_and_xVar, y = yVar, fill = fillValue))+
  geom_tile(colour = "black") +
  scale_x_discrete(position = "top", expand = c(0,0))+
  scale_y_discrete(expand = c(0,0))+
  scale_fill_manual(values=c("#FF4933", "#72AF4A"))+
  labs(x = "", y = "", fill = "")+
  theme_bw()+
  theme(axis.text.x = element_text(angle = 0, vjust = .05),
        legend.position = "none")

这不是我想要的。我想让每个组只在图上出现一次,并且要对代码进行软编码(以适应将来可能添加的新数据或组)。我也尝试过使用 facet_grid/facet_wrap 但我没有成功。

同时调整单元格的高度使其看起来更像第一张图片会更好:)

受此启发的解决方案post

ggplot(df, aes(x = xVar, y = yVar, fill = fillValue)) +
    geom_tile(colour = "black") +
    scale_x_discrete(position = "top", expand = c(0,0)) +
    scale_y_discrete(expand = c(0,0)) +
    labs(x = "", y = "", fill = "") +
    facet_grid(~group) +
    coord_fixed(ratio=0.5) +
    theme(legend.position = "none",
          panel.spacing = unit(0, "lines"), 
          strip.background = element_blank(),
          strip.placement = "outside")