我使用geom_tile
. 然后,我想在 x 轴下方添加轨道颜色。我从类似的主题答案(ggplot 在 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))