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
    Modified:   code/celltype_classifier/Protein_celltype_classifier_cytomapper.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_2.rmd) and HTML (docs/Supp-Figure_2.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 2ac1833 toobiwankenobi 2021-01-08 changes to Figures
Rmd 9442cb9 toobiwankenobi 2020-12-22 add all new files
Rmd 1af3353 toobiwankenobi 2020-10-16 add stuff
Rmd a6b51cd toobiwankenobi 2020-10-14 clean scripts, add new subfigures
Rmd 90196fc toobiwankenobi 2020-10-13 Supp Figure 2
Rmd 7affca0 toobiwankenobi 2020-10-13 clean branch and add suppfigure 2

Introduction

This script generates plots for Supplementary Figure 2.

Preparations

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
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(data.table)
library(survival)
library(ggplot2)
library(broom)
library(dplyr)
library(RColorBrewer)
library(ggalluvial)
library(tidyverse)
library(cowplot)
library(ggbeeswarm)
library(gridExtra)
library(SingleCellExperiment)
library(scater)
library(cba)
library(ComplexHeatmap)
library(reshape2)
library(rms)
library(ggrepel)
library(circlize)
library(coxme)
library(rstatix)
library(ggpubr)

Load Data

# clinical data
dat <- read_csv("data/data_for_analysis/protein/clinical_data_protein.csv")

# SCE object
sce_prot = readRDS(file = "data/data_for_analysis/sce_protein.rds")
sce_rna = readRDS(file = "data/data_for_analysis/sce_RNA.rds")

clincial = read.csv(file = "data/data_for_analysis/protein/clinical_data_protein.csv")

targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol

Supp Figure 2A

Fraction of Tumor Cells that express chemokines

cur_dat <- data.frame(colData(sce_rna))
cur_dat <- cur_dat %>%
  filter(celltype == "Tumor") %>%
  filter(Location != "CTRL")

cur_dat <- cur_dat[,c("ImageNumber", "Mutation", colnames(cur_dat)[grepl(glob2rx("C*L*"),names(cur_dat))])]

# colSums of Chemokines in Tumor Cells (Multiple Producer count more than once)
cur_dat <- cur_dat %>%
  group_by(ImageNumber, Mutation) %>%
  mutate(cells = n()) %>%
  group_by(ImageNumber, cells, Mutation) %>%
  summarise_each(funs(sum))
Warning: `summarise_each_()` is deprecated as of dplyr 0.7.0.
Please use `across()` instead.
This warning is displayed once every 8 hours.
Call `lifecycle::last_warnings()` to see where this warning was generated.
Warning: `funs()` is deprecated as of dplyr 0.8.0.
Please use a list of either functions or lambdas: 

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

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

  # Using lambdas
  list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))
This warning is displayed once every 8 hours.
Call `lifecycle::last_warnings()` to see where this warning was generated.
# compute fractions
cur_dat[,4:14] <- cur_dat[,4:14] / t(cur_dat$cells)

cur_dat <- cur_dat %>%
  filter(cells > 200) %>%
  reshape2::melt(id.vars=c("ImageNumber", "cells", "Mutation"), variable.name="chemokine", value.name="fraction")

ggplot(cur_dat,aes(x=fct_reorder(chemokine, fraction, .fun = median, .desc = TRUE), y=fraction+0.001)) + 
  geom_boxplot(alpha=.5) +
  geom_quasirandom(alpha=.2) +
  theme_bw() + 
  theme(text=element_text(size=16)) +
  ylab("Fraction of Expressing Tumor Cells\n(fraction + 0.001)") +
  xlab("") +
  scale_y_log10() +
  annotation_logticks(sides = "l") +
  geom_hline(yintercept = median(cur_dat$fraction+0.001), linetype = 2) 

Supp Figure 2B

Clinical features of the cohort

Note: as the cohort is very diverse, we are using the BlockID as the minimal unit since clinical parameters are described per BlockID. However, sometimes we do have patients of which we have multiple FFPE blocks (BlockIDs). Nonetheless, clinical parameters are not given per patient but per patient FFPE block and are therefore considered the minimial unit.

