Last updated: 2021-04-13

Checks: 6 1

Knit directory: melanoma_publication_old_data/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200728) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 3203891. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rproj.user/
    Ignored:    ._.DS_Store
    Ignored:    analysis/._clinical metadata preparation.Rmd
    Ignored:    code/.DS_Store
    Ignored:    code/._.DS_Store
    Ignored:    data/.DS_Store
    Ignored:    data/._.DS_Store
    Ignored:    data/data_for_analysis/
    Ignored:    data/full_data/
    Ignored:    output/.DS_Store
    Ignored:    output/._.DS_Store
    Ignored:    output/._protein_neutrophil.png
    Ignored:    output/._rna_neutrophil.png
    Ignored:    output/PSOCKclusterOut/
    Ignored:    output/bcell_grouping.png
    Ignored:    output/dysfunction_correlation.pdf

Unstaged changes:
    Modified:   .gitignore
    Modified:   analysis/10_Dysfunction_Score.rmd
    Modified:   analysis/11_Bcell_Score.Rmd
    Modified:   analysis/Figure_1.rmd
    Modified:   analysis/Figure_2.rmd
    Modified:   analysis/Figure_4.rmd
    Modified:   analysis/Figure_5.rmd
    Modified:   analysis/Summary_Statistics.rmd
    Modified:   analysis/Supp-Figure_1.rmd
    Modified:   analysis/Supp-Figure_2.rmd
    Modified:   analysis/Supp-Figure_4.rmd
    Modified:   analysis/Supp-Figure_5.rmd
    Modified:   analysis/XX_hazard_ratio.rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Supp-Figure_5.rmd) and HTML (docs/Supp-Figure_5.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 3203891 toobiwankenobi 2021-02-19 change celltype names
html 3203891 toobiwankenobi 2021-02-19 change celltype names
Rmd ee1595d toobiwankenobi 2021-02-12 clean repo and adapt files
html ee1595d toobiwankenobi 2021-02-12 clean repo and adapt files
html 3f5af3f toobiwankenobi 2021-02-09 add .html files
Rmd afa7957 toobiwankenobi 2021-02-08 minor changes on figures and figure order
Rmd 20a1458 toobiwankenobi 2021-02-04 adapt figure order
Rmd f9bb33a toobiwankenobi 2021-02-04 new Figure 5 and minor changes in figure order
Rmd 9442cb9 toobiwankenobi 2020-12-22 add all new files
Rmd 77466b7 Tobias Hoch 2020-10-22 work on subfigures
Rmd f643fb2 toobiwankenobi 2020-10-19 add tumor analysis
Rmd 58c40e5 toobiwankenobi 2020-10-19 correct files that don’t work
Rmd 1af3353 toobiwankenobi 2020-10-16 add stuff

Introduction

This script generates plots for Figure 3.

Preparations

knitr::opts_chunk$set(echo = TRUE, message= FALSE)
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())

Load libraries

First, we will load the libraries needed for this part of the analysis.

sapply(list.files("code/helper_functions", full.names = TRUE), source)
        code/helper_functions/calculateSummary.R
value   ?                                       
visible FALSE                                   
        code/helper_functions/censor_dat.R
value   ?                                 
visible FALSE                             
        code/helper_functions/detect_mRNA_expression.R
value   ?                                             
visible FALSE                                         
        code/helper_functions/DistanceToClusterCenter.R
value   ?                                              
visible FALSE                                          
        code/helper_functions/findMilieu.R code/helper_functions/findPatch.R
value   ?                                  ?                                
visible FALSE                              FALSE                            
        code/helper_functions/getInfoFromString.R
value   ?                                        
visible FALSE                                    
        code/helper_functions/getSpotnumber.R
value   ?                                    
visible FALSE                                
        code/helper_functions/plotCellCounts.R
value   ?                                     
visible FALSE                                 
        code/helper_functions/plotCellFractions.R
value   ?                                        
visible FALSE                                    
        code/helper_functions/plotDist.R
value   ?                               
visible FALSE                           
        code/helper_functions/scatter_function.R
value   ?                                       
visible FALSE                                   
        code/helper_functions/sceChecks.R
value   ?                                
visible FALSE                            
        code/helper_functions/validityChecks.R
