如何在 R 中创建一个在 y 轴上具有多级标签且只有一个 x 轴的 ggplot

How to create a ggplot in R that has multilevel labels on the y axis and only one x axis

我正在尝试在 R 中使用 ggplot 创建一个平铺图,在 Y 轴上有一个多级标签,并且只有一个 x 轴副本(例如,没有小平面)。期望的结果是这样的(想象一下瓷砖都在那里):

这是我目前的情况:

dat<- as.data.frame(cbind(Species = rep(c("a", "b", "c", "d", "e", "f", "g"),each = 3 ), 
                            threats = rep(c("1", "2", "3"), 7),
                            elev_grp = c(rep("Low", 9), rep("Mid", 9), rep("High", 3)), 
                            match = sample(1:3, size = 21, replace = T)))
dat$match.labs<- ifelse(dat$match == 1, "Both",
                        ifelse(dat$match == 2, "Neither", "One"))

ggplot(dat, aes(reorder(threats, match), Species, fill = match.labs))+
  geom_tile()+
  scale_fill_manual(values = c("#bd421f",
                               "#3fadaf",
                               "#ffb030"))

这给了我这个:

分面是不合适的,因为每个物种对于每个级别的“威胁”都有一个“匹配”值,并且在我的实际数据集中有几十个级别,这使得在“[=”的不同方面重复 x 轴23=]" 不切实际。 我也考虑过堆叠面,但无法弄清楚如何强制它们共享一个 x 轴,因此图中没有巨大的灰色区域...

如有任何帮助,我们将不胜感激。感谢您的宝贵时间!

您可以使用旧的“看起来不像刻面的刻面”技巧:

dat$elev_grp <- factor(dat$elev_grp, c("High", "Mid", "Low"))

ggplot(dat, aes(reorder(threats, match), Species, fill = match.labs))+
  geom_tile()+
  scale_fill_manual(values = c("#bd421f",
                               "#3fadaf",
                               "#ffb030")) +
  scale_y_discrete(drop = TRUE, expand = c(0, 0)) +
  facet_grid(elev_grp~., scales = "free", space = "free_y", switch = "y") +
  theme(strip.placement = "outside",
        panel.spacing = unit(0, "in"),
        strip.background.y = element_rect(fill = "white", color = "gray75"))