Last updated: 2021-02-10

Checks: 7 0

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.


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 2e443a5. 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:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    ._.DS_Store
    Ignored:    code/.DS_Store
    Ignored:    code/._.DS_Store
    Ignored:    code/helper_functions/._findCommunity.R
    Ignored:    data/.DS_Store
    Ignored:    data/._.DS_Store
    Ignored:    data/._layer_1_classification_rna.csv
    Ignored:    data/._survdat_for_modelling.csv
    Ignored:    data/12plex_validation/
    Ignored:    data/200323_TMA_256_Hot Cold_Clinical Data_Updated Response Data_For Collaborators_latest updated_Mar_2020_for_Coxph_modeling.csv
    Ignored:    data/layer_1_classification_protein.csv
    Ignored:    data/layer_1_classification_rna.csv
    Ignored:    data/manual_infiltration/
    Ignored:    data/protein/
    Ignored:    data/rna/
    Ignored:    data/safety_copy_SCE/
    Ignored:    data/sce_RNA.rds
    Ignored:    data/sce_protein.rds
    Ignored:    data/survdat_for_modelling.csv
    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/04_1_Protein_celltype_classification.rmd
    Modified:   analysis/04_1_RNA_celltype_classification.rmd
    Deleted:    code/findPackages.R

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_4.rmd) and HTML (docs/Figure_4.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 2e443a5 toobiwankenobi 2021-02-09 remove files that are not needed
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 73caa28 toobiwankenobi 2021-01-12 minor corrections
Rmd 545c207 toobiwankenobi 2020-12-22 clean up branch
Rmd 58c40e5 toobiwankenobi 2020-10-19 correct files that don’t work
Rmd 1af3353 toobiwankenobi 2020-10-16 add stuff
Rmd a6b51cd toobiwankenobi 2020-10-14 clean scripts, add new subfigures
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 4.

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/findClusters.R
value   ?                                   
visible FALSE                               
        code/helper_functions/findCommunity.R
value   ?                                    
visible FALSE                                
        code/helper_functions/getCellCount.R
value   ?                                   
visible FALSE                               
        code/helper_functions/getInfoFromString.R
value   ?                                        
visible FALSE                                    
        code/helper_functions/getSpotnumber.R
value   ?                                    
visible FALSE                                
        code/helper_functions/plotBarFracCluster.R
value   ?                                         
visible FALSE                                     
        code/helper_functions/plotCellCounts.R
value   ?                                     
visible FALSE                                 
        code/helper_functions/plotCellFrac.R
value   ?                                   
visible FALSE                               
        code/helper_functions/plotCellFracGroups.R
value   ?                                         
visible FALSE                                     
        code/helper_functions/plotCellFracGroupsSubset.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(SingleCellExperiment)
library(reshape2)
library(tidyverse)
library(dplyr)
library(data.table) 
library(ggplot2)
library(cba)
library(ComplexHeatmap)
library(colorRamps)
library(circlize)
library(RColorBrewer)
library(ggpubr)
library(ggbeeswarm)
library(gridExtra)
library(tidyr)
library(ggpmisc)
library(circlize)
library(coxme)
library(dittoSeq)
library(scater)
library(cowplot)
library(survminer)
library(ggalluvial)
library(cytomapper)
library(ggrepel)
library(rstatix)

Read the data

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

# meta data
dat_relation = fread(file = "data/protein/Object relationships.csv",stringsAsFactors = FALSE)
dat_relation_rna = fread(file = "data/RNA/Object relationships.csv",stringsAsFactors = FALSE)

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

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

Prepare Relation Data Protein

# prepare data and add cellID
dat_relation$cellID_first <- paste("protein", paste(dat_relation$`First Image Number`, dat_relation$`First Object Number`, sep = "_"), sep = "_")
dat_relation$cellID_second <- paste("protein", paste(dat_relation$`Second Image Number`, dat_relation$`Second Object Number`, sep = "_"), sep = "_")

# add celltype status to first and second label
celltype_first <- data.frame(colData(sce_prot))[,c("cellID", "celltype", "celltype_clustered")]
colnames(celltype_first) <- c("cellID_first", "celltype_first", "celltype_clust_first")
celltype_second <- data.frame(colData(sce_prot))[,c("cellID", "celltype", "celltype_clustered")]
colnames(celltype_second) <- c("cellID_second", "celltype_second", "celltype_clust_second")

dat_relation <- left_join(dat_relation, celltype_first, by = "cellID_first")
dat_relation <- left_join(dat_relation, celltype_second, by = "cellID_second")

colnames(dat_relation)[5] <- "FirstImageNumber"

Prepare Relation Data RNA

# prepare data and add cellID
dat_relation_rna$cellID_first <- paste("RNA", paste(dat_relation_rna$`First Image Number`, dat_relation_rna$`First Object Number`, sep = "_"), sep = "_")
dat_relation_rna$cellID_second <- paste("RNA", paste(dat_relation_rna$`Second Image Number`, dat_relation_rna$`Second Object Number`, sep = "_"), sep = "_")

# add celltype status to first and second label
celltype_first <- data.frame(colData(sce_rna))[,c("cellID", "celltype_rf", "celltype_clustered")]
colnames(celltype_first) <- c("cellID_first", "celltype_first", "celltype_clust_first")
celltype_second <- data.frame(colData(sce_rna))[,c("cellID", "celltype_rf", "celltype_clustered")]
colnames(celltype_second) <- c("cellID_second", "celltype_second", "celltype_clust_second")

dat_relation_rna <- left_join(dat_relation_rna, celltype_first, by = "cellID_first")
dat_relation_rna <- left_join(dat_relation_rna, celltype_second, by = "cellID_second")

colnames(dat_relation_rna)[5] <- "FirstImageNumber"

Figure 4A

Tumor Marker Profile for different Tcell Scoring Groups

tumor_marker_protein <- c("pS6", "H3K27me3", "HLADR", "PDL1", "IDO1")
tumor_marker_rna <- c("B2M")

# rna data 
dat_rna <- data.frame(t(assay(sce_rna[tumor_marker_rna, sce_rna$celltype == "Tumor"], "asinh")))
dat_rna$cellID <- rownames(dat_rna)
dat_rna <- left_join(dat_rna, data.frame(colData(sce_rna))[,c("cellID", "Tcell_density_score_image", "Description", "MM_location", "Location")])

# filter
dat_rna <- dat_rna %>%
  filter(Location != "CTRL")

# mean per image
dat_rna <- dat_rna %>%
  select(-cellID) %>%
  group_by(Description, Tcell_density_score_image) %>%
  summarise_if(is.numeric, mean, na.rm = TRUE)

# melt
dat_rna <- dat_rna %>%
  reshape2::melt(id.vars = c("Description", "Tcell_density_score_image"), variable.name = "channel", value.name = "asinh")

# protein data
dat_prot <- data.frame(t(assay(sce_prot[tumor_marker_protein,, sce_prot$celltype == "Tumor"], "asinh")))
dat_prot$cellID <- rownames(dat_prot)
dat_prot <- left_join(dat_prot, data.frame(colData(sce_prot))[,c("cellID", "Tcell_density_score_image", "Description", "MM_location", "Location")])

# filter
dat_prot <- dat_prot %>%
  filter(Location != "CTRL")

# mean per image
dat_prot <- dat_prot %>%
  select(-cellID) %>%
  group_by(Description, Tcell_density_score_image) %>%
  summarise_if(is.numeric, mean, na.rm = TRUE)

# melt
dat_prot <- dat_prot %>%
  reshape2::melt(id.vars = c("Description", "Tcell_density_score_image"), variable.name = "channel", value.name = "asinh")

# join both data sets
comb <- rbind(dat_prot, dat_rna)


# adjusted wilcox.test for groups
group_comparison <- list(c("absent", "high"), c("med", "high"))

stat.test <- comb %>%
  group_by(channel) %>%
  wilcox_test(data = ., asinh ~ Tcell_density_score_image) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj") %>%
  add_xy_position(x = "Tcell_density_score_image", dodge = 0.8, comparisons = group_comparison) %>%
  filter(is.na(y.position) == FALSE)

# plot 
p <- ggplot(comb, aes(x=Tcell_density_score_image, y=asinh, 
                      group=Tcell_density_score_image)) + 
  geom_boxplot(alpha=0.2, lwd=1, aes(group=Tcell_density_score_image, fill = Tcell_density_score_image)) +
  facet_wrap(~channel, scales = "free", ncol=3) + 
  stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 7) + 
  geom_quasirandom(alpha=0.6, size=2, aes(group=Tcell_density_score_image, col = Tcell_density_score_image)) +
  scale_color_discrete(guide = FALSE) +
  theme_bw() +
  theme(text = element_text(size=18),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank()) +
  xlab("") + 
  ylab("Mean Count per Image (asinh)") +
  scale_y_continuous(expand = expansion(mult = c(0.05, 0.15))) +
  guides(fill=guide_legend(title="Tcell Score", override.aes = c(lwd=0.5, alpha=1)))