Number of Samples

dat[dat$BlockID %in% unique(sce_prot[,sce_prot$Location == "CTRL"]$BlockID),]$MM_location <- "Control"

# remove control samples
dat <- dat[dat$BlockID %in% unique(sce_prot[,sce_prot$Location != "CTRL"]$BlockID),]

p1 <- unique(dat[,c("BlockID","MM_location")]) %>%
  ggplot()+
  geom_bar(aes(y=MM_location),stat ="count") +
  xlab("Biopsy Blocks per Location") +
  ylab("Metastasis Location") +
  theme_bw()+
  theme(text = element_text(size=16))
  
p2 <- dat %>%
  ggplot()+
  geom_bar(aes(x=BlockID, fill=(MM_location)),stat="count")+
  theme_bw()+
  theme(axis.text.x = element_blank(),
        axis.ticks.x=element_blank(),
        text = element_text(size=16)) + 
  ylab("Number of Samples") +
  xlab("Biopsy Blocks") +
  scale_y_continuous(limits = c(0,4), expand = c(0, 0)) +
  guides(fill=guide_legend(title="Metasis Location"))

plot_grid(p1,p2,rel_widths = c(1.25,3))  

Supp Figure 2C

Patients per Location

sce_rna$MM_location <- ifelse(sce_rna$MM_location %in% c("skin", "skin_undefine"), "skin_undefined", sce_rna$MM_location)

groups <- data.frame(colData(sce_rna)) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  group_by(MM_location) %>%
  distinct(PatientID, .keep_all = T) %>%
  summarise(n=n()) %>%
  filter(n>=10) %>%
  arrange(-n)

Boxplot/Barplot per Location for every chemokine combination

fractions_per_image <- data.frame(colData(sce_rna)) %>%
  group_by(ImageNumber, MM_location, expressor, celltype) %>%
  summarise(n = n()) %>%
  group_by(ImageNumber) %>%
  mutate(fraction_per_image = n / sum(n)) %>%
  group_by(ImageNumber, expressor) %>%
  mutate(group_fraction = sum(fraction_per_image)) %>%
  ungroup() %>%
  filter(expressor %in% targets & MM_location %in% groups$MM_location)

# fraction of expressor cells per image 
fraction_expressor_per_image <- fractions_per_image %>%
  distinct(ImageNumber, MM_location, expressor, .keep_all = T) %>%
  reshape2::dcast(ImageNumber + MM_location ~ expressor, value.var = "group_fraction", fill = 0) %>%
  reshape2::melt(id.vars = c("ImageNumber", "MM_location"), variable.name = "expressor", 
                 value.name = "fraction_per_image")

# fraction of celltype expressing a certain combi per image
celltype_fractions <- fractions_per_image %>%
  distinct(ImageNumber, celltype, expressor, .keep_all = T) %>%
  reshape2::dcast(ImageNumber + MM_location + expressor ~ celltype, value.var = "fraction_per_image", fill = 0) %>%
  reshape2::melt(id.vars = c("ImageNumber", "MM_location", "expressor"), 
                 variable.name = "celltype", value.name = "fraction_per_image") %>%
  reshape2::dcast(ImageNumber + MM_location + celltype ~ expressor, value.var = "fraction_per_image", fill = 0) %>%
  reshape2::melt(id.vars = c("ImageNumber", "MM_location", "celltype"), 
                 variable.name = "expressor", value.name = "fraction_per_image") %>%
  group_by(MM_location, expressor, celltype) %>%
  summarise(sum_fraction = sum(fraction_per_image)) %>% # sum-up fractions over all images 
  group_by(MM_location, expressor) %>%
  mutate(proportions = sum_fraction / sum(sum_fraction)) # calculate proportions for each expressor

Plot

# calculate signif of expressor-fractions per MM_location
fraction_expressor_per_image %>%
  group_by(expressor) %>%
  wilcox_test(fraction_per_image ~ MM_location) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
  arrange(p.adj)
