Last updated: 2022-02-22

Checks: 7 0

Knit directory: MelanomaIMC/

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


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

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

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

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

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

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

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

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

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


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rproj.user/
    Ignored:    Table_S4.csv
    Ignored:    code/.DS_Store
    Ignored:    code/._.DS_Store
    Ignored:    data/.DS_Store
    Ignored:    data/._.DS_Store
    Ignored:    data/data_for_analysis/
    Ignored:    data/full_data/

Unstaged changes:
    Modified:   .gitignore
    Modified:   analysis/Supp-Figure_10.rmd
    Modified:   analysis/_site.yml
    Deleted:    analysis/license.Rmd

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


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

File Version Author Date Message
html 1affd7b toobiwankenobi 2022-02-22 update .html
Rmd 64e5fde toobiwankenobi 2022-02-16 change order and naming of supp fig files

Introduction

This script generates plots for Supplementary Figure 14, which shows Figure 5 without any LN samples.

Preparations

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

Load libraries

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 code/helper_functions/read_Data.R
value   ?                                ?                                
visible FALSE                            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(ComplexHeatmap)
library(colorRamps)
library(circlize)
library(RColorBrewer)
library(ggpubr)
library(ggbeeswarm)
library(gridExtra)
library(tidyr)
library(ggpmisc)
library(circlize)
library(dittoSeq)
library(scater)
library(cowplot)
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")

# remove all LN samples
sce_rna <- sce_rna[,sce_rna$MM_location_simplified != "LN"]
sce_prot <- sce_prot[,sce_prot$MM_location_simplified != "LN"]

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

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

Supp Figure 14A

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()
  
  # 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"))
}

Version Author Date
235386f toobiwankenobi 2022-02-22

Version Author Date
235386f toobiwankenobi 2022-02-22
# create legend for tumor subclusters
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")))

Version Author Date
235386f toobiwankenobi 2022-02-22

Supp Figure 14B

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 = 20),
        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)

Version Author Date
235386f toobiwankenobi 2022-02-22
# 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: 4 × 7
# Groups:   dysfunction_score [1]
  ImageNumber bcell_patch_score    dysfunction_score celltype     n fraction
        <int> <fct>                <chr>             <chr>    <int>    <dbl>
1          13 No B cell Patches    Low Dysfunction   B cell      24   0.0146
2          19 Small B cell Patches Low Dysfunction   B cell     131   0.0761
3          29 B cell Follicles     Low Dysfunction   B cell     883   0.134 
4         118 B cell Follicles     Low Dysfunction   B cell     782   0.204 
# … with 1 more variable: median_frac <dbl>

Supp Figure 14C

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

Version Author Date
235386f toobiwankenobi 2022-02-22

Supp Figure 14D

Analysis and Visualization

# 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) %>%
  dplyr::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) %>%
  dplyr::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) %>%
  dplyr::select(Description, bcell_patch_score)

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

# stats - is there a difference between celltype fractions in the groups?
all_images %>%
  group_by(bcell_patch_score) %>%
  wilcox_test(fraction ~ celltype) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1))
# A tibble: 12 × 10
   bcell_patch_score   .y.   group1 group2    n1    n2 statistic       p   p.adj
 * <fct>               <chr> <chr>  <chr>  <int> <int>     <dbl>   <dbl>   <dbl>
 1 No B cells          frac… CD8- … CD8+ …    47    47    1093   9.24e-1 9.24e-1
 2 No B cells          frac… CD8- … HLA-DR    47    47    1444.  4.47e-4 8.94e-4
 3 No B cells          frac… CD8+ … HLA-DR    47    47    1492.  1.07e-4 2.57e-4
 4 No B cell Patches   frac… CD8- … CD8+ …    38    38     778.  5.54e-1 6.04e-1
 5 No B cell Patches   frac… CD8- … HLA-DR    38    38    1234   3.23e-9 3.88e-8
 6 No B cell Patches   frac… CD8+ … HLA-DR    38    38    1150   2.82e-7 1.69e-6
 7 Small B cell Patch… frac… CD8- … CD8+ …    13    13      23.5 2   e-3 3.43e-3
 8 Small B cell Patch… frac… CD8- … HLA-DR    13    13     162.  3.61e-5 1.08e-4
 9 Small B cell Patch… frac… CD8+ … HLA-DR    13    13     162.  3.61e-5 1.08e-4