leg <- get_legend(p)

grid.arrange(p + theme(legend.position = "none"))
grid.arrange(leg)

Figure 4B

Load masks

all_mask <- loadImages(x = "/home/ubuntu/bbvolume/Data/Analysis/melanoma_cohort_new_cp_pipeline/rna/cpout/",
                       pattern = "ilastik_s2_Probabilities_equalized_cellmask.tiff")

add the ImageNumber to masks

# we load the metadata for the images.
image_mat_rna <- as.data.frame(read.csv(file = "data/rna/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_rna$FileName_cellmask,
                     ImageNumber = image_mat_rna$ImageNumber,
                     Description = image_mat_rna$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_rna$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("L11", "N3")]
sce_rna_sub <- sce_rna[,sce_rna$Description %in% c("L11", "N3")]

plotCells(mask = mask_sub, 
          object = sce_rna_sub,
          img_id = "Description", cell_id = "CellNumber",
          colour_by = c("CD8", "Mart1", "SOX10", "B2M"),
          colour = list(CD8 = c("black", "green"),
                        Mart1 = c("black", "blue"),
                        SOX10 = c("black", "blue"),
                        B2M = c("black", "red")),
          display = "single",
          exprs_values = "scaled_asinh",
          scale = TRUE)

Figure 4C

Correlation with mean B2M expression and T cell density

tumor_dat <- data.frame(t(assay(sce_rna["B2M", sce_rna$celltype == "Tumor" & sce_rna$Location != "CTRL"], "asinh")))
tumor_dat$Description <- sce_rna[, sce_rna$celltype == "Tumor" & sce_rna$Location != "CTRL"]$Description

tumor_dat <- tumor_dat %>%
  group_by(Description) %>%
  summarise(mean_B2M = mean(B2M))

cur_df <- data.frame(colData(sce_rna)) %>%
  filter(Location != "CTRL") %>%
  group_by(Description, BlockID, celltype) %>%
  summarise(n=n()) %>%
  mutate(fraction = n/sum(n)) %>%
  ungroup() %>%
  complete(Description, celltype, fill = list(fraction = 0)) %>%
  filter(celltype == "Tcytotoxic")

cur_df_chemokine <- data.frame(colData(sce_rna)) %>%
  filter(Location != "CTRL") %>%
  group_by(Description, chemokine) %>%
  summarise(n=n()) %>%
  reshape2::dcast(Description ~ chemokine, value.var = "n", fill = 0) %>%
  mutate(fraction_positive = `TRUE` / (`FALSE` + `TRUE`))
  
tumor_dat <- left_join(tumor_dat, cur_df)
tumor_dat_chemokine <- left_join(tumor_dat, cur_df_chemokine)

# remove bad images and controls
tumor_dat <- tumor_dat
tumor_dat_chemokine <- tumor_dat_chemokine

# boxplot
a <- ggplot(tumor_dat, aes(y=mean_B2M, x=log10(fraction))) + 
  geom_point(size=3) +
  geom_smooth(method = "lm", formula = y ~ poly(x,2)) +
  stat_poly_eq(formula = y ~ poly(x,2), 
                aes(label =  ..rr.label..), 
                parse = TRUE, size=10) +
  ylab("Mean B2M Expression (asinh)") +
  xlab("Cytotoxic T cell Fraction (log10)") +
  theme_bw() + 
  theme(text = element_text(size=18))

b <- ggplot(tumor_dat_chemokine, aes(y=mean_B2M, x=log10(fraction_positive))) + 
  geom_point(size=3) +
  geom_smooth(method = "lm", formula = y~poly(x,2)) +
  stat_poly_eq(formula = y ~ poly(x,2), 
                aes(label =  ..rr.label..), 
                parse = TRUE, size=10) +
  ylab("Mean B2M Expression (asinh)") +
  xlab("Chemokine-Expressing Cell Fraction (log10)") +
  theme_bw() + 
  theme(text = element_text(size=18))

grid.arrange(a,b, nrow=1)
Warning: Removed 6 rows containing non-finite values (stat_smooth).
Warning: Removed 6 rows containing non-finite values (stat_poly_eq).

Figure 4D

Interaction between Dysfunctional CD8 and Tumor Cells

# number of interactions tcytotoxic and tumor per image
dat_relation_sub <- dat_relation_rna[dat_relation_rna$celltype_first %in% c("exhausted Tcytotoxic", "Tcytotoxic") & 
                                   dat_relation_rna$celltype_second == "Tumor"]

# count number of interactions
count <- dat_relation_sub %>%
  group_by(FirstImageNumber) %>%
  summarise(n=n())
names(count)[1] <- "ImageNumber"

# fraction of exhausted cd8 per image
dysfunction <- data.frame(colData(sce_rna)) %>%
  mutate(celltype2 = paste(celltype, CXCL13, sep = "_")) %>%
  group_by(ImageNumber, celltype2) %>%
  summarise(n=n()) %>%
  reshape2::dcast(ImageNumber ~ celltype2, value.var = "n", fill = 0) %>%
  reshape2::melt(id.vars = c("ImageNumber"), variable.name = "celltype2", value.name = "n") %>%
  group_by(ImageNumber) %>%
  mutate(fraction = n / sum(n)) %>%
  filter(celltype2 == "Tcytotoxic_1") %>%
  ungroup() %>%
  select(ImageNumber, fraction)

# correlation plot
cur_dat <- left_join(count, dysfunction)

ggplot(cur_dat, aes(x=log10(fraction), y=log10(n))) + 
  geom_point(size=3) + 
  geom_smooth(method="lm") +
  stat_poly_eq(formula = y ~ x, 
                aes(label =  ..rr.label..), 
                parse = TRUE, size=10) +
  theme_bw() +
  theme(text = element_text(size=14)) +
  xlab("Fraction of Dysfunctional Cytotoxic T Cells (log10)") +
  ylab("Number of CD8/Tumor Interactions\n(log10)")
Warning: Removed 59 rows containing non-finite values (stat_smooth).
Warning: Removed 59 rows containing non-finite values (stat_poly_eq).

Figure 4E

Boxplots with interaction counts per Image

# add dysfunction score to dat_relation
ex_score <- data.frame(colData(sce_prot)) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  select(ImageNumber, dysfunction_score, MM_location)

ex_score$FirstImageNumber <- ex_score$ImageNumber

dat_relation <- left_join(dat_relation, ex_score[,c("FirstImageNumber", "dysfunction_score", "MM_location")])

sum <- dat_relation %>%
  filter(celltype_first == "Tcytotoxic" & celltype_second == "Tumor" & !is.na(dysfunction_score)) %>%
  group_by(FirstImageNumber, MM_location, dysfunction_score, celltype_first, celltype_clust_second) %>%
  summarise(n=n()) %>%
  reshape2::dcast(FirstImageNumber + MM_location + dysfunction_score + celltype_first ~ celltype_clust_second, value.var = "n", fill=0) %>%
  reshape2::melt(id.vars = c("FirstImageNumber", "MM_location", "dysfunction_score", "celltype_first"), variable.name = "celltype", value.name = "n")

#sum <- sum[sum$MM_location == "skin_subcutaneous",]

# calculate fractions for every image (makes it more comparable)
sum2 <- sum %>%
  group_by(FirstImageNumber) %>%
  mutate(fraction = n/sum(n)) %>%
  ungroup()

stat.test <- sum2 %>%
  group_by(celltype) %>%
  wilcox_test(data = ., fraction ~ dysfunction_score) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj") %>%
  add_x_position(x = "celltype", dodge = 0.8)

ggplot(sum2, aes(x=celltype, y=fraction)) +
  geom_boxplot(alpha=.2, lwd=1, aes(fill = dysfunction_score)) +
  geom_quasirandom(alpha=.6, dodge.width=.75, size=2, aes(group = dysfunction_score, col=dysfunction_score)) +
  stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 7, y.position = 0.9) + 
  scale_color_discrete(guide = FALSE) +
  theme_bw() +
  theme(text = element_text(size = 16),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
  guides(fill=guide_legend(title="Dysfunction Score", override.aes = aes(lwd=0.5))) +
  xlab("") + 
  ylab("Fraction of Interactions") +
  ylim(0,1)

Figure 4F

Tumor Marker Profile for different Scoring Groups per Image

tumor_marker_protein <- c("S100", "MiTF")
tumor_marker_rna <- c("Mart1", "pRB")

# rna data 
dat_rna <- data.frame(t(assay(sce_rna[tumor_marker_rna, sce_rna$celltype == "Tumor"], "asinh")))
dat_rna$cellID <- rownames(dat_rna)
dat_rna <- left_join(dat_rna, data.frame(colData(sce_rna))[,c("cellID", "dysfunction_score", "Description", "MM_location")])

# filter
dat_rna <- dat_rna %>%
  filter(dysfunction_score %in% c("high dysfunction", "low dysfunction"))

# mean per image
dat_rna <- dat_rna %>%
  select(-cellID) %>%
  group_by(Description, dysfunction_score) %>%
  summarise_if(is.numeric, mean, na.rm = TRUE)

# melt
dat_rna <- dat_rna %>%
  reshape2::melt(id.vars = c("Description", "dysfunction_score"), variable.name = "channel", value.name = "asinh")

# protein data
dat_prot <- data.frame(t(assay(sce_prot[tumor_marker_protein,, sce_prot$celltype == "Tumor"], "asinh")))
dat_prot$cellID <- rownames(dat_prot)
dat_prot <- left_join(dat_prot, data.frame(colData(sce_prot))[,c("cellID", "dysfunction_score", "Description", "MM_location")])

# filter
dat_prot <- dat_prot %>%
  filter(dysfunction_score %in% c("high dysfunction", "low dysfunction"))

# mean per image
dat_prot <- dat_prot %>%
  select(-cellID) %>%
  group_by(Description, dysfunction_score) %>%
  summarise_if(is.numeric, mean, na.rm = TRUE)

# melt
dat_prot <- dat_prot %>%
  reshape2::melt(id.vars = c("Description", "dysfunction_score"), variable.name = "channel", value.name = "asinh")

# join both data sets
comb <- rbind(dat_prot, dat_rna)

stat.test <- comb %>%
  group_by(channel) %>%
  wilcox_test(data = ., asinh ~ dysfunction_score) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj") %>%
  add_xy_position(x = "celltype", dodge = 0.8)

# plot 
ggplot(comb, aes(x=dysfunction_score, y=asinh)) + 
  geom_boxplot(alpha=0.2, lwd=1, aes(fill=dysfunction_score)) +
  geom_quasirandom(alpha=0.6, size=3, aes(col=dysfunction_score)) +
  scale_color_discrete(guide = FALSE) +
  theme_bw() +
  theme(text = element_text(size=18),
        legend.position = "none") +
  facet_wrap(~channel, scales = "free") + 
  stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 7) + 
  ylab("Mean Expression (asinh)") + 
  xlab("") +
  scale_y_continuous(expand = expansion(mult = c(0.05, 0.2)))