# A tibble: 14 x 10
   expressor .y.   group1 group2    n1    n2 statistic       p  p.adj
   <fct>     <chr> <chr>  <chr>  <int> <int>     <dbl>   <dbl>  <dbl>
 1 CCL19     frac… LN     skin_…    49    52     1739  0.00129 0.0181
 2 CXCL13    frac… LN     skin_…    49    52     1634. 0.0138  0.0966
 3 CCL22     frac… LN     skin_…    49    52     1557  0.0548  0.145 
 4 CXCL12_C… frac… LN     skin_…    49    52     1535  0.062   0.145 
 5 CXCL8     frac… LN     skin_…    49    52     1580  0.0378  0.145 
 6 CXCL9_CC… frac… LN     skin_…    49    52     1523  0.0487  0.145 
 7 CCL18     frac… LN     skin_…    49    52     1501  0.124   0.217 
 8 CXCL10_C… frac… LN     skin_…    49    52     1054  0.121   0.217 
 9 CXCL10    frac… LN     skin_…    49    52     1095  0.225   0.315 
10 CXCL12    frac… LN     skin_…    49    52     1457  0.215   0.315 
11 CCL4      frac… LN     skin_…    49    52     1382  0.465   0.592 
12 CCL2      frac… LN     skin_…    49    52     1326. 0.724   0.845 
13 CXCL10_C… frac… LN     skin_…    49    52     1270  0.981   0.981 
14 CXCL9     frac… LN     skin_…    49    52     1288  0.926   0.981 
# … with 1 more variable: p.adj.signif <chr>
plot_list <- list()
for(i in groups$MM_location) {
  a <- fraction_expressor_per_image %>%
    filter(MM_location == i) %>%  
    group_by(ImageNumber, expressor) %>%
    ggplot(., aes(y=as.factor(expressor), x=fraction_per_image)) + 
    geom_boxplot() + 
    geom_point(alpha=0.2) +
    theme_bw() +
    theme(axis.title.y = element_blank(),
          axis.text.y = element_text(hjust=0.5)) +
    xlab("Cell Fraction per Image") + 
    coord_cartesian(xlim = c(0,0.05))
  
  b <- celltype_fractions %>%
    filter(MM_location == i) %>%  
    ggplot(., aes(y=expressor, x=-proportions, fill=celltype)) + 
    geom_bar(stat = "identity") +
    theme_bw() +
    theme(axis.text.y = element_blank(),
          axis.title.y = element_blank()) +
    guides(fill=guide_legend(title = "Cell Type",nrow=2,byrow=TRUE)) +
    xlab("Producing Cell Types") +
          scale_fill_manual(values = unname(metadata(sce_rna)$colour_vectors$celltype),
                        breaks = names(metadata(sce_rna)$colour_vectors$celltype),
                        labels = names(metadata(sce_rna)$colour_vectors$celltype)) +
    scale_x_continuous(breaks=c(-1.00,-0.75,-0.5, -0.25, 0.00),
                     labels=c("100%", "75%", "50%", "25%", "0%"))
  
  leg <- get_legend(b)
  
  grid.arrange(b+theme(legend.position = "none"),a,nrow=1,
               widths = c(.75,1),
               top = i)
}
grid.arrange(leg)

Supp Figure 2D

Expressor in MM_location

# add control location to sce
sce_rna$MM_location_simplified2 <- sce_rna$MM_location_simplified
sce_rna[,sce_rna$Location == "CTRL" & sce_rna$TissueType == "Skin"]$MM_location_simplified2 <- "control skin"
sce_rna[,sce_rna$Location == "CTRL" & sce_rna$TissueType == "Lymphnode"]$MM_location_simplified2 <- "control LN"
sce_rna[,sce_rna$Location == "CTRL" & sce_rna$TissueType == "PSO"]$MM_location_simplified2 <- "control psoriasis"

