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/Figure_5.rmd) and HTML (docs/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 c3e8a47 toobiwankenobi 2020-10-12 clean branch
Rmd 2c11d5c toobiwankenobi 2020-08-05 add new scripts

Introduction

This script generates plots for Figure 5.

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(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(corrplot)
library(ggridges)
library(rstatix)
library(sf)
library(concaveman)
library(RANN)

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")

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

# image
image_mat_rna <- read.csv("data/data_for_analysis/rna/Image.csv")

# surv_dat
dat_survival_prot <- fread(file = "data/data_for_analysis/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 5A

Generate adjacency matrix for all images

# subset sce for inflamed/exhausted in high samples
sce_protein_sub <- sce_prot[, sce_prot$dysfunction_density %in% c("high - High Dysfunction", "high - Low Dysfunction")]

# sample 9 images each
images <- data.frame(colData(sce_protein_sub)) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  group_by(dysfunction_density) %>%
  #filter(ImageNumber %in% sample(ImageNumber, 9)) %>%
  select(ImageNumber, dysfunction_density)

return <- list()

for (i in c("high - High Dysfunction", "high - Low Dysfunction")){
  # title name
  title_name <- i

  # count interactions in 20 sample images
  cur_dat_relation <- data.frame(dat_relation) %>%
    filter(FirstImageNumber %in% images[images$dysfunction_density == i,]$ImageNumber) %>%
    select("celltype_first" ,"celltype_second") %>%
    dplyr::count(celltype_first,celltype_second) %>%
    data.frame()
  
  # remove tumor-tumor interactions
  cur_dat_relation <- cur_dat_relation[cur_dat_relation$celltype_first != "Tumor",]
  cur_dat_relation <- cur_dat_relation[cur_dat_relation$celltype_first != "unknown",]
  cur_dat_relation <- cur_dat_relation[cur_dat_relation$celltype_second != "unknown",]
  
    # count interactions
  cur_dat_relation_subcluster <- data.frame(dat_relation) %>%
    filter(FirstImageNumber %in% images[images$dysfunction_density == i,]$ImageNumber) %>%
    select("celltype_first" , "celltype_clust_second") %>%
    dplyr::count(celltype_first, celltype_clust_second) %>%
    data.frame()
  
  # remove tumor-tumor interactions
  cur_dat_relation_subcluster <- cur_dat_relation_subcluster[cur_dat_relation_subcluster$celltype_first == "CD8+ T cell",]
  cur_dat_relation_subcluster <- cur_dat_relation_subcluster[cur_dat_relation_subcluster$celltype_clust_second %in% 
                                                               unique(sce_prot[,sce_prot$celltype == "Tumor"]$celltype_clustered),]
  # return subcluster adj df
  return[[i]] <- cur_dat_relation_subcluster
  
  # make coord diagram
  chordDiagramFromDataFrame(cur_dat_relation,
                            grid.col = metadata(sce_prot)$colour_vectors$celltype,
                            reduce = 0.05, 
                            transparency = ifelse(cur_dat_relation[[1]] %in% c("CD8+ T cell"),0,0.6),
                            annotationTrack = c("grid"))
  
  # add percentages
#   circos.track(track.index = 1, panel.fun = function(x, y) {
#     xlim = get.cell.meta.data("xlim")
#     ylim = get.cell.meta.data("ylim")
#     sector.name = get.cell.meta.data("sector.index")
#     xplot = get.cell.meta.data("xplot")
#     
#     circos.lines(xlim, c(mean(ylim), mean(ylim)), lty = 3) # dotted line
#     by = ifelse(abs(xplot[2] - xplot[1]) > 30, 0.2, 0.5)
#     for(p in seq(by, 1, by = by)) {
#         circos.text(p*(xlim[2] - xlim[1]) + xlim[1], mean(ylim) + 0.1, 
#             paste0(p*100, "%"), cex = 0.5, adj = c(0.5, 0), niceFacing = TRUE)
#     }
# }, bg.border = NA)
  
}
# create legend for tumor subclusters
#lgd1 = Legend(labels = names(col_vec[grep("Tumor", names(col_vec))]), title = "Tumor\nSubclusters", legend_gp = gpar(fill = unname(col_vec[grep("Tumor", names(col_vec))])))
lgd2 = Legend(labels = names(metadata(sce_prot)$colour_vector$celltype), title = "Cell Type", legend_gp = gpar(fill = unname(metadata(sce_prot)$colour_vector$celltype)))
draw(packLegend(lgd2, 
                #lgd1, 
                gap = unit(2, "cm")))

Figure 5B

Celltypes

celltypes <- data.frame(colData(sce_prot)) %>%
  filter(celltype != "Tumor") %>%
  group_by(ImageNumber, bcell_patch_score, dysfunction_score, celltype) %>%
  summarise(n=n()) %>%
  mutate(fraction = n/sum(n)) %>%
  filter(is.na(dysfunction_score) == FALSE)

celltypes$bcell_patch_score <- as.character(celltypes$bcell_patch_score)
celltypes$bcell_patch_score <- factor(celltypes$bcell_patch_score, levels = c("No B cells", "No B cell Patches", "Small B cell Patches", "B cell Follicles"))

stat.test <- celltypes %>%
  group_by(celltype) %>%
  wilcox_test(data = ., fraction ~ dysfunction_score) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
  add_x_position(x = "dysfunction_score", dodge = 0.8)


ggplot(celltypes, aes(x=celltype, y=fraction)) +
  geom_boxplot(alpha=.5, lwd = 1, outlier.shape = NA, aes(fill=dysfunction_score)) +
  geom_quasirandom(dodge.width=0.75, alpha=1, size=1, aes(group=dysfunction_score)) + 
  stat_pvalue_manual(stat.test, x = "celltype", label = "p.adj.signif", size = 7, y.position = -0.05) + 
  theme_bw() +
  theme(text = element_text(size = 16),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) + 
  guides(fill=guide_legend(title="Dysfunction Score", override.aes = c(lwd=0.5, alpha=1)), col=guide_legend(title="B cell Score")) +
  xlab("") + 
  ylab("Cell Type Fractions") +
  scale_color_manual(values = c("black", "lightblue", "darkblue", "red", "red4"),
                    labels = c(" ", "no Bcells", "few Bcells", "small patches", "large patches"),
                    guide = TRUE)
# check images above median in Low Dysfunction group for B cells (all have large patches)
celltypes %>%
  filter(dysfunction_score == "Low Dysfunction") %>%
  filter(celltype == "B cell") %>%
  group_by(dysfunction_score) %>%
  mutate(median_frac = median(fraction)) %>%
  filter(fraction > median_frac)
# A tibble: 7 x 7
# Groups:   dysfunction_score [1]
  ImageNumber bcell_patch_sco… dysfunction_sco… celltype     n fraction
        <int> <fct>            <chr>            <chr>    <int>    <dbl>
1          29 B cell Follicles Low Dysfunction  B cell     883    0.134
2          33 B cell Follicles Low Dysfunction  B cell    4829    0.365
3          86 B cell Follicles Low Dysfunction  B cell    2416    0.253
4          95 B cell Follicles Low Dysfunction  B cell    1602    0.116
5         109 B cell Follicles Low Dysfunction  B cell    1337    0.255
6         114 B cell Follicles Low Dysfunction  B cell    2895    0.362
7         118 B cell Follicles Low Dysfunction  B cell     782    0.204
# … with 1 more variable: median_frac <dbl>

Composition of Dysfunction Groups (Met Location and Punch Location)

c <- data.frame(colData(sce_rna)) %>%
  distinct(Description, .keep_all = T) %>%
  filter(dysfunction_score %in% c("Low Dysfunction", "High Dysfunction")) %>%
  dplyr::count(MM_location, Location, dysfunction_score) %>%
  ggplot(aes(axis1 = MM_location, axis2 = Location, axis3 = dysfunction_score,y=n))+
  geom_alluvium(aes(fill=as.factor(dysfunction_score)))+
  geom_stratum()+
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  theme_minimal()+
  scale_x_discrete(limits = c("Met Location", "Punch Location", "Dysfunction Score"), expand = c(.2, .05)) +
  theme(text = element_text(size=20)) +
  guides(fill=guide_legend(title="Dysfunction Score")) +
  ylab("Number of Samples")
plot(c)

Figure 5C

B cell patch grouping for dysfunction groups

a <- data.frame(colData(sce_rna)) %>%
  distinct(Description, .keep_all = T) %>%
  group_by(bcell_patch_score, dysfunction_score) %>%
  summarise(n=n()) %>%
  filter(is.na(dysfunction_score) == F) %>%
  group_by(dysfunction_score) %>%
  mutate(fraction = n / sum(n)) %>%
  ungroup()

ggplot(a) + 
  geom_col(aes(y=dysfunction_score, x=fraction, fill=bcell_patch_score)) +
  theme_minimal() + 
  theme(text = element_text(size = 22)) +
  xlab("Fraction of Samples") +
  ylab("") +
  guides(fill=guide_legend(title="B cell Score"))

Figure 5D

Analysis

# im_size
im_size <- as.data.frame(cbind(image_mat_rna$Metadata_Description, (image_mat_rna$Height_cellmask * image_mat_rna$Width_cellmask)/1000000))
names(im_size) <- c("Description", "mm2")
im_size$mm2 <- as.numeric(im_size$mm2)

cxcl13 <- data.frame(colData(sce_rna)) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>% # remove LN margin samples 
  filter(CXCL13 == 1) %>%
  group_by(Description, MM_location, celltype) %>%
  summarise(n=n()) %>%
  reshape2::dcast(Description + MM_location ~ celltype, value.var = "n", fill = 0)

all_images <- data.frame(colData(sce_rna)) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>%
  distinct(Description, .keep_all = T) %>%
  select(Description)

# left_join to have all images
all_images <- left_join(all_images, cxcl13)

# replace NA
all_images[is.na(all_images)] <- 0

all_images <- all_images %>%
  reshape2::melt(id.vars=c("Description", "MM_location"), variable.name = "celltype", value.name = "n")

# add mm2 and calculate density
all_images <- left_join(all_images, im_size)
all_images$density <- all_images$n / all_images$mm2

#
Bcell <- data.frame(colData(sce_rna)) %>%
  distinct(Description, .keep_all = T) %>%
  group_by(Description) %>%
  select(Description, bcell_patch_score)

# add grouping
all_images <- left_join(all_images, Bcell[,c("Description","bcell_patch_score")]) %>%
  filter(celltype %in% c("CD8+ T cell", "CD8- T cell", "HLA-DR")) 

#all_images$interaction <- interaction(all_images$celltype, all_images$bcell_patch_score)

ggplot(all_images,aes(x=bcell_patch_score, y = log10(as.numeric(density+1)), fill=celltype)) + 
  geom_boxplot(alpha=1, lwd=1, outlier.shape = NA) + 
  geom_quasirandom(dodge.width=0.75, alpha=1, size=2) +
  ylab("CXCL13 Expressing Cells per mm2\n(log10 + 1)") +
  xlab("") + 
  theme_bw() +
  theme(text = element_text(size=18),
        axis.text.x = element_text(angle=45, vjust=1, hjust=1)) +
  scale_fill_manual(values = unname(metadata(sce_rna)$colour_vectors$celltype[c("CD8+ T cell", "CD8- T cell", "HLA-DR")]),
                    breaks = names(metadata(sce_rna)$colour_vectors$celltype[c("CD8+ T cell", "CD8- T cell", "HLA-DR")])) +
  guides(fill=guide_legend(title="Cell Type", override.aes = c(lwd=0.5)))

Fig 5D with fractions

# fraction of all CXCL13 production
cxcl13_fraction <- data.frame(colData(sce_rna)) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>% # remove LN margin samples 
  filter(CXCL13 == 1) %>% 
  group_by(Description, celltype, .drop = FALSE) %>%
  summarise(n=n()) %>%
  reshape2::dcast(Description ~ celltype, fill = 0, value.var = "n") %>%
  reshape2::melt(id.vars=c("Description"), variable.name = "celltype", value.name = "n") %>%
  group_by(Description, .drop = FALSE) %>%
  mutate(fraction = n / sum(n)) %>%
  filter(celltype %in% c("CD8+ T cell", "CD8- T cell", "HLA-DR"))

all_images <- data.frame(colData(sce_rna)) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>%
  distinct(Description, .keep_all = T) %>%
  select(Description)

# left_join to have all images
all_images <- left_join(all_images, cxcl13_fraction)

# add 0 to images that do not containt CXCL13 producing cells
all_images <- all_images %>%
  reshape2::dcast(Description ~ celltype, value.var = "fraction", fill = 0) %>%
  select(-`NA`) %>%
  reshape2::melt(id.vars=c("Description"), variable.name = "celltype", value.name = "fraction")

# get Bcell score for each image
Bcell <- data.frame(colData(sce_rna)) %>%
  distinct(Description, .keep_all = T) %>%
  group_by(Description) %>%
  select(Description, bcell_patch_score)

# add Bcell score
all_images <- left_join(all_images, Bcell[,c("Description","bcell_patch_score")])

ggplot(all_images,aes(x=bcell_patch_score, y = as.numeric(fraction), fill=celltype)) + 
  geom_boxplot(alpha=1, lwd=1, outlier.shape = NA) + 
  geom_quasirandom(dodge.width=0.75, alpha=1, size=2) +
  ylab("Fraction of Total CXCL13 Expression") +
  xlab("") + 
  theme_bw() +
  theme(text = element_text(size=18),
        axis.text.x = element_text(angle=45, vjust=1, hjust=1)) +
  scale_fill_manual(values = unname(metadata(sce_rna)$colour_vectors$celltype[c("CD8+ T cell", "CD8- T cell", "HLA-DR")]),
                    breaks = names(metadata(sce_rna)$colour_vectors$celltype[c("CD8+ T cell", "CD8- T cell", "HLA-DR")])) +
  guides(fill=guide_legend(title="Cell Type", override.aes = c(lwd=0.5)))

Figure 5E

Example of CXCL10 Cluster and corresponding Community

example <- findPatch(sce_prot[,sce_prot$Description == "C9"], sce_prot[,colData(sce_prot)$celltype %in% c("B cell", "BnT cell")]$cellID, 
                    'cellID', 
                    'Center_X', 'Center_Y', 
                    'Description', 
                    distance = 15, 
                    min_clust_size = 20,
                    output_colname = "example_patch")
Time difference of 2.200766 secs
[1] "patches successfully added to sce object"
example <- findMilieu(example, 
              'cellID', 
              'Center_X', 'Center_Y', 
              'Description', 
              'example_patch', 
              distance = 50,
              output_colname = "example_milieu",
              plot = TRUE)
Time difference of 3.316583 secs
[1] "milieus successfully added to sce object"

Figure 5F

Fraction of Tcf7 Tcells cells in B cell patch groups

celltypes <- data.frame(colData(sce_prot)) %>%
  mutate(mmLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(mmLocationPunch != "LN_M") %>% # remove LN margin images 
  #filter(celltype != "Tumor") %>%
  mutate(TCF7_PD1 = paste(PD1, TCF7, 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")) 

celltypes$bcell_patch_score <- as.character(celltypes$bcell_patch_score)
celltypes$bcell_patch_score <- factor(celltypes$bcell_patch_score, levels = c("No B cells", "No B cell Patches", "Small B cell Patches", "B cell Follicles"))

stat.test <- celltypes %>%
  group_by(celltype, TCF7_PD1) %>%
  kruskal_test(data = ., fraction ~ bcell_patch_score) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
  mutate(group1 = celltype, group2 = TCF7_PD1) %>%
  add_xy_position()

ggplot(celltypes, aes(x=TCF7_PD1, y=fraction)) +
  geom_boxplot(alpha=1, lwd = 0.5, outlier.size = 0.5, aes(fill=bcell_patch_score)) +
  stat_pvalue_manual(x = "group2", stat.test, y.position = -0.1, size = 6) +
  theme_bw() +
  theme(text = element_text(size = 14),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) + 
  guides(fill=guide_legend(title="B cell Score", override.aes = c(lwd=0.5))) +
  xlab("") + 
  ylab("Fraction of Population") +
  facet_wrap(~celltype, scales = "free") +
  ylim(-0.1,1.1)

Magnify TCF7+PD1+ population

# magnify PD1+TCF7+ population
ggplot(celltypes[celltypes$TCF7_PD1 == "PD1+_TCF7+",], aes(x=TCF7_PD1, y=fraction)) +
  geom_boxplot(alpha=1, lwd = 0.5, outlier.size = 0.5, aes(fill=bcell_patch_score)) +
  theme_bw() +
  theme(text = element_text(size = 14),
        axis.text.x = element_blank(),
        legend.position = "none") + 
  xlab("") + 
  ylab("") +
  facet_wrap(~celltype, scales = "free") +
  coord_cartesian(ylim = c(0,0.05))

Figure 5G

Percentage of TCF7+PD1+CD8+ cells that are part of a Bcell milieu

# what fraction of each celltype is part of a milieu?
cur_dat <- data.frame(colData(sce_prot)) %>%
  mutate(MMLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(MMLocationPunch != "LN_M") %>%
  filter(Location != "CTRL") %>%
  filter(celltype %in% c("CD8+ T cell", "CD4+ T cell")) %>%
  mutate(status = paste(TCF7, PD1, sep = "_")) %>%
  #filter(status == "TCF7+_PD1+") %>%
  mutate(milieu_binary = ifelse(bcell_milieu > 0, 1, 0)) %>%
  group_by(Description, milieu_binary, celltype, status) %>%
  summarise(n=n()) %>%
  group_by(Description, celltype, status) %>%
  mutate(fraction_in_milieu = n / sum(n)) %>%
  filter(milieu_binary == 1)

# what fraction of the total cell area is made up by cells that are part of a milieu
milieu_area <- data.frame(colData(sce_prot)) %>%
  mutate(MMLocationPunch = paste(MM_location, Location, sep = "_")) %>%
  filter(MMLocationPunch != "LN_M") %>%
  filter(Location != "CTRL") %>%
  mutate(milieu_binary = ifelse(bcell_milieu > 0, 1, 0)) %>%
  group_by(Description, milieu_binary) %>%
  summarise(area = sum(Area)) %>% 
  group_by(Description) %>%
  mutate(fraction_of_area = area / sum(area))  %>%
  filter(row_number() == n())

sum <- left_join(cur_dat, milieu_area, by="Description")

# calculate metric - milieu_fraction divided by milieu-area-fraction (this normalizes the first metric)
sum$metric <- sum$fraction_in_milieu / sum$fraction_of_area

# one-sample t test
stat.test <- sum %>%
  group_by(celltype, status) %>%
  mutate(log10_metric = log10(metric)) %>%
  t_test(log10_metric ~ 1, mu = 0, alternative = "greater", detailed = TRUE) %>%
  adjust_pvalue() %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1))

ggplot(sum, aes(x=sum$status, y=log10(metric))) +
  geom_boxplot(outlier.shape = NA) + 
  geom_quasirandom(size=0.75) +
  geom_hline(yintercept = 0) +
  facet_wrap(~celltype) +
  theme_bw() + 
  theme(text=element_text(size=14),
        axis.text.x = element_text(angle=45, vjust=1, hjust=1)) +
  stat_pvalue_manual(
    stat.test, x = "status", y.position = 1.5,
    label = "p.adj.signif",
    position = position_dodge(0.8), 
    size=6) + 
  ylab("Enrichment in B cell milieus (log10)") +
  xlab("") #+
  #coord_cartesian(ylim=c(-1,1.75))

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