Rajan Raju
Rajan Raju

Reputation: 123

How to incorporate grid layout in background of a heatmap in R?

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

Upvotes: 1

Views: 827

Answers (1)

josep maria porr&#224;
josep maria porr&#224;

Reputation: 1388

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)

Upvotes: 1

Related Questions