frac <- data.frame(colData(sce_rna)) %>%
  filter(MM_location_simplified2 != "control psoriasis") %>%
  group_by(Description, MM_location_simplified2, expressor) %>%
  summarise(n=n()) %>%
  mutate(fraction = n / sum(n)) %>%
  filter(expressor %in% targets) %>%
  reshape2::dcast(Description + MM_location_simplified2 ~ expressor, value.var = "fraction", fill = 0) %>%
  reshape2::melt(id.vars = c("Description", "MM_location_simplified2"), variable.name = "expressor", value.name = "fraction")

ggplot(frac, aes(x=expressor, y = fraction)) + 
  geom_boxplot(alpha=1, outlier.size = 0.5, aes(fill = MM_location_simplified2)) +
  scale_color_discrete(guide=FALSE) +
  theme_bw() +
  theme(text = element_text(size = 15),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) + 
  guides(fill=guide_legend(title="Met Location", override.aes = aes(lwd=0.5))) +
  xlab("") + 
  ylab("Fractions") +
  coord_cartesian(ylim = c(0,0.06))

Supp Figure 2E

Mutation split by Location

targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol

# subset sce_rna
group_size <- data.frame(colData(sce_rna)) %>%
  group_by(ImageNumber, Mutation) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  group_by(Mutation) %>%
  summarise(n=n()) %>%
  filter(n>10 & Mutation != "")

sce_rna_sub <- sce_rna[,sce_rna$Mutation %in% group_size$Mutation]

a <- plotCellCounts(sce = sce_rna_sub, 
                     sce_sub = sce_rna_sub[,which(sce_rna_sub$expressor %in% targets)],
                     cellID = "cellID",
                     colour_by = "expressor",
                     split_by = "Mutation",
                     imageID = "ImageNumber",
                     normalize = TRUE,
                    show_n = FALSE,
                     colour_vector = metadata(sce_rna)$colour_vectors$chemokine_combinations) + 
  guides(fill=guide_legend("Chemokine")) +
  theme(text = element_text(size=18))

b <- plotCellCounts(sce = sce_rna_sub[,which(sce_rna_sub$expressor %in% targets)],
                     cellID = "cellID",
                     colour_by = "celltype",
                     split_by = "Mutation",
                     imageID = "ImageNumber",
                     proportion = TRUE,
                    show_n = FALSE,
                     colour_vector = metadata(sce_rna)$colour_vectors$celltype) + 
  guides(fill=guide_legend("Cell Type")) +
  theme(text = element_text(size=18))

# fraction of chemokine-expressing cells per image
chemo <- data.frame(colData(sce_rna_sub)) %>%
  #filter(MM_location_simplified2 %in% c("skin_subcutaneous", "LN")) %>%
  group_by(ImageNumber, Mutation, chemokine, MM_location_simplified2) %>%
  summarise(n=n()) %>%
  group_by(ImageNumber) %>%
  mutate(fraction = n / sum(n)) %>%
  reshape2::dcast(ImageNumber + Mutation + MM_location_simplified2 ~ chemokine, value.var = "fraction")

median_expression <- median(chemo$`TRUE`)

stat.test <- chemo %>%
  wilcox_test(`TRUE` ~ Mutation) %>%
  adjust_pvalue(method="BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
  add_xy_position(x = "Mutation")

stat.test$y.position <- stat.test$y.position - 0.125

c <- ggplot(chemo, aes(x=Mutation, y=`TRUE`)) + 
  geom_boxplot(alpha=0.2, lwd=1.5) + 
  geom_quasirandom(aes(col=MM_location_simplified2), size=2, alpha=.8) +
  #geom_hline(yintercept = median_expression, linetype=2, size=2) + 
  stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 7) + 
  xlab("") + 
  ylab("Fraction of Chemokine-Expressing Cells") +
  theme_bw() +
  theme(text = element_text(size=16),
        axis.text.x = element_text(angle=45, hjust=1, vjust=1)) +
  guides(col=guide_legend("Location")) + 
  coord_cartesian(ylim=c(0,0.35))