10 B cell Follicles    frac… CD8- … CD8+ …     7     7      31   4.56e-1 6.04e-1
11 B cell Follicles    frac… CD8- … HLA-DR     7     7      36.5 1.4 e-1 2.1 e-1
12 B cell Follicles    frac… CD8+ … HLA-DR     7     7      30   5.21e-1 6.04e-1
# … with 1 more variable: p.adj.signif <chr>
ggplot(all_images,aes(x=bcell_patch_score, y = as.numeric(fraction), fill=celltype)) + 
  geom_boxplot(alpha=1, lwd=1, outlier.shape = NA, aes(fill=celltype)) + 
  geom_quasirandom(dodge.width=0.75, alpha=1, size=2, aes(fill=celltype)) +
  ylab("Fraction of Total CXCL13 Expression") +
  #stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 7) + 
  xlab("") + 
  theme_bw() +
  theme(text = element_text(size=19),
        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))) +
  scale_color_discrete(guide = FALSE)
Warning: It is deprecated to specify `guide = FALSE` to remove a guide. Please
use `guide = "none"` instead.

Version Author Date
235386f toobiwankenobi 2022-02-22

Supp Figure 14E

Example of CXCL10 Cluster and corresponding Community

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

Version Author Date
235386f toobiwankenobi 2022-02-22
Time difference of 1.445762 secs
[1] "milieus successfully added to sce object"

Supp Figure 14F

Fraction of Tcf7 Tcells cells in B cell patch groups

celltypes <- data.frame(colData(sce_prot)) %>%
  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") %>%
  reshape2::dcast(PatientID + BlockID + Description + bcell_patch_score + TCF7_PD1 ~ celltype, value.var = "n", fill=0) %>%
  reshape2::melt(id.vars = c("PatientID","BlockID", "Description", "bcell_patch_score", "TCF7_PD1"), 
                 variable.name = "celltype", 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"))

celltypes$celltype <- factor(celltypes$celltype, levels = c("CD8+ T cell", "CD4+ T cell"))

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)
Warning: Removed 36 rows containing non-finite values (stat_boxplot).

Version Author Date
235386f toobiwankenobi 2022-02-22

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))
Warning: Removed 9 rows containing non-finite values (stat_boxplot).

Version Author Date
235386f toobiwankenobi 2022-02-22

Supp Figure 14G

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 = "_")) %>%
  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

sum$celltype <- factor(sum$celltype, levels = c("CD8+ T cell", "CD4+ T cell"))

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

Version Author Date
235386f toobiwankenobi 2022-02-22

sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.3 LTS

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

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

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

other attached packages:
 [1] RANN_2.6.1                  concaveman_1.1.0           
 [3] sf_1.0-5                    rstatix_0.7.0              
 [5] ggridges_0.5.3              corrplot_0.92              
 [7] cytomapper_1.6.0            EBImage_4.36.0             
 [9] cowplot_1.1.1               scater_1.22.0              
[11] scuttle_1.4.0               dittoSeq_1.6.0             
[13] ggpmisc_0.4.5               ggpp_0.4.3                 
[15] gridExtra_2.3               ggbeeswarm_0.6.0           
[17] ggpubr_0.4.0                RColorBrewer_1.1-2         
[19] circlize_0.4.13             colorRamps_2.3             
[21] ComplexHeatmap_2.10.0       data.table_1.14.2          
[23] forcats_0.5.1               stringr_1.4.0              
[25] purrr_0.3.4                 readr_2.1.2                
[27] tidyr_1.2.0                 tibble_3.1.6               
[29] ggplot2_3.3.5               tidyverse_1.3.1            
[31] reshape2_1.4.4              SingleCellExperiment_1.16.0
[33] SummarizedExperiment_1.24.0 Biobase_2.54.0             
[35] GenomicRanges_1.46.1        GenomeInfoDb_1.30.1        
[37] IRanges_2.28.0              S4Vectors_0.32.3           
[39] BiocGenerics_0.40.0         MatrixGenerics_1.6.0       
[41] matrixStats_0.61.0          dplyr_1.0.7                
[43] workflowr_1.7.0            

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