jokergoo / ComplexHeatmap

Make Complex Heatmaps
https://jokergoo.github.io/ComplexHeatmap-reference/book/
Other
1.31k stars 228 forks source link

Adjusting the column title position #1205

Open rbutleriii opened 2 months ago

rbutleriii commented 2 months ago

I have a list of plots I am plotting with patchwork, and the column titles are overlapping: image

I am trying to get the titles to move right, or align with the left side of the heat map box, or at least consistently move each title to the right to see them. I am trying to adjust it with

      column_title = gt_render(input[i], padding = unit(c(0, 0, 0, 0.5), "in")),
      column_title_gp = gpar(fontsize = 16, fontface = "bold")

But I can't find any help on what order that vector is in for the unit (top, bottom, right, left?), or if adding padding is even the right way to do it. It seems to work for the first two but then ignore the others.

rbutleriii commented 2 months ago
#' plot heatmap of overlaps colored by value, and sized by overlap (given matrices, name)
#'
#' @param mat matrix of heatmap values (fdr, p-val, or odds.ratio)
#' @param pval matched matrix of fdr values, to bold significant circles
#' @param name legend name for plot (fdr, p-val, or odds.ratio)
#' @param range vector of two numbers for upper/lower bounds of heatmap default: auto select
#'
#' @return a draw graph call
heat <- function(mat, pval, name, range = NULL, ...) {
  # color palette
  if (is.null(range)) {
    bottom <- floor(min(mat, na.rm = TRUE))
    top <- ceiling(max(mat, na.rm = TRUE))
  }
  col_fun <- colorRamp2(c(bottom, 0, top), c("#2166ac", "#FFFFFF", "#b2182b"))

  # heatmap plot 
  a <- Heatmap(mat, 
    cluster_rows = FALSE, 
    cluster_columns = FALSE, 
    na_col = "#FFFFFF", 
    col = col_fun, 
    name = name, 
    show_column_names = FALSE, 
    heatmap_legend_param = list(at = c(bottom, 0, top)), 
    cell_fun = function(j, i, x, y, w = unit(1.5, "cm"), h, col) {
      width = unit(1.5, "cm")
      # add text to each grid
      if (pval[i, j] < 0.05) {
        grid.text(sprintf("%s", "*"), x, y, 
          gp = gpar(fontsize = 10, fontface = "bold", col = "black")
        )
      }
    }, 
    ...
  )
  draw(a)
}

p.list <- lapply(seq(input), function(i) {
  grid.grabExpr(
    heat(
      mat = m.list[[i]][[1]], 
      pval = m.list[[i]][[2]], 
      name = "beta", 
      range = c(bottom, top),
      column_title = gt_render(input[i], padding = unit(c(0, 0, 0, 0.5), "in")),
      column_title_gp = gpar(fontsize = 16, fontface = "bold")
    )
  )
})

ggsave(
  filename = file.path(output, paste(nameset, "top_genes.pdf", sep=".")), 
  plot = wrap_plots(p.list) + plot_layout(nrow = 1), 
  device = cairo_pdf,
  width = 20, 
  height = 14
)