p <- grid.arrange(a,b, ncol=2, nrow=1)
grid.arrange(p,c,nrow=1, widths = c(0.65,0.35))
# MM_location for Mutations
data.frame(colData(sce_rna_sub)) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  group_by(Mutation, MM_location_simplified) %>%
  summarise(n=n()) %>%
  group_by(Mutation) %>%
  mutate(percentage = n / sum(n) * 100)
# A tibble: 9 x 4
# Groups:   Mutation [3]
  Mutation MM_location_simplified     n percentage
  <chr>    <chr>                  <int>      <dbl>
1 BRAF     LN                        30       42.3
2 BRAF     other                     10       14.1
3 BRAF     skin                      31       43.7
4 NRAS     LN                        16       32  
5 NRAS     other                     10       20  
6 NRAS     skin                      24       48  
7 wt       LN                         6       21.4
8 wt       other                      5       17.9
9 wt       skin                      17       60.7

Mutation split by Location

targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol

# subset sce_rna
group_size <- data.frame(colData(sce_rna)) %>%
  group_by(ImageNumber, Mutation) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  group_by(Mutation) %>%
  summarise(n=n()) %>%
  filter(n>10 & Mutation != "")

sce_rna_sub <- sce_rna[,sce_rna$Mutation %in% group_size$Mutation]

a1 <- plotCellCounts(sce = sce_rna_sub[,sce_rna_sub$MM_location == "LN"], 
                    sce_sub = sce_rna_sub[,which(sce_rna_sub$expressor %in% targets & sce_rna_sub$MM_location == "LN")],
                    cellID = "cellID",
                    colour_by = "expressor",
                    split_by = "Mutation",
                    imageID = "ImageNumber",
                    normalize = TRUE,
                    show_n = FALSE,
                    colour_vector = metadata(sce_rna)$colour_vectors$chemokine_combinations) + 
  guides(fill=guide_legend("Chemokine")) +
  theme(text = element_text(size=16)) +
  ylab("Normalized Cell Fraction")

b1 <- plotCellCounts(sce = sce_rna_sub[,which(sce_rna_sub$expressor %in% targets & sce_rna_sub$MM_location == "LN")],
                    cellID = "cellID",
                    colour_by = "celltype",
                    split_by = "Mutation",
                    imageID = "ImageNumber",
                    proportion = TRUE,
                    show_n = FALSE,
                    colour_vector = metadata(sce_rna)$colour_vectors$celltype) + 
  guides(fill=guide_legend("Cell Type")) +
  theme(text = element_text(size=16))

a2 <- plotCellCounts(sce = sce_rna_sub[,sce_rna_sub$MM_location == "skin_subcutaneous"], 
                    sce_sub = sce_rna_sub[,which(sce_rna_sub$expressor %in% targets & sce_rna_sub$MM_location == "skin_subcutaneous")],
                    cellID = "cellID",
                    colour_by = "expressor",
                    split_by = "Mutation",
                    imageID = "ImageNumber",
                    normalize = TRUE,
                    show_n = FALSE,
                    colour_vector = metadata(sce_rna)$colour_vectors$chemokine_combinations) + 
  guides(fill=guide_legend("Chemokine")) +
  theme(text = element_text(size=16)) +
  ylab("Normalized Cell Fraction")

b2 <- plotCellCounts(sce = sce_rna_sub[,which(sce_rna_sub$expressor %in% targets & sce_rna_sub$MM_location == "skin_subcutaneous")],
                    cellID = "cellID",
                    colour_by = "celltype",
                    split_by = "Mutation",
                    imageID = "ImageNumber",
                    proportion = TRUE,
                    show_n = FALSE,
                    colour_vector = metadata(sce_rna)$colour_vectors$celltype) + 
  guides(fill=guide_legend("Cell Type")) +
  theme(text = element_text(size=16))

# fraction of chemokine-expressing cells per image
chemo <- data.frame(colData(sce_rna_sub)) %>%
  filter(MM_location %in% c("skin_subcutaneous", "LN")) %>%
  group_by(ImageNumber, Mutation, chemokine, MM_location) %>%
  summarise(n=n()) %>%
  group_by(ImageNumber) %>%
  mutate(fraction = n / sum(n)) %>%
  reshape2::dcast(ImageNumber + Mutation + MM_location ~ chemokine, value.var = "fraction")

