Last updated: 2022-02-22

Checks: 7 0

Knit directory: MelanomaIMC/

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


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

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 d246c15. 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:    Table_S4.csv
    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/

Unstaged changes:
    Modified:   .gitignore
    Modified:   analysis/Supp-Figure_10.rmd
    Modified:   analysis/_site.yml
    Deleted:    analysis/license.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/Figure_1.rmd) and HTML (docs/Figure_1.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
html 73aa800 toobiwankenobi 2022-02-22 add .html for static website
Rmd 588dbb1 toobiwankenobi 2022-02-06 Figure Order
Rmd 3da15db toobiwankenobi 2021-11-24 changes for revision
Rmd c4e2793 toobiwankenobi 2021-08-04 rearrange figure order to match pre-print
html 4109ff1 toobiwankenobi 2021-07-07 delete html files and adapt gitignore
Rmd fc55711 toobiwankenobi 2021-07-07 figure changes
html fc55711 toobiwankenobi 2021-07-07 figure changes
Rmd 0f72ef1 toobiwankenobi 2021-05-11 figure adaptations
html 0f72ef1 toobiwankenobi 2021-05-11 figure adaptations
Rmd 4affda4 toobiwankenobi 2021-04-14 figure adaptations
html 4affda4 toobiwankenobi 2021-04-14 figure adaptations
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 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 d8c7699 Tobias Hoch 2020-10-23 adapt figure 1 and supp fig 6
Rmd 1af3353 toobiwankenobi 2020-10-16 add stuff
Rmd d8819f2 toobiwankenobi 2020-10-08 read new data (nuclei expansion) and adapt scripts
Rmd 2c11d5c toobiwankenobi 2020-08-05 add new scripts

Introduction

This script generates plots for Figure 1. Panel A and B were created manually.

Preparation

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

Load libraries

library(SingleCellExperiment)
library(data.table)
library(scater)
library(ggplot2)
library(dittoSeq)
library(ComplexHeatmap)
library(dplyr)
library(reshape2)
library(tidyverse)
library(rms)
library(cytomapper)
library(ggrepel)
library(circlize)
library(ggbeeswarm)
library(dendextend)

Load data

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

sce_rna <- sce_rna[,sce_rna$Location != "CTRL"]
sce_prot <- sce_prot[,sce_prot$Location != "CTRL"]

Figure 1C

Heatmap showing marker expression of celltypes - RNA data

# add marker expression to cells
marker_expression <- data.frame(t(assay(sce_rna[rowData(sce_rna)$good_marker,], "asinh")))
marker_expression$cellID <- rownames(marker_expression)
dat <- data.frame(colData(sce_rna))[,c("cellID", "celltype")]
dat <- left_join(dat, marker_expression)
dat$cellID <- NULL

# aggregate the groups
dat_aggr <- dat %>%
  group_by(celltype) %>%
  summarise_all(funs(mean))
Warning: `funs()` was deprecated in dplyr 0.8.0.
Please use a list of either functions or lambdas: 

  # Simple named list: 
  list(mean = mean, median = median)

  # Auto named with `tibble::lst()`: 
  tibble::lst(mean, median)

  # Using lambdas
  list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))
This warning is displayed once every 8 hours.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
# number of cells per group
dat_sum <- dat %>%
  group_by(celltype) %>%
  summarise(n=n())

dat_sum <- data.frame(t(dat_sum))

# scale and center expression
dat_aggr[,-c(1)] <- scale(dat_aggr[,-c(1)])

# create matrix
m <- as.matrix(t(dat_aggr[,-c(1)]))
colnames(m) <- dat_aggr$celltype

# number annotation
ha <- HeatmapAnnotation("Numbers" = anno_text(format(round(as.numeric(dat_sum[2,])), nsmall = 0, big.mark = "'"), 
                                                   which = "column", 
                                                   rot = 90, 
                                                   just = "center",
                                              height = unit(2.3,"cm"),
                                                   location = 0.5,
                                                   gp = gpar(fontsize=16,col = "black", border = "black")))

