ggplot2heatmapgeom-tilecomplexheatmapd3heatmap

Heatmap with Annotation Using GGplot


I am trying to make a heatmap in R for species in a family of microorganisms with samplesID as x, species names as y, and two faceting factor groups at the top. I want something like the picture below

Here is what I have been able to do so far:

ad = tidyr::pivot_wider(Intrasporangiaceae, names_from = 'Species',values_from='Abundance')         
     ad[is.na(ad)] <- 0
     ad = as.matrix(ad[,-c(1:11)])
adscaled <- scale(ad)
Aclust <- hclust(dist(t(ad)))

ggplot(Intrasporangiaceae, aes(Sorghum_Variety, Species, fill = Abundance)) + 
    geom_tile(width=1.0) +
    facet_grid(~Striga_Infestation_Status) +
    
    scale_fill_gradientn(name= 'Abundance',
                         colours = c("#373898ff", "pink","#c11630ff"), 
                         values = c(0,0.1,1), expand = c(0,0), limit = c(0,NA)) +
    scale_y_discrete(limits = colnames(ad)[Aclust$order]) +
    labs(title = paste('Species Abundance in', family_Name), x='', y='') +
    theme(legend.position='right',panel.background=element_blank(),
          axis.line = element_blank(),
          axis.ticks = element_blank(),
          axis.text.x = element_text(size = 8,angle = 90, hjust = 1),
          axis.text.y= element_markdown(),
          legend.text = element_text(size=7),
          legend.key.height = unit(10,'pt'),
          legend.title = element_text(size = 10),
          strip.text = element_text(size = 10),
          axis.title.x = element_text(size = 8),
          axis.title.y = element_text(size = 10),
          plot.title = element_text(size=15, hjust = 0.5)) +
    coord_fixed(ratio = 0.5) +
    theme(panel.spacing = unit(0.04, 'lines'))

What I want: What I want I look forward to your help. Thanks in advance. A sample data is available here: https://drive.google.com/file/d/1Y-D2h3mYNOpBjAPaqdLmTcGtHtOS-F2z/view?usp=sharing`


Solution

  • The ggh4x package can help you create a heat map with nested facets:

    Since coord_fixed is incompatible with free scales in facet_ functions, you can specify the desired aspect ratio as one of your theme's components.

    library(ggplot2)
    
    aspect_ratio <- length(unique(df$Species))
    
    ggplot(df, aes(SampleID, Species, fill = Abundance)) +
      geom_tile(width = 1, height = 1) +
      scale_fill_gradientn(name= 'Abundance',
                           colours = c("#373898ff", "pink","#c11630ff"), 
                           values = c(0,0.1,1), expand = c(0,0), limit = c(0,NA)) +
      ggh4x::facet_nested(~ Sorghum_Variety + Striga_Infestation_Status,
                               space = 'free_x',
                               scales = 'free_x'
                   ) +
      labs(y = '') +
      theme(axis.text.x = element_text(angle = 45, hjust = 1),
            axis.text.y = element_text(angle = -45, vjust = 1),
            aspect.ratio = aspect_ratio,
            legend.position = 'bottom')