value   ?                                     
visible FALSE                                 
library(cytomapper)
library(SingleCellExperiment)
library(reshape2)
library(tidyverse)
library(dplyr)
library(data.table) 
library(ggplot2)
library(colorRamps)
library(RColorBrewer)
library(gridExtra)
library(ggpmisc)
library(ComplexHeatmap)
library(scater)
library(dittoSeq)
library(ggbeeswarm)
library(corrplot)
library(ggpubr)
library(cowplot)
library(circlize)
library(ggrepel)
library(rstatix)

Read the data

sce_rna = readRDS(file = "data/data_for_analysis/sce_RNA.rds")
sce_prot = readRDS(file = "data/data_for_analysis/sce_protein.rds")

# remove LN margin samples and control samples
sce_rna$PunchLocation <- paste(sce_rna$MM_location, sce_rna$Location, sep = "_")
sce_prot$PunchLocation <- paste(sce_prot$MM_location, sce_prot$Location, sep = "_")
sce_rna <- sce_rna[,sce_rna$PunchLocation != "LN_M" & sce_rna$Location != "CTRL"]
sce_prot <- sce_prot[,sce_prot$PunchLocation != "LN_M" & sce_prot$Location != "CTRL"]

# image
image_mat_prot <- read.csv("data/data_for_analysis/protein/Image.csv")

# surv_dat
dat_survival_prot <- fread(file = "data/data_for_analysis/protein/clinical_data_protein.csv")

Prepare image size data

im_size <- as.data.frame(cbind(image_mat_prot$Metadata_Description, (image_mat_prot$Height_cellmask * image_mat_prot$Width_cellmask)/1000000))
names(im_size) <- c("Description", "mm2")
im_size$mm2 <- as.numeric(im_size$mm2)
im_size[im_size$Description %in% c("G1", "G1 - split"), ]$mm2 <- mean(im_size[im_size$Description %in% c("G1", "G1 - split"), ]$mm2)
im_size <- im_size[im_size != "G1 - split",]

Supp Figure 5A/5B

Diffusion Map for CXCL13 Producing Cells

# loop through all patches 
for(i in c("cxcl13only_clust")){
  # subset sce object to only contain community cells
  sce_sub <- sce_rna[,colData(sce_rna)[,i] > 0]

  assay(sce_sub, "scaled_asinh") <- t(scale(t(assay(sce_sub, "asinh"))))
  
  # create UAMP
  set.seed(12345)
  sce_sub <- runDiffusionMap(sce_sub, 
                             exprs_values = "asinh", 
                             subset_row = rowData(sce_sub)$good_marker,
                             ncomponents = 2)
  
  # add patch size to sce
  cur_df <- data.frame(colData(sce_sub))

  clust_size <- cur_df %>%
    group_by(cur_df[,i]) %>%
    summarise(clust_size = n())
   
  names(clust_size)[1] <- i 
  
  cur_df <- left_join(cur_df, clust_size)
  sce_sub$clust_size = as.numeric(log10(cur_df$clust_size))
  
   # col by clust size
  a <- dittoDimPlot(sce_sub,
                    reduction.use = "DiffusionMap",
                    var = "clust_size", 
                    size = 1,
                    legend.show = TRUE,
                    opacity = 1,
                    max.color = "red", min.color = "blue",
                    main = NULL,
                    legend.title = "Patch Size (log10)") +
    xlim(quantile(reducedDim(sce_sub, "DiffusionMap")[,1], 0.05)[[1]],
         quantile(reducedDim(sce_sub, "DiffusionMap")[,1], 0.95)[[1]]) +
    ylim(quantile(reducedDim(sce_sub, "DiffusionMap")[,2], 0.05)[[1]],
         quantile(reducedDim(sce_sub, "DiffusionMap")[,2], 0.95)[[1]]) +
    theme_bw() +
    theme(text = element_text(size=18))

  # col by celltype
  b <- dittoDimPlot(sce_sub, 
             reduction.use = "DiffusionMap", 
             var = "celltype", 
             opacity = 1,
             color.panel = metadata(sce_sub)$colour_vector$celltype,
             size = 1,
             legend.show = TRUE,
                    main = NULL,
             legend.title = "Cell Type") +
    theme_bw() +
    xlim(quantile(reducedDim(sce_sub, "DiffusionMap")[,1], 0.05)[[1]],
         quantile(reducedDim(sce_sub, "DiffusionMap")[,1], 0.95)[[1]]) +
    ylim(quantile(reducedDim(sce_sub, "DiffusionMap")[,2], 0.05)[[1]],
         quantile(reducedDim(sce_sub, "DiffusionMap")[,2], 0.95)[[1]]) +
    theme(text = element_text(size=18)) + 
    guides(colour = guide_legend(override.aes = list(alpha = 1, size=3))) 
  
  leg_a <- cowplot::get_legend(a)
  leg_b <- cowplot::get_legend(b)

}
Warning: Removed 1063 rows containing missing values (geom_point).

