jokergoo / InteractiveComplexHeatmap

Make Interactive Complex Heatmaps
https://jokergoo.github.io/InteractiveComplexHeatmap/
Other
130 stars 24 forks source link

How to change Z-score values in heatmap? #102

Open hndyilm opened 1 year ago

hndyilm commented 1 year ago

Hello everyone,

How to change Z-score distribution in heatmap? When I make heatmap , it gives Z-score <0 and >0. I want to make Z-score between -2 and 2.

my_Z_scoreNormalize <- function(x){(x-mean(x))/sd(x)}

heatmap_df_normalized <- t(apply(heatmap_df, MARGIN=1, FUN=my_Z_scoreNormalize))

pdf("heatmap.pdf", height=10, width=16) Heatmap(heatmap_df_normalized, col = inferno(256), cluster_rows = FALSE, cluster_columns = FALSE, show_column_names = FALSE, top_annotation=heatmap_cohort_annotation, column_split=celltype_order, column_title = NULL, use_raster=FALSE) dev.off()

Thank you in advance.

jokergoo commented 1 year ago

First, the range of z-score is [-inf, inf].

If you want to perform z-score scaling but restricted in [-2. 2], you can change values < -2 to -2 and all values > 2 to 2.

my_Z_scoreNormalize <- function(x){
  x2 = (x-mean(x))/sd(x)
  x2[x2 < -2] = -2
  x2]x2 > 2] = 2
  x2
}

You can also do a min-max scaling where you can specify a range:

min_max_scale = function(x, range = c(-2, 2)) {
    (x - min(x))/(max(x) - min(x)) * (range[2] -range[1]) + range[1]
}