Zettelkasten

source(file.path("..", "Analyses", "Differential Expression", "RNA-Seq - EdgeR.R"), verbose=TRUE)

max.genes.in.heatmap <- 35

#################################################################
# Heatmap                                                       #
#################################################################
genes.to.plot <- de.results %>%
  dplyr::filter( # Cutoffs
    FDR < 0.05,
    abs(logFC) > log2(fc.cutoff)
  ) %>%
  dplyr::arrange(
    PValue
  ) %>%
  dplyr::filter(
    dplyr::row_number() <= max.genes.in.heatmap # Let's plot the top 35
  ) %>%
  dplyr::arrange( # Visually group the top results by Fold Change, within there sort by PValue
    abs(logFC) > fc.cutoff,
    PValue
  ) %>%
  dplyr::mutate(
    gene.color = ifelse(
      logFC > 0,
      "red",
      "blue"
    )
  )

masterTable <- masterTable %>%
  dplyr::arrange(group)

expressionData <- expressionData %>%
  select.columns.in.order(c("Gene", masterTable$mirna.sample.id))

# Heatmap
norm_expressionData <- (expressionData %>%
  tibble::column_to_rownames("Gene") %>%
  limma::voom())[genes.to.plot$ensembl_gene_id, ] # We use 'limma::voom()', Because 'edgeR::cpm()' is not visually pleasing.

if (nrow(genes.to.plot) > 0) {
  png(
    filename = file.path(out.dir, "heatmap.png"),
    width = 500,
    height = 800
  )

  heatmap3::heatmap3(
    as.matrix(
      norm_expressionData[
        genes.to.plot$ensembl_gene_id,
        masterTable$mirna.sample.id
      ]
    ),
    ColSideColors = as.numeric(masterTable$group),
    RowSideColors = genes.to.plot$gene.color,
    RowSideLabs = "Fold change",
    col = colorRampPalette(c("blue", "white", "red"))(256),
    Rowv = NA,
    Colv = NA,
    cexRow = "1",
    cexCol = "1",
    scale = "row",
    margins = c(1, 12),
    main = "Heatmap",
    labCol = NA,
    balanceColor = TRUE # Important
  )

  dev.off()
}