1

I want to add grid layout in the background with a heatmap. How can I do it?

Here is my code:

df <- read_tsv("Typhi_Phage_Data.tsv")

df %>% column_to_rownames(var = "ID") %>% as.matrix() %>%
  heatmap(Colv = NA, scale = "row", margins = c(10,10), col= c("#27AE60", "#E74C3C"))

Generated output:

enter image description here

Rajan Raju
  • 113
  • 7
  • Does this answer your question? [How to put black borders in heatmap in R](https://stackoverflow.com/questions/5035491/how-to-put-black-borders-in-heatmap-in-r) – caldwellst Mar 05 '22 at 08:34
  • @caldwellst, No. I'm not using ggplot. Using heatmap – Rajan Raju Mar 05 '22 at 08:44
  • The responses there uses many different packages, not just `ggplot2`, outlining how to add grids to heatmaps, exactly your question. Would recommend reading through them, because it may be much easier to use those solutions rather than the base `heatmap()`. – caldwellst Mar 05 '22 at 08:47
  • @caldwellst is it possible to add dendrogram using ggplot – Rajan Raju Mar 05 '22 at 08:48
  • Look at `gplots::heatmap.2()` in the linked post above. – caldwellst Mar 05 '22 at 08:53

1 Answers1

1

I’m using cars data as I cannot access to “Typhi_Phage_Data.tsv” file but you should not have any problem to apply the same code

I wrote a short note on decorating heatmap() function result in RPubs. You can find there more details on the solution proposed.

x  <- as.matrix(mtcars)

heatmap(x, col = cm.colors(256), scale = "row",
  margins = c(10,10),
  Colv = NA)

# use `verbose = TRUE` to get layout parameters 
heatmap(x, col = cm.colors(256), scale = "row",
  margins = c(10,10),
  Colv = NA, verbose = TRUE)
#> layout: widths =  1 4 , heights =  0.05 4 ; lmat=
#>      [,1] [,2]
#> [1,]    0    3
#> [2,]    2    1

lmat <- matrix(c(1, 3, 2, 4), 2, 2, byrow = TRUE)
lhei <- c(0.05, 4)
lwid <- c(1, 4)
n <- dim(x)
xlim <- 0.5 + c(0, n[2])
ylim <- 0.5 + c(0, n[1])

#new layout
layout(lmat, widths = lwid, heights = lhei, respect = TRUE)
# if you change the margins in `heatmap()` call, change them also here
par(mar = c(10, 0, 0, 10), new = TRUE, xaxs = 'i', yaxs = 'i')
plot(1, 1, type = 'n', xaxt = 'n', yaxt = 'n', ann = FALSE,
  xlim = xlim, ylim = ylim, bty = 'n')

# These are the grid lines. YOu can format color, size and type
abline(h = (0:n[1]) + 0.5, v = (0:n[2]) + 0.5, col = "red", lwd = 1)

Created on 2022-03-05 by the reprex package (v2.0.1)

josep maria porrà
  • 1,198
  • 10
  • 18