Search code examples
rggplot2ggplotly

Separate groups in a ggplot heatmap by adding a black column between them


I have a dataframe:

gene_symbol <- c("sads", "sdsds", "sdasdad", "dfds", "sdsdd")
panel <- c("big", "big", "big", "gr", "sm")
variable <- c("x", "x", "y", "z", "y")
value <- c("normal", "over", "low", "normal", "low")
colors <- c("red", "green", "yellow", "red", "red")

HG44 <- data.frame(gene_symbol, panel, variable, value, colors)
HG44$gene_symbol <- factor(HG44$gene_symbol, levels = unique(HG44$gene_symbol))

and I create a heatmap with:

library(ggplot2)
library(reshape2)

pp <- ggplot(HG44, aes(gene_symbol, variable)) + 
  geom_tile(aes(fill = value)) + 
  theme(axis.text.x = element_text(family = "Calibri", 
                                   size = 11, angle = 45, hjust = 1))

library(plotly)

ggplotly(pp)

As you can see the first 3 gene symbols belong to the panel "big" and the other 2 to the other 2 panel respectively. I would like somehow to separate those grouped gene symbols without using facet.grid(). I am thinking of adding an empty black column in the end of every group which will separate them from the others and will have the name of each panel at the top or at the bottom.


Solution

  • It seems you can use geom_vline function to separate these groups. See as below:

    gene_symbol <- c("sads", "sdsds", "sdasdad","dfds","sdsdd")
    panel <- c("big", "big", "big", "gr", "sm")
    variable <- c("x","x","y","z","y")
    value <- c("normal", "over", "low", "normal", "low")
    colors <- c("red", "green", "yellow", "red", "red")
    
    HG44 <- data.frame(gene_symbol, panel, variable, value, colors)
    HG44$gene_symbol <- factor(HG44$gene_symbol, levels = unique(HG44$gene_symbol))
    
    library(ggplot2)
    library(reshape2)
    
    pp <- ggplot(HG44, aes(gene_symbol,variable)) + 
      geom_tile(aes(fill = value)) + 
      theme(axis.text.x = element_text(family = "Calibri", size = 11, angle = 45, hjust = 1)) +
      geom_vline(xintercept = c(3.5, 4.5), size = 2)
    
    library(plotly)
    ggplotly(pp)
    

    Output: Genes separated