Warning: Removed 1063 rows containing missing values (geom_point).
sce_sub <- sce_rna[,colData(sce_rna)[,"cxcl13only_clust"] > 0]

# add patch size to sce
cur_df <- data.frame(colData(sce_sub))

clust_size <- cur_df %>%
  group_by(cxcl13only_clust) %>%
  summarise(clust_size = n())
   
names(clust_size)[1] <- "cxcl13only_clust"
  
cur_df <- left_join(cur_df, clust_size)

sce_sub$clust_size = as.numeric(log10(cur_df$clust_size))

# add clust size correlation plot 
clust_size <- data.frame(colData(sce_sub)) %>%
  distinct(Description, cxcl13only_clust, .keep_all = T) %>%
  group_by(Description) %>%
  summarise(maxClustSize = max(clust_size))

Bcell_patch <- data.frame(colData(sce_prot)) %>%
  group_by(Description, bcell_patch) %>%
  summarise(n=n()) %>%
  mutate(n = ifelse(bcell_patch == 0, 0, n)) %>%
  mutate(maxPatchSize = log10(max(n+1))) %>%
  distinct(Description, .keep_all = T) %>% 
  select(Description, maxPatchSize)

Bcell_patch <- left_join(Bcell_patch, clust_size)
Bcell_patch[is.na(Bcell_patch$maxClustSize), ]$maxClustSize <- 0

Bcell <- data.frame(colData(sce_prot)) %>%
  group_by(Description, celltype) %>%
  summarise(n=n()) %>%
  mutate(fraction = n / sum(n)) %>%
  reshape2::dcast(Description ~ celltype, value.var = "fraction", fill = 0) %>%
  select(Description, `B cell`)

Bcell <- left_join(Bcell, clust_size)
Bcell[is.na(Bcell$maxClustSize), ]$maxClustSize <- 0

# only when not 0 - CHANGE?
c <- ggplot(Bcell_patch[rowSums(Bcell_patch[,-1]) > 0,], aes(x = maxClustSize, y = maxPatchSize, label=Description)) + 
  geom_point() +
  geom_smooth(method="lm") + 
  stat_cor(method = "pearson",
           aes(label = paste0("atop(", ..r.label..,  ",", ..rr.label.. ,")")),
           size = 6, cor.coef.name = "R", label.sep="\n", label.y = 0.5, label.x = 2) + 
  ylab("Max Size of B cell\nPatches (log10)") +
  xlab("Max Size of CXCL13 Patches (log10)") +
  theme_bw() + 
  theme(text = element_text(size=18))

d <- ggplot(Bcell, aes(x = maxClustSize, y = `B cell`, label=Description)) + 
  geom_point() +
  geom_smooth(method="lm") + 
  stat_cor(method = "pearson",
           aes(label = paste0("atop(", ..r.label..,  ",", ..rr.label.. ,")")),
           size = 6, cor.coef.name = "R", label.sep="\n", label.y = 0.05, label.x = 2) + 
  ylab("B Cell Fraction") +
  xlab("Max Size of CXCL13 Patches (log10)") +
  theme_bw() + 
  theme(text = element_text(size=18))

plot_grid(grid.arrange(a + theme(legend.position = "none"), 
                       b + theme(legend.position = "none"),
                       ncol = 2),
          grid.arrange(d,c, ncol = 2),
          ncol = 1, 
          rel_heights = c(0.65,0.35))
Warning: Removed 1063 rows containing missing values (geom_point).

Warning: Removed 1063 rows containing missing values (geom_point).

Legend for Plot

grid.arrange(leg_a)
grid.arrange(leg_b)

Supp Figure 5C

Tcf7+ correlation with Tcf7+PD1+ in Tcells

