使用 geom_tile 在 x 轴下方添加轨道颜色

Adding the track colors below x-axis using geom_tile

我使用 geom_tile 绘制了一个矩阵。然后,我想在 x 轴下方添加轨道颜色。我 运行 来自类似主题答案 () 的以下代码,但它显示错误“向连续刻度提供离散值”。

sp <- c("sp1","sp1","sp1","sp2","sp2","sp2","sp3","sp3","sp3","sp4","sp4","sp4","sp5","sp5","sp5")
 category <- c("a","b","c","a","b","c","a","b","c","a","b","c","a","b","c")
 count <- c(1,2,1,1,4,2,3,1,3,1,4,5,2,5,1)
 habitat <- c("A","A","A","B","B","B","C","C","C","A","A","A","B","B","B")
 d <- data.frame(cbind(sp, category, count, habitat))

 dm <- d %>%
    select(sp, category, count)%>%
    tidyr::pivot_wider(names_from = "sp", values_from = "count")%>%  
    replace(is.na(.),0)
 dm <- as.matrix(dm[, -1]) # -1 to omit categories from matrix
 

 clust <- hclust(dist(t(dm)), method = "single")

 dmc <- data.frame(x = factor(d$sp), colour = factor(d$habitat))
 
 my_fill <- scale_fill_gradient(low="grey90", high="red",  
                                breaks=c(0,5,10,15,20, 25, 30), 
                                rescale=function(x, ...) scales::rescale(x, from=c(0, 30)),
                                limits=c(0,30))
 

 ggplot(d, aes(category, sp))+
    geom_tile(aes(fill = as.numeric(count)))+
    my_fill +
    scale_y_discrete(limits = colnames(dm)[clust$order])+
    geom_tile(data=dmc, aes(x = x, y = 1, fill = colour))

这是一种可能的解决方案:

library(tidyverse)
library(ggpubr)

sp <- c("sp1","sp1","sp1","sp2","sp2","sp2","sp3","sp3","sp3","sp4","sp4","sp4","sp5","sp5","sp5")
category <- c("a","b","c","a","b","c","a","b","c","a","b","c","a","b","c")
count <- c(1,2,1,1,4,2,3,1,3,1,4,5,2,5,1)
habitat <- c("A","A","A","B","B","B","C","C","C","D","D","D","E","E","E")
d <- data.frame(cbind(sp, category, count, habitat))

dm <- d %>%
  select(sp, category, count)%>%
  tidyr::pivot_wider(names_from = "sp", values_from = "count")%>%  #clusterで並び替え
  replace(is.na(.),0)
dm <- as.matrix(dm[, -1]) # -1 to omit categories from matrix
clust <- hclust(dist(t(dm)), method = "single")

dmc <- data.frame(x = factor(d$sp), colour = factor(d$sp))

my_fill <- scale_fill_gradient(low="grey90", high="red",  
                               breaks=c(0,5,10,15,20, 25, 30), 
                               rescale=function(x, ...) scales::rescale(x, from=c(0, 30)),
                               limits=c(0,30))

plot1 <- ggplot(d, aes(category, sp))+
  geom_tile(aes(fill = as.numeric(count)))+
  my_fill +
  scale_y_discrete(limits = colnames(dm)[clust$order]) +
  theme(legend.position = "right")

plot2 <- ggplot(dmc) +
  geom_tile(aes(x = 1, y = x, fill = colour)) +
  theme_void() +
  scale_fill_manual(values = viridis::viridis(5)) +
  theme(legend.position = "none")

ggarrange(plot2, plot1, nrow = 1, widths = c(0.25, 10), align = "hv")