median_expression <- median(chemo$`TRUE`)

stat.test <- chemo %>%
  group_by(MM_location) %>%
  wilcox_test(`TRUE` ~ Mutation) %>%
  adjust_pvalue(method="BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
  add_xy_position(x = "Mutation")

stat.test$y.position <- stat.test$y.position - 0.025

c <- ggplot(chemo, aes(x=Mutation, y=`TRUE`)) + 
  geom_boxplot(alpha=0.2, lwd=1.5) + 
  geom_quasirandom(aes(col=MM_location), size=2, alpha=.8) +
  #geom_hline(yintercept = median_expression, linetype=2, size=2) + 
  #stat_pvalue_manual(stat.test, label = "p.adj.signif", size = 7) + 
  xlab("") + 
  ylab("Fraction of Chemokine-Expressing Cells") +
  theme_bw() +
  theme(text = element_text(size=16),
        axis.text.x = element_text(angle=45, hjust=1, vjust=1)) +
  guides(col=guide_legend("Location")) + 
  coord_cartesian(ylim=c(0,0.25)) +
  facet_wrap(~MM_location)

margin_top <- theme(plot.margin = unit(c(1,1,2,1), "cm"))
margin_bottom <- theme(plot.margin = unit(c(2,1,1,1), "cm"))
p <- grid.arrange(a1+margin_top,b1+margin_top,a2+margin_bottom,b2+margin_bottom, ncol=2, nrow=2)

grid.arrange(p,c,nrow=1, widths = c(0.65,0.35))

# MM_location for Mutations
data.frame(colData(sce_rna_sub)) %>%
  distinct(ImageNumber, .keep_all = T) %>%
  group_by(Mutation, MM_location_simplified) %>%
  summarise(n=n()) %>%
  group_by(Mutation) %>%
  mutate(percentage = n / sum(n) * 100)

B2M and S100A1 expression by Mutation Type

tumor_marker_protein <- c("bCatenin", "Sox9", "pERK", "p75", "Ki67", "SOX10", "PARP", "S100", "MiTF", "IDO1", "PDL1")
tumor_marker_rna <- c("Mart1", "pRB", "B2M")

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

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

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

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

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

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

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

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

# join both data sets
comb <- rbind(dat_prot, dat_rna) %>%
  filter(Mutation %in% c("BRAF", "NRAS", "wt"))

stat.test <- comb %>%
  group_by(channel) %>%
  wilcox_test(data = ., asinh ~ Mutation) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
  add_xy_position(x = "Mutation", dodge = 0.8) %>%
  filter(is.na(y.position) == FALSE)

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

leg <- get_legend(p)

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

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] ggpubr_0.4.0                rstatix_0.6.0              
 [3] coxme_2.2-16                bdsmatrix_1.3-4            
 [5] circlize_0.4.12             ggrepel_0.9.0              
 [7] rms_6.1-0                   SparseM_1.78               
 [9] Hmisc_4.4-2                 Formula_1.2-4              
[11] lattice_0.20-41             reshape2_1.4.4             
[13] ComplexHeatmap_2.4.3        cba_0.2-21                 
[15] proxy_0.4-24                scater_1.16.2              
[17] SingleCellExperiment_1.12.0 SummarizedExperiment_1.20.0
[19] Biobase_2.50.0              GenomicRanges_1.42.0       
[21] GenomeInfoDb_1.26.2         IRanges_2.24.1             
[23] S4Vectors_0.28.1            BiocGenerics_0.36.0        
[25] MatrixGenerics_1.2.0        matrixStats_0.57.0         
[27] gridExtra_2.3               ggbeeswarm_0.6.0           
[29] cowplot_1.1.1               forcats_0.5.0              
[31] stringr_1.4.0               purrr_0.3.4                
[33] readr_1.4.0                 tidyr_1.1.2                
[35] tibble_3.0.4                tidyverse_1.3.0            
[37] ggalluvial_0.12.3           RColorBrewer_1.1-2         
[39] dplyr_1.0.2                 broom_0.7.3                
[41] ggplot2_3.3.3               survival_3.2-7             
[43] data.table_1.13.6           workflowr_1.6.2            