Figure 4G

S100 and T Cell Dysfunction

# fraction of exhausted cd8 per image
dysfunction <- data.frame(colData(sce_rna)) %>%
  mutate(celltype2 = paste(celltype, CXCL13, sep = "_")) %>%
  group_by(ImageNumber, celltype2) %>%
  summarise(n=n()) %>%
  reshape2::dcast(ImageNumber ~ celltype2, value.var = "n", fill = 0) %>%
  reshape2::melt(id.vars = c("ImageNumber"), variable.name = "celltype2", value.name = "n") %>%
  group_by(ImageNumber) %>%
  mutate(fraction = n / sum(n)) %>%
  filter(celltype2 == "Tcytotoxic_1") %>%
  ungroup() %>%
  select(ImageNumber, fraction)

# rna data 
dat_rna <- data.frame(t(assay(sce_rna["S100", sce_rna$celltype == "Tumor"], "asinh")))
dat_rna$cellID <- rownames(dat_rna)
dat_rna <- left_join(dat_rna, data.frame(colData(sce_rna))[,c("cellID", "ImageNumber")])

# mean per image
dat_rna <- dat_rna %>%
  select(-cellID) %>%
  group_by(ImageNumber) %>%
  summarise_if(is.numeric, mean, na.rm = TRUE)