# row_split for markers
rowData(sce_rna)$heatmap_relevance <- ""
rowData(sce_rna[rowData(sce_rna)$good_marker,])$heatmap_relevance <- "Lineage"
rowData(sce_rna[grepl("CXCL|CCL|DapB", rownames(sce_rna)),])$heatmap_relevance <- "Chemokine"
rowData(sce_rna[grepl("B2M|GLUT1|CD134|Lag3|CD163|cleavedPARP|pRB", rownames(sce_rna)),])$heatmap_relevance <- "Other"

# plot heatmap
h <- Heatmap(m, name = "Scaled Expression",
             row_split = rowData(sce_rna[rowData(sce_rna)$good_marker,])$heatmap_relevance,
             cluster_columns = TRUE,
             show_column_dend = FALSE,
             column_names_gp = gpar(fontsize=18),
             column_names_rot = 45,
             column_names_centered = FALSE,
             show_column_names = TRUE,
             top_annotation = ha,
             row_names_gp = gpar(fontsize = 14),
             row_title_gp = gpar(fontsize = 23),
             col = colorRamp2(c(-2, 0, 2), c("blue", "white", "red")),
             heatmap_legend_param = list(at = c(-2:2), legend_width = unit(6,"cm"), 
                                         direction="horizontal", title_gp = gpar(fontsize=16),
                                         labels_gp = gpar(fontsize=12), title_position = "topcenter"),
             column_names_side = "bottom",
             height = unit(17, "cm"),
             width = unit(15,"cm"))

draw(h, heatmap_legend_side = "bottom")

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Heatmap showing marker expression of celltypes - Protein data

# add marker expression to cells
marker_expression <- data.frame(t(assay(sce_prot[rowData(sce_prot)$good_marker,], "asinh")))
marker_expression$cellID <- rownames(marker_expression)
dat <- data.frame(colData(sce_prot))[,c("cellID", "celltype")]
dat <- left_join(dat, marker_expression)
dat$cellID <- NULL

# aggregate the groups
dat_aggr <- dat %>%
  group_by(celltype) %>%
  summarise_all(funs(mean))

# number of cells per group
dat_sum <- dat %>%
  group_by(celltype) %>%
  summarise(n=n())

dat_sum <- data.frame(t(dat_sum))

# scale and center expression
dat_aggr[,-c(1)] <- scale(dat_aggr[,-c(1)])

# create matrix
m <- as.matrix(t(dat_aggr[,-c(1)]))
colnames(m) <- dat_aggr$celltype

# number annotation
ha <- HeatmapAnnotation("Numbers" = anno_text(format(round(as.numeric(dat_sum[2,])), nsmall = 0, big.mark = "'"), 
                                                   which = "column", 
                                                   rot = 90, 
                                                   just = "center",
                                              height = unit(2.3,"cm"),
                                                   location = 0.5,
                                                   gp = gpar(fontsize=16,col = "black", border = "black")))

# row_split for markers
rowData(sce_prot)$heatmap_relevance <- ""
rowData(sce_prot[rowData(sce_prot)$good_marker,])$heatmap_relevance <- "Lineage"
rowData(sce_prot[grepl("PDL1|CD11b|CD206|PARP|CXCR2|CD11c|pS6|GrzB|IDO1|CD45RA|H3K27me3|TCF7|CD45RO|PD1|pERK|ICOS|Ki67", rownames(sce_prot)),])$heatmap_relevance <- "Other"

# plot heatmap
h <- Heatmap(m, name = "Scaled Expression",
             row_split = rowData(sce_prot[rowData(sce_prot)$good_marker,])$heatmap_relevance,
             cluster_columns = TRUE,
             show_column_dend = FALSE,
             column_names_gp = gpar(fontsize=18),
             column_names_rot = 45,
             column_names_centered = FALSE,
             show_column_names = TRUE,
             row_names_gp = gpar(fontsize = 14),
             row_title_gp = gpar(fontsize = 23),
             top_annotation = ha,
             col = colorRamp2(c(-2, 0, 2), c("blue", "white", "red")),
             heatmap_legend_param = list(at = c(-2:2), legend_width = unit(6,"cm"), 
                                         direction="horizontal", title_gp = gpar(fontsize=16),title_position = "topcenter",
                                         labels_gp = gpar(fontsize=12)),
             column_names_side = "bottom",
             height = unit(17, "cm"),
             width = unit(15,"cm"))