cur_dat <- data.frame(colData(sce_prot)) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>% # remove LN margin images 
  filter(Location != "CTRL") %>%
  mutate(TCF7_PD1 = paste(TCF7, PD1, sep = "_")) %>%
  group_by(Description, bcell_patch_score, celltype, TCF7_PD1) %>%
  summarise(n=n()) %>% 
  reshape2::dcast(Description + bcell_patch_score + celltype ~ TCF7_PD1, value.var = "n", fill=0) %>%
  reshape2::melt(id.vars = c("Description", "bcell_patch_score", "celltype"), 
                 variable.name = "TCF7_PD1", value.name = "n") %>%
  group_by(Description, celltype) %>%
  mutate(fraction = n/sum(n)) %>%
  mutate(total_cells = sum(n)) %>%
  ungroup() %>%
  filter(celltype %in% c("CD8+ T cell", "CD4+ T cell")) 

cur_dat <- left_join(cur_dat, im_size)

cur_dat$density <- cur_dat$n / cur_dat$mm2

cur_dat <- cur_dat %>%
  filter(TCF7_PD1 %in% c("TCF7+_PD1+", "TCF7+_PD1-")) %>%
  reshape2::dcast(Description + bcell_patch_score + celltype ~ TCF7_PD1, value.var = "density", fill=0)

ggplot(cur_dat, aes(x=log10(`TCF7+_PD1+`+1), y=log10(`TCF7+_PD1-`+1))) + 
  geom_point(size=3) + 
  geom_smooth(method="lm") +
  stat_cor(method = "pearson",
           aes(label = paste0("atop(", ..r.label..,  ",", ..rr.label.. ,")")),
           size = 7, cor.coef.name = "R", label.sep="\n", label.y.npc = "top") +
  theme_bw() +
  theme(text = element_text(size=16)) +
  xlab("TCF7+PD1+ Cells per mm2 (log10+1)") +
  ylab("TCF7+PD1- Cells per mm2 (log10+1)") +
  facet_wrap(~celltype)

Supp Figure 5D

Response / Survival Analysis

# select blocks in ICI subgroup that are treatment-naive and non-adjuvant
blocks <- unique(sce_prot[,sce_prot$treatment_status_before_surgery == "naive" & 
                            sce_prot$treatment_group_after_surgery == "ICI" &
                            sce_prot$Adjuvant == "n"]$BlockID)

# subset survival data (only data points that contain info for 3m response)
dat_survival_prot_sub <- dat_survival_prot[dat_survival_prot$BlockID %in% blocks & 
                                             is.na(dat_survival_prot$Status_at_3m) == FALSE, ]

# remove LN margin samples
dat_survival_prot_sub <- dat_survival_prot_sub %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M")

# group sizes
dat_survival_prot_sub %>%
  distinct(PatientID, .keep_all = T) %>%
  group_by(Status_at_3m) %>%
  summarise(n=n())
# A tibble: 2 x 2
  Status_at_3m     n
  <chr>        <int>
1 NR               7
2 R                4

TCF7/PD1 fraction in responder vs. non responder

cur_dat <- data.frame(colData(sce_prot[,sce_prot$BlockID %in% unique(dat_survival_prot_sub$BlockID)])) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>% # remove LN margin images 
  #filter(celltype != "Tumor") %>%
  mutate(TCF7_PD1 = paste(TCF7, PD1, sep = "_")) %>%
  group_by(PatientID,BlockID, Description, bcell_patch_score, celltype, TCF7_PD1) %>%
  summarise(n=n()) %>% 
  reshape2::dcast(PatientID + BlockID + Description + bcell_patch_score + celltype ~ TCF7_PD1, value.var = "n", fill=0) %>%
  reshape2::melt(id.vars = c("PatientID","BlockID", "Description", "bcell_patch_score", "celltype"), 
                 variable.name = "TCF7_PD1", value.name = "n") %>%
  group_by(Description, celltype) %>%
  mutate(fraction = n/sum(n)) %>%
  mutate(total_cells = sum(n)) %>%
  ungroup() %>%
  filter(celltype %in% c("CD8+ T cell", "CD4+ T cell")) 

cur_dat <- left_join(cur_dat, dat_survival_prot_sub[,c("BlockID", "Status_at_3m", "Primary_melanoma_type")]) %>%
  distinct(Description, celltype, TCF7_PD1, .keep_all = T)

cur_dat <- left_join(cur_dat, im_size[im_size$Description %in% unique(cur_dat$Description),])
cur_dat$n_per_mm2 <- cur_dat$n / cur_dat$mm2
cur_dat$celltype2 <- paste(cur_dat$celltype, cur_dat$TCF7_PD1, sep = ", ")