# melt
dat_rna <- dat_rna %>%
  reshape2::melt(id.vars = c("ImageNumber"), variable.name = "channel", value.name = "asinh")

# correlation plot
cur_dat <- left_join(dysfunction, dat_rna)

# high density images
cur_dat <- cur_dat[cur_dat$ImageNumber %in% unique(sce_rna[,colData(sce_rna)$dysfunction_score %in% c("high dysfunction", "low dysfunction")]$ImageNumber),]

ggplot(cur_dat, aes(x=asinh, y=log10(fraction))) + 
  geom_point(size=3) + 
  geom_smooth(method="lm") +
  stat_poly_eq(formula = y ~ x, 
                aes(label =  ..rr.label..), 
                parse = TRUE, size=10) +
  theme_bw() +
  theme(text = element_text(size=15)) +
  xlab("Mean S100 (asinh)") +
  ylab("Fraction of Dysfunctional T cells\n(log10)")
Warning: Removed 1 rows containing non-finite values (stat_smooth).
Warning: Removed 1 rows containing non-finite values (stat_poly_eq).

Figure 4H

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(Internal_pat_ID, .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

Celltypes Clustered in Responder vs. Non-Responder

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",]

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") %>%
  group_by(PatientID,BlockID, Description, bcell_patch_score, celltype_clustered) %>%
  summarise(n=n()) %>% 
  reshape2::dcast(PatientID + BlockID + Description + bcell_patch_score ~ celltype_clustered, value.var = "n", fill=0) %>%
  reshape2::melt(id.vars = c("PatientID","BlockID", "Description", "bcell_patch_score"), 
                 variable.name = "celltype", value.name = "n") %>%
  group_by(Description) %>%
  mutate(fraction = n/sum(n)) %>%
  mutate(total_cells = sum(n)) %>%
  ungroup() %>%
  filter(celltype %in% c("Tumor_1", "Tumor_9"))

cur_dat <- left_join(cur_dat, dat_survival_prot_sub[,c("BlockID", "Status_at_3m", "Primary_melanoma_type")]) %>%
  distinct(Description, celltype, .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

stat.test <- cur_dat %>%
  group_by(celltype) %>%
  mutate(y_log10 = log10(n_per_mm2+1)) %>%
  wilcox_test(data = ., y_log10 ~ Status_at_3m) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj") %>%
  add_xy_position(x = "Status_at_3m", dodge = 0.8)

ggplot(cur_dat, aes(x=Status_at_3m, y=log10(n_per_mm2+1), group = Status_at_3m, label=PatientID)) + 
  geom_boxplot(alpha=.4, outlier.shape = NA, aes(fill=Status_at_3m)) +
  geom_beeswarm(size=3) +
  stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 6) + 
  geom_label_repel(aes(group=Status_at_3m , label=PatientID), max.overlaps = 12, size = 5, alpha=.5) + 
  theme_bw() +
  theme(text = element_text(size=18),
        legend.position = "none") +
  ylab("Cells per mm2 (log10)") +
  xlab("") +
  guides(fill=guide_legend(title="Response 3m", override.aes = c(lwd=0.5, size=1))) +
  facet_wrap(~celltype, scales = "free") +
  scale_y_continuous(expand = c(0.1, 0))
Warning: Duplicated aesthetics after name standardisation: size
Warning: ggrepel: 7 unlabeled data points (too many overlaps). Consider
increasing max.overlaps

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] cytomapper_1.3.1            EBImage_4.32.0             
 [5] ggalluvial_0.12.3           survminer_0.4.8            
 [7] cowplot_1.1.1               scater_1.16.2              
 [9] dittoSeq_1.0.2              coxme_2.2-16               