draw(h, heatmap_legend_side = "bottom")

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Figure 1D

Load segmentation masks

all_mask <- loadImages(x = "data/full_data/protein/cpout/",
                       pattern = "ilastik_s2_Probabilities_equalized_cellmask.tiff")

add the ImageNumber to masks

# we load the metadata for the images.
image_mat <- as.data.frame(read.csv(file = "data/data_for_analysis/protein/Image.csv",stringsAsFactors = FALSE))

# we extract only the FileNames of the masks as they are in the all_masks object
cur_df <- data.frame(cellmask = image_mat$FileName_cellmask,
                     ImageNumber = image_mat$ImageNumber,
                     Description = image_mat$Metadata_Description)

# we set the rownames of the extracted data to be equal to the names of all_masks
rownames(cur_df) <- gsub(pattern = ".tiff",replacement = "",image_mat$FileName_cellmask)

# we add the extracted information via mcols in the order of the all_masks object
mcols(all_mask) <- cur_df[names(all_mask),]

scale the masks

all_mask <- scaleImages(all_mask,2^16-1)

Plot two example Images

# subset masks
mask_sub <- all_mask[mcols(all_mask)$Description %in% c("H9", "L7", "H2")]
sce_prot_sub <- sce_prot[,sce_prot$Description %in% c("H9", "L7", "H2")]

# rename all cells that are not tumor and not tcytotoxic
#sce_prot_sub$celltype <- ifelse(sce_prot_sub$celltype %in% c("Tumor", "CD8+ T cell"), sce_prot_sub$celltype, "other")

col_list <- list()
col_list$`Cell Type` <- metadata(sce_prot)$colour_vectors$celltype

sce_prot_sub$`Cell Type` <- sce_prot_sub$celltype

plotCells(mask = mask_sub, 
          object = sce_prot_sub,
          cell_id = "CellNumber", img_id = "Description", 
          colour_by = "Cell Type",
          colour = col_list,
          display = "single")

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Figure 1E

Barplot containing Cell Types per Image

# Create table with celltype fractions
cur_df <- data.frame(celltype = sce_prot$celltype,
                     Description = sce_prot$Description,
                     Location = sce_prot$Location)

# remove control samples 
cur_df <- cur_df %>%
  filter(Location != "CTRL") %>%
  group_by(Description, celltype) %>%
  summarise(n=n()) %>% 
  group_by(Description) %>%
  mutate(fraction = n / sum(n)) %>%
  reshape2::dcast(Description ~ celltype, value.var = "fraction", fill=0)

matrixrownames <- cur_df$Description 

# now we create a matrix from the data and cluster the data based on the cell fractions
hm_dat = as.matrix(cur_df[,-1])
rownames(hm_dat) <- as.character(matrixrownames)

# calculate distance and then cluster images based on cluster fraction
dd <- dist((hm_dat), method = "euclidean")
hc <- hclust(dd, method = "ward.D2")
row_sorted <- hc$labels

# now we generate the clinical metadata and order it in the same way as the celltype data
patient_meta <- metadata(sce_prot)
patient_meta <- data.frame(patient_meta[c("Description", "MM_location_simplified", "Location")])
patient_meta <- patient_meta %>%
  filter(Location != "CTRL")

mrownames <- patient_meta$Description
patient_meta <- as.matrix(patient_meta)
rownames(patient_meta) <- mrownames
patient_meta <- data.frame(patient_meta[row_sorted,])

# generate the barplot. this is generated as the annotation for the heatmap of the Patient_ID that is generated below.
hm_dat <- hm_dat[row_sorted,]

# bring cell types in order (column order)
col_order <- c("Tumor", "Macrophage", "Neutrophil", "CD8+ T cell", "CD4+ T cell", "FOXP3+ T cell", "B cell", "BnT cell", "pDC", "Stroma", "unknown")
hm_dat <- hm_dat[, col_order]

col_vector <- metadata(sce_prot)$colour_vector$celltype[colnames(hm_dat)]
col_vector_location <- structure(c("blue", "red", "green"), 
                                 names = c("LN", "other", "skin"))

# rename punch locations
patient_meta[patient_meta$Location == "M", ]$Location <- "margin"
patient_meta[patient_meta$Location == "C", ]$Location <- "core"