stat.test <- cur_dat %>%
  filter(TCF7_PD1 %in% c("TCF7+_PD1+", "TCF7+_PD1-")) %>%
  mutate(log10_n_per_mm2 = log10(n_per_mm2 + 1)) %>%
  group_by(celltype2) %>%
  wilcox_test(data = ., log10_n_per_mm2 ~ Status_at_3m) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1))

# check adjusted p-values with another function
p.adjust(stat.test$p, method = "BH")
[1] 0.0566 0.0566 0.0566 0.0566
info <- cur_dat[,c("celltype2", "TCF7_PD1")] %>%
  distinct(celltype2, .keep_all = T)

# filter relevant tests
stat.test <- left_join(stat.test, info) %>%
  filter(TCF7_PD1 %in% c("TCF7+_PD1+", "TCF7+_PD1-"))

stat.test$p_and_p.adj <- paste(paste("p = ", round(stat.test$p,2), sep = ""), paste("p.adj = ", round(stat.test$p.adj,2), sep = ""), sep = "\n")

ggplot(cur_dat[cur_dat$TCF7_PD1 %in% c("TCF7+_PD1+", "TCF7+_PD1-"),], aes(x=Status_at_3m, y=log10(n_per_mm2+1), label=PatientID)) + 
  geom_boxplot(alpha=.4, outlier.shape = NA, aes(fill=Status_at_3m)) +
  geom_beeswarm(size=3) +
  geom_label_repel(aes(label=PatientID), max.overlaps = 12, size = 5, alpha=.5) + 
  stat_pvalue_manual(stat.test, label = "p_and_p.adj", size=5, label.x.npc = "left", y.position = -0.9, bracket.size = 0) +
  theme_bw() +
  theme(text = element_text(size=18)) +
  ylab("Cells per mm2 (log10)") +
  scale_fill_manual(values=c("blue", "orange")) + 
  xlab("") +
  guides(fill=guide_legend(title="Response 3m", override.aes = c(lwd=0.5, size=1))) +
  facet_wrap(~celltype2, scales = "free")
Warning: Duplicated aesthetics after name standardisation: size
Warning: ggrepel: 5 unlabeled data points (too many overlaps). Consider
increasing max.overlaps
Warning: ggrepel: 10 unlabeled data points (too many overlaps). Consider
increasing max.overlaps
Warning: ggrepel: 13 unlabeled data points (too many overlaps). Consider
increasing max.overlaps

Supp Figure 5E

Chemokine Correlation with Tcf7+CD8+

targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol

# top abundant chemokines
cur_rna <- data.frame(colData(sce_rna)) %>%
  filter(Location != "CTRL")

# protein data
cur_prot <- data.frame(colData(sce_prot)) %>%
  filter(Location != "CTRL")

# sum
rna_sum <- cur_rna %>%
  group_by(Description) %>%
  mutate(total_cells=n()) %>%
  ungroup() %>%
  group_by(Description, total_cells, expressor) %>%
  summarise(n=n()) %>%
  mutate(fraction=n/total_cells) %>%
  reshape2::dcast(Description ~ expressor, value.var = "fraction", fill = 0) 

# only keep highly abundant chemokines
rna_sum <- rna_sum[,c("Description", targets)]

prot_sum <- cur_prot %>%
  mutate(celltype2 = ifelse(celltype %in% c("CD4+ T cell", "CD8+ T cell"), 
                            paste(paste(celltype, TCF7, sep="_"), PD1, sep = "_"), celltype)) %>%
  group_by(Description, celltype2) %>%
  summarise(n = n()) %>%
  group_by(Description) %>%
  mutate(fraction = n/sum(n)) %>%
  #filter(!celltype2 %in% c("CD4+ T cell_TCF7+_PD1+", "CD4+ T cell_TCF7-_PD1+", "CD8+ T cell_TCF7+_PD1+")) %>%
  reshape2::dcast(Description ~ celltype2, value.var = "fraction", fill = 0) %>%
  select(Description,contains(c("CD8+ T cell", "CD4+ T cell")))

# equal images
all(rna_sum$Description == prot_sum$Description)
[1] TRUE
# correlation
cor <- cor(rna_sum[,-1], prot_sum[,-1], method = "pearson")

