Search code examples
rggplot2heatmapdendrogram

Merge two plots while fix axis elements


I want to merge a tileplot (from tile object) and a dendrogram (from dendro object) while fixing all the elements on y axis at the same place.

With a small reproducible example of data:

library(tidyverse)
library(dendextend)
library(ggpubr)

df <- tibble(
Method=c("kbest_f","fpr_chi2","perc_f","kbest_chi2","fpr_chi2","perc_mutual","perc_f","perc_mutual","fpr_chi2","fpr_chi2"),
Coincidence = c("AVV","ENH","MPN","WET","TKR","LEA","SPQ","PIY","VYL","AGL"), n=rep(1,10))

scores <- with(df, table(Coincidence, Method))
dendro <- as.dendrogram(hclust(dist(scores, method="binary"), method="ward.D"))

tile <- df %>%
    mutate(Coincidence = factor(Coincidence,levels=partition_leaves(dendro)[[1]]))

I've managed to generate these two plots:

tileplot <- tile %>%
    ggplot(aes(Method, Coincidence, fill= n)) + 
  geom_tile()+
  theme(
    axis.text.x = element_text(
        angle = 90,
        vjust = 0.5,
        hjust=1),
    axis.text.y = element_text(size=5),
    legend.position="none")

dendroplot <- 
    ggdendrogram(
        dendro,
        rotate=TRUE)+
    theme(axis.text.y = element_text(
          size = 5,
          vjust = 0.5,
              hjust = 1.0))

Finally:

ggarrange(
    tileplot,
    dendroplot,
    labels=c("A","B"),
    ncol=2,
    nrow=1)

While using ggarrange to merge tileplot and dendroplot generates the correct array, the size of the y-axis dendrogram needs to be shorter, so that all labels remain at the corresponding level.

So, how can I adjust them?

P.D: Default options of heatmap() functions do not show all the elements i need at the way i need.


Solution

  • A solution is to use plot_grid() from the cowplot package. cowplot::plot_grid() allows you to arrange and align plots in a grid.
    Specifically, the align = "h" option allows plots to be drawn with horizontal alignment, which means that the y-axes of plots in the same row have the same lengths on the grid.

    library(cowplot)
    
    plot_grid(tileplot, dendroplot, labels = "AUTO", align = "h")
    

    enter image description here

    Reference: https://wilkelab.org/cowplot/articles/plot_grid.html