col_vector_punch <- structure(c("black", "grey"), 
                                 names = c("core", "margin"))

# create annotation with cell type proportions
ha <- rowAnnotation(`Punch Location` = patient_meta[,c("Location")],
                    `Cell Type Proportion` =
                      anno_barplot(hm_dat, 
                                   gp=gpar(fill=col_vector),
                                   bar_width = 1,
                                   height = unit(25,"cm"),
                                   width = unit(11,"cm"),
                                   show_row_names = FALSE),
                        col = list(`Punch Location` = col_vector_punch),
                    show_legend = FALSE)


dend <- as.dendrogram(hc)
dend <- color_branches(dend, k = 4, col = c("gray50", "blue", "green", "red"), groupLabels = TRUE) # `color_branches()` returns a dendrogram object

# heatmap consisting of the patient_IDs. one color per patient
h1 = Heatmap(patient_meta[,c("MM_location_simplified")], 
             col = col_vector_location, 
             width = unit(0.5, "cm"), 
             cluster_rows = dend,
             row_dend_width = unit(1, "cm"),
             height = unit(25, "cm"),
             show_heatmap_legend = FALSE, 
             heatmap_legend_param = list(title = "Met Location"),
             row_names_gp = gpar(cex=3),
             show_row_names = TRUE,
             right_annotation =  ha,
             column_labels = "Met Location")

# plot the data
ht = grid.grabExpr(draw(h1))
grid.newpage()
pushViewport(viewport(angle = 270))
grid.draw(ht)

Version Author Date
3697a9b toobiwankenobi 2022-02-22

Legend for Barplot

lgd1 <- Legend(labels = names(col_vector), 
             title = "Cell Type", 
             legend_gp = gpar(fill = col_vector),
             ncol = 1)

lgd2 <- Legend(labels = names(col_vector_location), 
             legend_gp = gpar(fill = unname(col_vector_location)),
             title = "Met Location",
             ncol = 1)

lgd3 <- Legend(labels = names(col_vector_punch), 
             legend_gp = gpar(fill = unname(col_vector_punch)),
             title = "Punch Location",
             ncol = 1)

pd = packLegend(lgd1, lgd2, lgd3, direction = "vertical", 
    column_gap = unit(0.5, "cm"))
draw(pd)

Version Author Date
3697a9b toobiwankenobi 2022-02-22

sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.3 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=en_US.UTF-8   
 [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      stats4    stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] dendextend_1.15.2           ggbeeswarm_0.6.0           
 [3] circlize_0.4.13             ggrepel_0.9.1              
 [5] cytomapper_1.6.0            EBImage_4.36.0             
 [7] rms_6.2-0                   SparseM_1.81               
 [9] Hmisc_4.6-0                 Formula_1.2-4              
[11] survival_3.2-13             lattice_0.20-45            
[13] forcats_0.5.1               stringr_1.4.0              
[15] purrr_0.3.4                 readr_2.1.2                
[17] tidyr_1.2.0                 tibble_3.1.6               
[19] tidyverse_1.3.1             reshape2_1.4.4             
[21] dplyr_1.0.7                 ComplexHeatmap_2.10.0      
[23] dittoSeq_1.6.0              scater_1.22.0              
[25] ggplot2_3.3.5               scuttle_1.4.0              
[27] data.table_1.14.2           SingleCellExperiment_1.16.0
[29] SummarizedExperiment_1.24.0 Biobase_2.54.0             
[31] GenomicRanges_1.46.1        GenomeInfoDb_1.30.1        
[33] IRanges_2.28.0              S4Vectors_0.32.3           
[35] BiocGenerics_0.40.0         MatrixGenerics_1.6.0       
[37] matrixStats_0.61.0          workflowr_1.7.0            

