Last updated: 2021-02-08

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 20a1458. 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/._density_infiltration_BlockID.csv
    Ignored:    data/._layer_1_classification_rna.csv
    Ignored:    data/._manual_infiltration_scoring.csv
    Ignored:    data/._manual_infiltration_scoring_BlockID.csv
    Ignored:    data/._manual_infiltration_scoring_RC.csv
    Ignored:    data/._manual_infiltration_scoring_TH.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/colour_vector.rds
    Ignored:    data/density_infiltration_BlockID.csv
    Ignored:    data/fraction_and_infiltration_scoring.csv
    Ignored:    data/layer_1_classification_protein.csv
    Ignored:    data/layer_1_classification_protein.rds
    Ignored:    data/layer_1_classification_rna.csv
    Ignored:    data/manual_infiltration_scoring.csv
    Ignored:    data/manual_infiltration_scoring_BlockID.csv
    Ignored:    data/manual_infiltration_scoring_RC.csv
    Ignored:    data/manual_infiltration_scoring_TH.csv
    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/11_Bcell_TLS_identifiaction.Rmd
    Modified:   analysis/Figure_2.rmd
    Modified:   analysis/Figure_3.rmd
    Modified:   analysis/Figure_4.rmd
    Modified:   analysis/Figure_5.rmd
    Modified:   analysis/Summary_Statistics.rmd
    Modified:   analysis/Supp-Figure_2.rmd
    Modified:   analysis/Supp-Figure_3.rmd
    Modified:   analysis/Supp-Figure_4.rmd
    Modified:   analysis/Supp-Figure_5.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 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/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(corrplot)
library(ggridges)
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_rna <- read.csv("data/rna/Image.csv")

# surv_dat
dat_survival_prot <- fread(file = "data/protein/clinical_data_protein.csv")
time_data = fread(file = "data/survdat_for_modelling.csv",stringsAsFactors = FALSE)
time_data$BlockID <- time_data$Block.ID

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 == "Tcytotoxic",]
  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("Tcytotoxic"),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", "TLS"))

stat.test <- celltypes %>%
  group_by(celltype) %>%
  wilcox_test(data = ., fraction ~ dysfunction_score) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj") %>%
  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_jitter(alpha=1, position = position_jitterdodge(dodge.width = 0.75,jitter.width = 0.1), size = 4, 
              #aes(x = celltype, y = fraction, #col=ifelse(celltype %in% c("Bcell", "BnTcell"), bcell_patch_score, " "),
                  #group = dysfunction_score)) + 
  geom_quasirandom(dodge.width=0.75, alpha=1, size=1) + 
  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="Bcell 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 == "Bcell") %>%
  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 TLS              low dysfunction  Bcell      885    0.134
2          33 TLS              low dysfunction  Bcell     4831    0.365
3          86 TLS              low dysfunction  Bcell     2400    0.252
4          95 TLS              low dysfunction  Bcell     1603    0.116
5         109 TLS              low dysfunction  Bcell     1333    0.254
6         114 TLS              low dysfunction  Bcell     2881    0.360
7         118 TLS              low dysfunction  Bcell      787    0.206
# … 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="Bcell 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("Tcytotoxic", "Tcell", "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) + 
  #scale_x_discrete(labels = rep(unique(all_images$bcell_patch_score), each = 3)) +
  geom_quasirandom(dodge.width=0.75, alpha=1, size=2) +
  #geom_line(aes(group = Description), alpha = ifelse(all_images$celltype != "HLA-DR", 0.6, 0), colour = "black") +
  #geom_point(aes(group= interaction), position = position_dodge(0.75)) +
  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("Tcytotoxic", "Tcell", "HLA-DR")]),
                    breaks = names(metadata(sce_rna)$colour_vectors$celltype[c("Tcytotoxic", "Tcell", "HLA-DR")])) +
  #scale_color_manual(values = unname(metadata(sce_rna)$colour_vectors$celltype[c("Tcytotoxic", "Tcell", "HLA-DR")]),
                    #breaks = names(metadata(sce_rna)$colour_vectors$celltype[c("Tcytotoxic", "Tcell", "HLA-DR")]),
                    #guide = FALSE) +
  guides(fill=guide_legend(title="Cell Type", override.aes = c(lwd=0.5)))

Figure 5E

Example of CXCL10 Cluster and corresponding Community

example <- findClusters(sce_prot[,sce_prot$Description == "C9"], sce_prot[,colData(sce_prot)$celltype %in% c("Bcell", "BnTcell")]$cellID, 
                    'cellID', 
                    'Center_X', 'Center_Y', 
                    'Description', 
                    distance = 15, 
                    min_clust_size = 20,
                    output_colname = "example_patch")
Time difference of 2.244363 secs
[1] "clusters successfully added to sce object"
example <- findCommunity(example, 
              'cellID', 
              'Center_X', 'Center_Y', 
              'Description', 
              'example_patch', 
              distance = 50,
              output_colname = "example_milieu",
              plot = TRUE)
Time difference of 3.29452 secs
[1] "communities successfully added to sce object"

Figure 5F

Fraction of Tcf7 Tcells cells in bcell 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("Tcytotoxic", "Thelper")) 

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

stat.test <- celltypes %>%
  group_by(celltype, TCF7_PD1) %>%
  kruskal_test(data = ., fraction ~ bcell_patch_score) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj") %>%
  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="Bcell Score", override.aes = c(lwd=0.5))) +
  xlab("") + 
  ylab("Fraction of Population") +
  facet_wrap(~celltype, scales = "free") +
  ylim(-0.1,1.1)

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)) %>%
  filter(Location != "CTRL") %>%
  filter(celltype %in% c("Tcytotoxic", "Thelper")) %>%
  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)) %>%
  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")

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