Search code examples
rggplot2pheatmap

How to produce a geom_line graph above heatmap?


Im trying to produce a heatmap of circadian gene expression data and above it to show the behavior measured.

i want it to look somthing like this: enter image description here

Note the 2 red dots should be above CT13 and CT37 (respectively)...

this is the code i tried to use but it produces 2 separated graphs:

library(pheatmap)
library(RColorBrewer)
library(ggplot2)

# prepare data for Heat map:
my_heatmap <- read.csv("circ_genes.csv", header = TRUE)
mymat <- my_heatmap[,c(2:13)]
rownames(mymat) <- paste("Gene", my_heatmap[,1], sep="_")
mydf <- data.frame(row.names = paste("Gene", my_heatmap[,1], sep="_"), 
category = my_heatmap[,14])
my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 1000)

# prepare data for line graph
behavior_LD <- read.csv("behavior.csv", header = TRUE)
CT <- behavior_LD$CT
CT <- as.character(CT)
behavior_LD$CT <- factor(behavior_LD$CT, levels = CT )
mycolours <- c("H1" = "red", "H0" = "black")

behavePlot <- ggplot(data=behavior_LD, aes(x=CT, y=Average, group=1)) +
  geom_line()+
  geom_point(aes(colour = factor(highlight)), size = 3) +
  geom_errorbar(aes(ymin=Average-SE, ymax=Average+SE), width=.1)+
  scale_color_manual(values = mycolours) + theme(legend.position="none") +
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()) +
  theme(plot.margin=unit(c(5,2,5,2),"cm"))

# plot 2 graphs
par(mfrow=c(2,1))

behavePlot

pheatmap(mymat, color = my_palette, legend_labels = "Clusters", cluster_cols 
= F, cluster_rows = F, annotation_row = mydf, gaps_row = c(43, 60, 88, 124), 
annotation_names_row = FALSE, show_rownames = FALSE )

files i used can be found in here: https://www.dropbox.com/sh/n3mplr0fdz7oh6f/AACU_CdVjT6OmJLzrKmAtxj2a?dl=0

thank you for your help!


Solution

  • First, remove

    theme(plot.margin=unit(c(5,2,5,2), "cm")) 
    

    from your top line chart code.

    Then, just fill in some missing columns in each gtable and add some padding:

    library(gtable)
    library(grid.arrange)
    
    top <- ggplotGrob(behavePlot)
    bot <- phm$gtable
    
    bot1 <- gtable_add_cols(bot, unit.c(top$widths[[1]], top$widths[[2]], top$widths[[3]]), 0)
    top1 <- gtable_add_cols(top, bot$widths[[6]])
    
    grid.newpage()
    grid.draw(
      gtable_add_padding(
        arrangeGrob(top1, bot1, ncol=1, nrow=2, heights=c(0.2, 0.8)),
        unit(c(0, 2, 0, 2), "lines")
      )
    )
    

    enter image description here

    NOTE: this is a bit of a hack that achieves your desired result but is very fragile. Hopefully Claus will spot this q and have a more elegant solution for you.