ha <- t(str_split_fixed(colnames(cor), "_", n=3))

dat_sum <- cur_prot %>%
  filter(celltype %in% c("CD4+ T cell", "CD8+ T cell")) %>%
  mutate(celltype2 = ifelse(celltype %in% c("CD4+ T cell", "CD8+ T cell"), 
                            paste(paste(celltype, TCF7, sep="_"), PD1, sep = "_"), celltype)) %>%
  group_by(celltype2) %>%
  summarise(n = n())


ha1 <- HeatmapAnnotation("TCF7_PD1" = anno_text(paste(ha[2,], ha[3,], sep = " ")),
                         "Cell Type" = ha[1,],
                         "Number of Cells" = anno_barplot(dat_sum$n,
                                                         height = unit(2,"cm"),
                                                         axis_param = list(gp = gpar(fontsize=14))),
                        "Numbers" = anno_text(dat_sum$n, 
                                              which = "column", 
                                              rot = 0,
                                              height = unit(0.5,"cm"),
                                              just = "center", 
                                              location = 0.5),
                         col = list("Cell Type" = metadata(sce_prot)$colour_vectors$celltype[c("CD4+ T cell", "CD8+ T cell")]),
                         show_legend = FALSE)

h <- Heatmap(cor,
        name = "Pearson\nCorrelation",
        cluster_rows = FALSE,
        cluster_columns = FALSE,
        show_column_names = FALSE,
        show_row_names = TRUE,
        cell_fun = function(j, i, x, y, width, height, fill) {
          grid.text(sprintf("%.2f", cor[i, j]), x, y, gp = gpar(fontsize = 15, col = "black"))
          },
        col = colorRamp2(c(-1, 0, 1), c("red", "white", "blue")),
        row_title = "Expressor",
        row_names_side = "left",
        top_annotation = ha1,
        width = unit(18, "cm"),
        height = unit(10, "cm"),
        show_heatmap_legend = FALSE)

# draw heatmap
draw(h)

Legend heatmap

lgd1 = color_mapping_legend(h@matrix_color_mapping, plot = FALSE, legend_direction = "vertical", legend_width=unit(3,"cm"), at = c(-1:1))
lgd2 = color_mapping_legend(ha1@anno_list$`Cell Type`@color_mapping, plot = FALSE, legend_direction = "vertical", nrow = 4)

lgd_list = packLegend(lgd1,lgd2,direction = "vertical", gap = unit(1,"cm"))
draw(lgd_list)

sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04 LTS

Matrix products: default
BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C             
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
 [1] grid      parallel  stats4    stats     graphics  grDevices utils    
 [8] datasets  methods   base     

other attached packages:
 [1] rstatix_0.6.0               ggrepel_0.9.0              
 [3] circlize_0.4.12             cowplot_1.1.1              
 [5] ggpubr_0.4.0                corrplot_0.84              
 [7] ggbeeswarm_0.6.0            dittoSeq_1.0.2             
 [9] scater_1.16.2               ComplexHeatmap_2.4.3       
[11] ggpmisc_0.3.7               gridExtra_2.3              
[13] RColorBrewer_1.1-2          colorRamps_2.3             
[15] data.table_1.13.6           forcats_0.5.0              
[17] stringr_1.4.0               dplyr_1.0.2                
[19] purrr_0.3.4                 readr_1.4.0                
[21] tidyr_1.1.2                 tibble_3.0.4               
[23] ggplot2_3.3.3               tidyverse_1.3.0            
[25] reshape2_1.4.4              cytomapper_1.3.1           
[27] SingleCellExperiment_1.12.0 SummarizedExperiment_1.20.0
[29] Biobase_2.50.0              GenomicRanges_1.42.0       
[31] GenomeInfoDb_1.26.2         IRanges_2.24.1             
[33] S4Vectors_0.28.1            BiocGenerics_0.36.0        
[35] MatrixGenerics_1.2.0        matrixStats_0.57.0         
[37] EBImage_4.32.0              workflowr_1.6.2            

