1
votes

I plotted a matrix using geom_tile. Then, I would like to add the track colors below the x-axis. I ran the following code from the similar topic answer (ggplot Adding Tracking Colors Below X-Axis), but it shows the error "Discrete value supplied to continuous scale".

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))
1

1 Answers

1
votes

Here is one potential solution:

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")

example_3.png