[11] bdsmatrix_1.3-4             survival_3.2-7             
[13] ggpmisc_0.3.7               gridExtra_2.3              
[15] ggbeeswarm_0.6.0            ggpubr_0.4.0               
[17] RColorBrewer_1.1-2          circlize_0.4.12            
[19] colorRamps_2.3              ComplexHeatmap_2.4.3       
[21] cba_0.2-21                  proxy_0.4-24               
[23] data.table_1.13.6           forcats_0.5.0              
[25] stringr_1.4.0               dplyr_1.0.2                
[27] purrr_0.3.4                 readr_1.4.0                
[29] tidyr_1.1.2                 tibble_3.0.4               
[31] ggplot2_3.3.3               tidyverse_1.3.0            
[33] reshape2_1.4.4              SingleCellExperiment_1.12.0
[35] SummarizedExperiment_1.20.0 Biobase_2.50.0             
[37] GenomicRanges_1.42.0        GenomeInfoDb_1.26.2        
[39] IRanges_2.24.1              S4Vectors_0.28.1           
[41] BiocGenerics_0.36.0         MatrixGenerics_1.2.0       
[43] matrixStats_0.57.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] BiocParallel_1.22.0       munsell_0.5.0            
  [7] codetools_0.2-18          withr_2.3.0              
  [9] colorspace_2.0-0          knitr_1.30               
 [11] rstudioapi_0.13           ggsignif_0.6.0           
 [13] labeling_0.4.2            git2r_0.28.0             
 [15] GenomeInfoDbData_1.2.4    KMsurv_0.1-5             
 [17] farver_2.0.3              pheatmap_1.0.12          
 [19] rprojroot_2.0.2           vctrs_0.3.6              
 [21] generics_0.1.0            xfun_0.20                
 [23] R6_2.5.0                  clue_0.3-58              
 [25] rsvd_1.0.3                locfit_1.5-9.4           
 [27] bitops_1.0-6              DelayedArray_0.16.0      
 [29] assertthat_0.2.1          promises_1.1.1           
 [31] scales_1.1.1              beeswarm_0.2.3           
 [33] gtable_0.3.0              rlang_0.4.10             
 [35] systemfonts_0.3.2         GlobalOptions_0.1.2      
 [37] splines_4.0.3             broom_0.7.3              
 [39] yaml_2.2.1                abind_1.4-5              
 [41] modelr_0.1.8              backports_1.2.1          
 [43] httpuv_1.5.4              tools_4.0.3              
 [45] ellipsis_0.3.1            raster_3.4-5             
 [47] polynom_1.4-0             ggridges_0.5.3           
 [49] Rcpp_1.0.5                plyr_1.8.6               
 [51] zlibbioc_1.36.0           RCurl_1.98-1.2           
 [53] GetoptLong_1.0.5          viridis_0.5.1            
 [55] zoo_1.8-8                 haven_2.3.1              
 [57] cluster_2.1.0             fs_1.5.0                 
 [59] magrittr_2.0.1            openxlsx_4.2.3           
 [61] reprex_0.3.0              whisker_0.4              
 [63] hms_0.5.3                 mime_0.9                 
 [65] evaluate_0.14             fftwtools_0.9-9          
 [67] xtable_1.8-4              rio_0.5.16               
 [69] jpeg_0.1-8.1              readxl_1.3.1             
 [71] shape_1.4.5               compiler_4.0.3           
 [73] crayon_1.3.4              htmltools_0.5.0          
 [75] mgcv_1.8-33               later_1.1.0.1            
 [77] tiff_0.1-6                lubridate_1.7.9.2        
 [79] DBI_1.1.0                 dbplyr_2.0.0             
 [81] Matrix_1.3-2              car_3.0-10               
 [83] cli_2.2.0                 pkgconfig_2.0.3          
 [85] km.ci_0.5-2               foreign_0.8-81           
 [87] sp_1.4-5                  xml2_1.3.2               
 [89] svglite_1.2.3.2           vipor_0.4.5              
 [91] XVector_0.30.0            rvest_0.3.6              
 [93] digest_0.6.27             rmarkdown_2.6            
 [95] cellranger_1.1.0          survMisc_0.5.5           
 [97] edgeR_3.30.3              DelayedMatrixStats_1.10.1
 [99] gdtools_0.2.3             curl_4.3                 
[101] shiny_1.5.0               rjson_0.2.20             
[103] lifecycle_0.2.0           nlme_3.1-151             
[105] jsonlite_1.7.2            carData_3.0-4            
[107] BiocNeighbors_1.6.0       viridisLite_0.3.0        
[109] limma_3.44.3              fansi_0.4.1              
[111] pillar_1.4.7              lattice_0.20-41          
[113] fastmap_1.0.1             httr_1.4.2               
[115] glue_1.4.2                zip_2.1.1                
[117] png_0.1-7                 svgPanZoom_0.3.4         
[119] stringi_1.5.3             BiocSingular_1.4.0       
[121] irlba_2.3.3