loaded via a namespace (and not attached):
  [1] utf8_1.1.4                shinydashboard_0.7.1     
  [3] tidyselect_1.1.0          htmlwidgets_1.5.3        
  [5] ranger_0.12.1             BiocParallel_1.22.0      
  [7] munsell_0.5.0             destiny_3.2.0            
  [9] codetools_0.2-18          withr_2.3.0              
 [11] colorspace_2.0-0          knitr_1.30               
 [13] rstudioapi_0.13           robustbase_0.93-7        
 [15] ggsignif_0.6.0            vcd_1.4-8                
 [17] VIM_6.0.0                 TTR_0.24.2               
 [19] labeling_0.4.2            git2r_0.28.0             
 [21] GenomeInfoDbData_1.2.4    farver_2.0.3             
 [23] pheatmap_1.0.12           rprojroot_2.0.2          
 [25] vctrs_0.3.6               generics_0.1.0           
 [27] xfun_0.20                 ggthemes_4.2.0           
 [29] R6_2.5.0                  clue_0.3-58              
 [31] rsvd_1.0.3                RcppEigen_0.3.3.9.1      
 [33] locfit_1.5-9.4            bitops_1.0-6             
 [35] DelayedArray_0.16.0       assertthat_0.2.1         
 [37] promises_1.1.1            scales_1.1.1             
 [39] nnet_7.3-14               beeswarm_0.2.3           
 [41] gtable_0.3.0              rlang_0.4.10             
 [43] systemfonts_0.3.2         scatterplot3d_0.3-41     
 [45] splines_4.0.3             GlobalOptions_0.1.2      
 [47] hexbin_1.28.2             broom_0.7.3              
 [49] yaml_2.2.1                abind_1.4-5              
 [51] modelr_0.1.8              backports_1.2.1          
 [53] httpuv_1.5.4              tools_4.0.3              
 [55] ellipsis_0.3.1            raster_3.4-5             
 [57] proxy_0.4-24              ggridges_0.5.3           
 [59] Rcpp_1.0.5                plyr_1.8.6               
 [61] zlibbioc_1.36.0           RCurl_1.98-1.2           
 [63] GetoptLong_1.0.5          viridis_0.5.1            
 [65] zoo_1.8-8                 haven_2.3.1              
 [67] cluster_2.1.0             fs_1.5.0                 
 [69] magrittr_2.0.1            RSpectra_0.16-0          
 [71] openxlsx_4.2.3            lmtest_0.9-38            
 [73] reprex_0.3.0              pcaMethods_1.80.0        
 [75] whisker_0.4               hms_0.5.3                
 [77] mime_0.9                  fftwtools_0.9-9          
 [79] evaluate_0.14             xtable_1.8-4             
 [81] smoother_1.1              rio_0.5.16               
 [83] jpeg_0.1-8.1              readxl_1.3.1             
 [85] shape_1.4.5               compiler_4.0.3           
 [87] crayon_1.3.4              htmltools_0.5.0          
 [89] mgcv_1.8-33               later_1.1.0.1            
 [91] tiff_0.1-6                lubridate_1.7.9.2        
 [93] DBI_1.1.0                 dbplyr_2.0.0             
 [95] MASS_7.3-53               boot_1.3-25              
 [97] Matrix_1.3-2              car_3.0-10               
 [99] cli_2.2.0                 pkgconfig_2.0.3          
[101] foreign_0.8-81            laeken_0.5.1             
[103] sp_1.4-5                  xml2_1.3.2               
[105] svglite_1.2.3.2           vipor_0.4.5              
[107] XVector_0.30.0            rvest_0.3.6              
[109] digest_0.6.27             rmarkdown_2.6            
[111] cellranger_1.1.0          edgeR_3.30.3             
[113] DelayedMatrixStats_1.10.1 gdtools_0.2.3            
[115] curl_4.3                  shiny_1.5.0              
[117] ggplot.multistats_1.0.0   rjson_0.2.20             
[119] nlme_3.1-151              lifecycle_0.2.0          
[121] jsonlite_1.7.2            carData_3.0-4            
[123] BiocNeighbors_1.6.0       viridisLite_0.3.0        
[125] limma_3.44.3              fansi_0.4.1              
[127] pillar_1.4.7              lattice_0.20-41          
[129] fastmap_1.0.1             httr_1.4.2               
[131] DEoptimR_1.0-8            xts_0.12.1               
[133] glue_1.4.2                zip_2.1.1                
[135] png_0.1-7                 svgPanZoom_0.3.4         
[137] class_7.3-17              stringi_1.5.3            
[139] RcppHNSW_0.3.0            BiocSingular_1.4.0       
[141] knn.covertree_1.0         irlba_2.3.3              
[143] e1071_1.7-4