如何解决使用 geom_tile 在 x 轴下方添加轨道颜色
我使用 geom_tile
绘制了一个矩阵。然后,我想在 x 轴下方添加轨道颜色。我从类似的主题答案 (ggplot Adding Tracking Colors Below X-Axis) 中运行了以下代码,但它显示错误“离散值提供给连续比例”。
sp <- c("sp1","sp1","sp2","sp3","sp4","sp5","sp5")
category <- c("a","b","c","a","c")
count <- c(1,2,1,4,3,5,1)
habitat <- c("A","A","B","C","B")
d <- data.frame(cbind(sp,category,count,habitat))
dm <- d %>%
select(sp,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,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","sp2","sp3","sp4","sp5","sp5")
category <- c("a","b","c","a","c")
count <- c(1,2,1,4,3,5,1)
habitat <- c("A","A","B","C","D","E","E")
d <- data.frame(cbind(sp,category,count,habitat))
dm <- d %>%
select(sp,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,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")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。