loaded via a namespace (and not attached):
  [1] shinydashboard_0.7.2      utf8_1.2.2               
  [3] tidyselect_1.1.1          htmlwidgets_1.5.4        
  [5] BiocParallel_1.28.3       munsell_0.5.0            
  [7] ScaledMatrix_1.2.0        codetools_0.2-18         
  [9] withr_2.4.3               colorspace_2.0-2         
 [11] highr_0.9                 knitr_1.37               
 [13] rstudioapi_0.13           git2r_0.29.0             
 [15] GenomeInfoDbData_1.2.7    pheatmap_1.0.12          
 [17] rhdf5_2.38.0              rprojroot_2.0.2          
 [19] vctrs_0.3.8               generics_0.1.2           
 [21] TH.data_1.1-0             xfun_0.29                
 [23] R6_2.5.1                  doParallel_1.0.16        
 [25] clue_0.3-60               rsvd_1.0.5               
 [27] locfit_1.5-9.4            rhdf5filters_1.6.0       
 [29] bitops_1.0-7              DelayedArray_0.20.0      
 [31] assertthat_0.2.1          promises_1.2.0.1         
 [33] scales_1.1.1              multcomp_1.4-18          
 [35] nnet_7.3-17               beeswarm_0.4.0           
 [37] gtable_0.3.0              beachmat_2.10.0          
 [39] processx_3.5.2            sandwich_3.0-1           
 [41] rlang_1.0.0               MatrixModels_0.5-0       
 [43] systemfonts_1.0.3         GlobalOptions_0.1.2      
 [45] splines_4.1.2             broom_0.7.12             
 [47] checkmate_2.0.0           yaml_2.2.2               
 [49] abind_1.4-5               modelr_0.1.8             
 [51] backports_1.4.1           httpuv_1.6.5             
 [53] tools_4.1.2               ellipsis_0.3.2           
 [55] raster_3.5-15             jquerylib_0.1.4          
 [57] RColorBrewer_1.1-2        ggridges_0.5.3           
 [59] Rcpp_1.0.8                plyr_1.8.6               
 [61] base64enc_0.1-3           sparseMatrixStats_1.6.0  
 [63] zlibbioc_1.40.0           RCurl_1.98-1.5           
 [65] ps_1.6.0                  rpart_4.1.16             
 [67] GetoptLong_1.0.5          viridis_0.6.2            
 [69] cowplot_1.1.1             zoo_1.8-9                
 [71] haven_2.4.3               cluster_2.1.2            
 [73] fs_1.5.2                  magrittr_2.0.2           
 [75] magick_2.7.3              reprex_2.0.1             
 [77] mvtnorm_1.1-3             whisker_0.4              
 [79] xtable_1.8-4              mime_0.12                
 [81] hms_1.1.1                 evaluate_0.14            
 [83] fftwtools_0.9-11          jpeg_0.1-9               
 [85] readxl_1.3.1              gridExtra_2.3            
 [87] shape_1.4.6               compiler_4.1.2           
 [89] crayon_1.4.2              htmltools_0.5.2          
 [91] later_1.3.0               tzdb_0.2.0               
 [93] tiff_0.1-11               lubridate_1.8.0          
 [95] DBI_1.1.2                 dbplyr_2.1.1             
 [97] MASS_7.3-55               Matrix_1.4-0             
 [99] cli_3.1.1                 parallel_4.1.2           
[101] pkgconfig_2.0.3           getPass_0.2-2            
[103] sp_1.4-6                  foreign_0.8-82           
[105] terra_1.5-17              xml2_1.3.3               
[107] foreach_1.5.2             svglite_2.0.0            
[109] vipor_0.4.5               bslib_0.3.1              
[111] XVector_0.34.0            rvest_1.0.2              
[113] callr_3.7.0               digest_0.6.29            
[115] rmarkdown_2.11            cellranger_1.1.0         
[117] htmlTable_2.4.0           DelayedMatrixStats_1.16.0
[119] shiny_1.7.1               quantreg_5.87            
[121] rjson_0.2.21              lifecycle_1.0.1          
[123] nlme_3.1-155              jsonlite_1.7.3           
[125] Rhdf5lib_1.16.0           BiocNeighbors_1.12.0     
[127] viridisLite_0.4.0         fansi_1.0.2              
[129] pillar_1.7.0              fastmap_1.1.0            
[131] httr_1.4.2                glue_1.6.1               
[133] svgPanZoom_0.3.4          png_0.1-7                
[135] iterators_1.0.13          HDF5Array_1.22.1         
[137] stringi_1.7.6             sass_0.4.0               
[139] polspline_1.1.19          BiocSingular_1.10.0      
[141] latticeExtra_0.6-29       irlba_2.3.5