loaded via a namespace (and not attached):
  [1] readxl_1.3.1              backports_1.2.1          
  [3] plyr_1.8.6                splines_4.0.3            
  [5] BiocParallel_1.22.0       TH.data_1.0-10           
  [7] digest_0.6.27             htmltools_0.5.1.1        
  [9] viridis_0.5.1             fansi_0.4.1              
 [11] magrittr_2.0.1            checkmate_2.0.0          
 [13] cluster_2.1.0             openxlsx_4.2.3           
 [15] modelr_0.1.8              sandwich_3.0-0           
 [17] jpeg_0.1-8.1              colorspace_2.0-0         
 [19] rvest_0.3.6               haven_2.3.1              
 [21] xfun_0.20                 crayon_1.3.4             
 [23] RCurl_1.98-1.2            jsonlite_1.7.2           
 [25] zoo_1.8-8                 glue_1.4.2               
 [27] gtable_0.3.0              zlibbioc_1.36.0          
 [29] XVector_0.30.0            MatrixModels_0.4-1       
 [31] GetoptLong_1.0.5          DelayedArray_0.16.0      
 [33] car_3.0-10                BiocSingular_1.4.0       
 [35] shape_1.4.5               abind_1.4-5              
 [37] scales_1.1.1              mvtnorm_1.1-1            
 [39] DBI_1.1.0                 Rcpp_1.0.5               
 [41] viridisLite_0.3.0         htmlTable_2.1.0          
 [43] clue_0.3-58               foreign_0.8-81           
 [45] rsvd_1.0.3                htmlwidgets_1.5.3        
 [47] httr_1.4.2                ellipsis_0.3.1           
 [49] farver_2.0.3              pkgconfig_2.0.3          
 [51] nnet_7.3-14               dbplyr_2.0.0             
 [53] utf8_1.1.4                labeling_0.4.2           
 [55] tidyselect_1.1.0          rlang_0.4.10             
 [57] later_1.1.0.1             munsell_0.5.0            
 [59] cellranger_1.1.0          tools_4.0.3              
 [61] cli_2.2.0                 generics_0.1.0           
 [63] evaluate_0.14             yaml_2.2.1               
 [65] knitr_1.30                fs_1.5.0                 
 [67] zip_2.1.1                 nlme_3.1-151             
 [69] whisker_0.4               quantreg_5.82            
 [71] xml2_1.3.2                compiler_4.0.3           
 [73] rstudioapi_0.13           curl_4.3                 
 [75] beeswarm_0.2.3            png_0.1-7                
 [77] ggsignif_0.6.0            reprex_0.3.0             
 [79] stringi_1.5.3             Matrix_1.3-2             
 [81] vctrs_0.3.6               pillar_1.4.7             
 [83] lifecycle_0.2.0           GlobalOptions_0.1.2      
 [85] BiocNeighbors_1.6.0       bitops_1.0-6             
 [87] irlba_2.3.3               conquer_1.0.2            
 [89] httpuv_1.5.4              R6_2.5.0                 
 [91] latticeExtra_0.6-29       promises_1.1.1           
 [93] rio_0.5.16                vipor_0.4.5              
 [95] codetools_0.2-18          polspline_1.1.19         
 [97] MASS_7.3-53               assertthat_0.2.1         
 [99] rprojroot_2.0.2           rjson_0.2.20             
[101] withr_2.3.0               multcomp_1.4-15          
[103] GenomeInfoDbData_1.2.4    hms_0.5.3                
[105] rpart_4.1-15              rmarkdown_2.6            
[107] DelayedMatrixStats_1.10.1 carData_3.0-4            
[109] git2r_0.28.0              lubridate_1.7.9.2        
[111] base64enc_0.1-3