Last updated: 2021-04-13

Checks: 7 0

Knit directory: melanoma_publication_old_data/

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


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

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

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

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

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

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

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

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

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


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rproj.user/
    Ignored:    ._.DS_Store
    Ignored:    analysis/._clinical metadata preparation.Rmd
    Ignored:    code/.DS_Store
    Ignored:    code/._.DS_Store
    Ignored:    data/.DS_Store
    Ignored:    data/._.DS_Store
    Ignored:    data/data_for_analysis/
    Ignored:    data/full_data/
    Ignored:    output/.DS_Store
    Ignored:    output/._.DS_Store
    Ignored:    output/._protein_neutrophil.png
    Ignored:    output/._rna_neutrophil.png
    Ignored:    output/PSOCKclusterOut/
    Ignored:    output/bcell_grouping.png
    Ignored:    output/dysfunction_correlation.pdf

Unstaged changes:
    Modified:   .gitignore
    Modified:   analysis/10_Dysfunction_Score.rmd
    Modified:   analysis/11_Bcell_Score.Rmd
    Modified:   analysis/Figure_1.rmd
    Modified:   analysis/Figure_2.rmd
    Modified:   analysis/Figure_4.rmd
    Modified:   analysis/Figure_5.rmd
    Modified:   analysis/Summary_Statistics.rmd
    Modified:   analysis/Supp-Figure_1.rmd
    Modified:   analysis/Supp-Figure_2.rmd
    Modified:   analysis/Supp-Figure_4.rmd
    Modified:   analysis/Supp-Figure_5.rmd
    Modified:   analysis/XX_hazard_ratio.rmd

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


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Figure_3.rmd) and HTML (docs/Figure_3.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 545c207 toobiwankenobi 2020-12-22 clean up branch
Rmd 64d1f24 toobiwankenobi 2020-12-22 start new branch with clean scripts
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 d8819f2 toobiwankenobi 2020-10-08 read new data (nuclei expansion) and adapt scripts
Rmd 2c11d5c toobiwankenobi 2020-08-05 add new scripts

Introduction

This script generates plots for Figure 3.

Preparations

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

Load libraries

First, we will load the libraries needed for this part of the analysis.

sapply(list.files("code/helper_functions", full.names = TRUE), source)
        code/helper_functions/calculateSummary.R
value   ?                                       
visible FALSE                                   
        code/helper_functions/censor_dat.R
value   ?                                 
visible FALSE                             
        code/helper_functions/detect_mRNA_expression.R
value   ?                                             
visible FALSE                                         
        code/helper_functions/DistanceToClusterCenter.R
value   ?                                              
visible FALSE                                          
        code/helper_functions/findMilieu.R code/helper_functions/findPatch.R
value   ?                                  ?                                
visible FALSE                              FALSE                            
        code/helper_functions/getInfoFromString.R
value   ?                                        
visible FALSE                                    
        code/helper_functions/getSpotnumber.R
value   ?                                    
visible FALSE                                
        code/helper_functions/plotCellCounts.R
value   ?                                     
visible FALSE                                 
        code/helper_functions/plotCellFractions.R
value   ?                                        
visible FALSE                                    
        code/helper_functions/plotDist.R
value   ?                               
visible FALSE                           
        code/helper_functions/scatter_function.R
value   ?                                       
visible FALSE                                   
        code/helper_functions/sceChecks.R
value   ?                                
visible FALSE                            
        code/helper_functions/validityChecks.R
value   ?                                     
visible FALSE                                 
library(SingleCellExperiment)
library(reshape2)
library(tidyverse)
library(dplyr)
library(umap)
library(data.table) 
library(fpc)
library(ggplot2)
library(cba)
library(ComplexHeatmap)
library(colorRamps)
library(circlize)
library(RColorBrewer)
library(ggbeeswarm)
library(destiny)
library(scater)
library(dittoSeq)
library(gridExtra)
library(ggpmisc)
library(neighbouRhood)
library(cowplot)
library(viridis)
library(ggpubr)
library(rstatix)
library(sf)
library(concaveman)
library(RANN)

Read the data

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

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

Prepare Relation Table

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

Figure 3B

CP output

# Load and prepare
dat_cells = fread(file = "data/data_for_analysis/rna/cell.csv",stringsAsFactors = FALSE)
dat_relation = fread(file = "data/data_for_analysis/rna/Object relationships.csv",stringsAsFactors = FALSE)

# Number of cores used for multicore:
if(detectCores() >= 12){
  ncores = round(detectCores()/1.25,0)
}
if(detectCores() > 1 & detectCores() < 12){
  ncores = round(detectCores()/2,0)
}
if(detectCores() == 1){
  ncores = 1
}

n_perm = 100 

Start the analysis

start = Sys.time()
cur_sce <- as.data.frame(colData(sce_rna))

# add same cellID to dat_cells as in sce object
dat_cells$cellID <- paste("RNA_", paste(dat_cells$ImageNumber, dat_cells$ObjectNumber, sep = "_"), sep = "")

image_df <- data.frame()
for(size in c(2,3,4,5,6)) {
  images <- data.frame()
  for(i in colnames(cur_sce[,grepl("CCL|CXCL",colnames(cur_sce))])){
    # add chemokine info to celltype
    sce_info <- cur_sce[,c("cellID", i , "Description")]
    
    # add celltype information
    dat_cells_tmp <- left_join(as.data.frame(dat_cells), sce_info, by = "cellID")
    
    #assign labels and groups
    dat_cells_tmp$label <- dat_cells_tmp[,i]
    dat_cells_tmp$group <- dat_cells_tmp$Description
    dat_cells_tmp <- as.data.table(dat_cells_tmp)
    
    # subset dat_relation and dat_cells
    dat_cells_sub <- dat_cells_tmp#[dat_cells$Description == "P3",]
    dat_relation_sub <- dat_relation#[dat_relation$`First Image Number` == unique(sce_rna[,sce_rna$Description == "P3"]$ImageNumber),]
    
    # Prepare the data
    d = neighbouRhood::prepare_tables(dat_cells_sub, dat_relation_sub)
    
    # Calculate the baseline statistics
    dat_baseline = neighbouRhood::apply_labels(d[[1]], d[[2]]) %>%
      neighbouRhood::aggregate_classic_patch(., patch_size = size)
    
    # Calculate the permutation statistics
    # This will run the test using parallel computing. The name of the idcol does actually not matter.
    
    set.seed(12312)
    dat_perm = rbindlist(mclapply(1:n_perm, function(x){
      dat_labels = neighbouRhood::shuffle_labels(d[[1]])
      neighbouRhood::apply_labels(dat_labels, d[[2]]) %>%
        neighbouRhood::aggregate_classic_patch(., patch_size = size)
    },mc.cores = ncores
    ), idcol = 'run')
    
    # calc p values
    dat_p <- neighbouRhood::calc_p_vals(dat_baseline, dat_perm, n_perm = n_perm, p_tresh = 0.01) 
    
    # select interactions between chemokine+ cells
    dat_p$interaction <- paste(dat_p$FirstLabel, dat_p$SecondLabel, sep = "_")
    
    dat_p_wide <- dat_p %>%
      reshape2::dcast(group ~ interaction, value.var = "sigval", fill = 0) %>%
      select(group, `1_1`)
    
    summary <- as.data.frame(dat_p_wide) %>%
      group_by(`1_1`) %>%
      summarise(n=n(),.groups = 'drop') %>%
      ungroup() %>%
      mutate(percentage_sig = (n/sum(n)) * 100)
    
    images <- rbind(images, cbind(summary[1,], i))
  }
  
  # calculate percentage of images with significant patches
  images$percentage_sig <- 100 - images$percentage_sig
  images$patch_size <- size
  images <- select(images, percentage_sig, i, patch_size)
  colnames(images) <- c("significant_images", "chemokine", "patch_size")
  
  # add to data.frame
  image_df <- rbind(image_df, images)
}
end = Sys.time()

print(end-start)
Time difference of 23.48571 mins

Visualize

dat <- image_df %>%
  reshape2::dcast(chemokine ~ patch_size, value.var = "significant_images", fill = 0)

rownames(dat) <- dat$chemokine
dat$chemokine <- NULL

m <- t(as.matrix(dat))

col_fun = viridis::inferno(100)

Heatmap(m,
        cluster_rows = FALSE,
        col = col_fun,
        column_title = "Self-Interaction",
        column_title_side = "bottom",
        show_row_names = TRUE,
        cell_fun = function(j, i, x, y, width, height, fill) {
          grid.text(sprintf("%.1f", m[i, j]), x, y, gp = gpar(fontsize = 15, col = "grey"))
          },
        heatmap_legend_param = list(
          title = "% Significant\nImages", at = c(0, 10, 20, 30, 40, 50),
          labels = c("0%", "10%", "20%", "30%","40%", "50%")),
        row_title = "Motif Size",
        row_names_side = "left",
        width = unit(15, "cm"),
        height = unit(8, "cm"))

Calculate p-value for Figure 3B

start = Sys.time()
cur_sce <- as.data.frame(colData(sce_rna))

image_df <- data.frame()
for(size in c(2,3,4,5,6,7,8,9,10)) {
  images <- data.frame()
  for(i in c("CXCL10")){
    # add chemokine info to celltype
    sce_info <- cur_sce[,c("cellID", i , "Description")]
    
    # add celltype information
    dat_cells_tmp <- left_join(as.data.frame(dat_cells), sce_info, by = "cellID")
    
    #assign labels and groups
    dat_cells_tmp$label <- dat_cells_tmp[,i]
    dat_cells_tmp$group <- dat_cells_tmp$Description
    dat_cells_tmp <- as.data.table(dat_cells_tmp)
    
    # subset dat_relation and dat_cells
    dat_cells_sub <- dat_cells_tmp[Description == "P3",]
    dat_relation_sub <- dat_relation[dat_relation$`First Image Number` == unique(sce_rna[,sce_rna$Description == "P3"]$ImageNumber),]
    
    # Prepare the data
    d = neighbouRhood::prepare_tables(dat_cells_sub, dat_relation_sub)
    
    # Calculate the baseline statistics
    dat_baseline = neighbouRhood::apply_labels(d[[1]], d[[2]]) %>%
      neighbouRhood::aggregate_classic_patch(., patch_size = size)
    
    # Calculate the permutation statistics
    # This will run the test using parallel computing. The name of the idcol does actually not matter.
    
    set.seed(12312)
    dat_perm = rbindlist(mclapply(1:n_perm, function(x){
      dat_labels = neighbouRhood::shuffle_labels(d[[1]])
      neighbouRhood::apply_labels(dat_labels, d[[2]]) %>%
        neighbouRhood::aggregate_classic_patch(., patch_size = size)
    },mc.cores = ncores
    ), idcol = 'run')
    
    # calc p values
    dat_p <- neighbouRhood::calc_p_vals(dat_baseline, dat_perm, n_perm = n_perm, p_tresh = 0.01) 
    
    # select interactions between chemokine+ cells
    dat_p$interaction <- paste(dat_p$FirstLabel, dat_p$SecondLabel, sep = "_")
    images <- rbind(images,dat_p)
  }
  
  # calculate percentage of images with significant patches
  images$patch_size <- size
  
  # add to data.frame
  image_df <- rbind(image_df, images)
}

end = Sys.time()
print(end-start)
Time difference of 1.236454 mins
# Significant Self-Interatcions
image_df[image_df$interaction == "1_1",]
   group FirstLabel SecondLabel       p_gt p_lt direction          p   sig
1:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
2:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
3:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
4:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
5:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
6:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
7:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
8:    58          1           1 0.00990099    1      TRUE 0.00990099  TRUE
9:    58          1           1 1.00000000    1     FALSE 1.00000000 FALSE
   sigval interaction patch_size
1:      1         1_1          2
2:      1         1_1          3
3:      1         1_1          4
4:      1         1_1          5
5:      1         1_1          6
6:      1         1_1          7
7:      1         1_1          8
8:      1         1_1          9
9:      0         1_1         10

Figure 3C

Example of CXCL10 Cluster and corresponding Community

example <- findPatch(sce_rna[,sce_rna$ImageNumber == 58], sce_rna[,sce_rna$CXCL10 == 1]$cellID, 
                    'cellID', 
                    'Center_X', 'Center_Y', 
                    'ImageNumber', 
                    distance = 20, 
                    min_clust_size = 10,
                    output_colname = "example_cluster")
Time difference of 1.191686 secs
[1] "patches successfully added to sce object"
example <- findMilieu(example, 
              'cellID', 
              'Center_X', 'Center_Y', 
              'ImageNumber', 
              'example_cluster', 
              distance = 25,
              output_colname = "chemokine_community_i",
              plot = TRUE)
Time difference of 3.529992 secs
[1] "milieus successfully added to sce object"

Zoom-in plot for patch/milieu

example <- findPatch(sce_rna[,sce_rna$ImageNumber == 58], sce_rna[,sce_rna$CXCL10 == 1]$cellID, 
                    'cellID', 
                    'Center_X', 'Center_Y', 
                    'ImageNumber', 
                    distance = 20, 
                    min_clust_size = 10,
                    output_colname = "example_cluster")
Time difference of 0.8591537 secs
[1] "patches successfully added to sce object"
example <- findMilieu(example, 
              'cellID', 
              'Center_X', 'Center_Y', 
              'ImageNumber', 
              'example_cluster', 
              distance = 25,
              output_colname = "chemokine_community_i",
              plot = TRUE,
              xlim = c(725,850),
              ylim = c(500,675),
              point_size = 14)
Warning: Removed 533 rows containing missing values (geom_point).
Time difference of 3.343175 secs
[1] "milieus successfully added to sce object"

Figure 3D

Chemokine-producing cells in Patches

# define fractions of chemokines present in community
cur_dt <- data.frame(colData(sce_rna))

plot_list <- list()

for(i in names(cur_dt[,grepl(glob2rx("*pure"),names(cur_dt))])) {
  chemokine_name <- toupper(str_split(i, "_")[[1]][1])
  
  # select all cells that are in a milieu
  unique_comms <- unique(cur_dt[cur_dt[,i] > 0,i])
  cur_dt_sub <- cur_dt[cur_dt[,i] %in% unique_comms,]
  
  cur_dt_sub <- cbind(cur_dt_sub[,i],
                      cur_dt_sub[,grepl(glob2rx("C*L*"),names(cur_dt_sub))])
  
  colnames(cur_dt_sub)[1] <- i
  
  # add celltype and MM_location_simplified
  cur_dt_sub$cellID <- rownames(cur_dt_sub)
  cur_dt_sub <- left_join(cur_dt_sub, cur_dt[,c("cellID", "celltype", "MM_location_simplified")])
  
  # melt the table
  cur_dt_sub <- cur_dt_sub %>%
    reshape2::melt(id.vars = c("cellID", "celltype", "MM_location_simplified", i), variable.name = "chemokine", value.name = "status")
  
  # all cells that do not produce a chemokine
  non_producer <- cur_dt_sub %>%
    group_by(cellID) %>%
    summarise(sum = sum(status)) %>%
    filter(sum == 0) %>%
    select(cellID)
  
  # all cells that produce a chemokine - regardless of what chemokine
  producer <- cur_dt_sub %>%
    group_by(cellID) %>%
    summarise(sum = sum(status)) %>%
    filter(sum > 0) %>%
    select(cellID)
  
  # select non-producing cells and count
  non_producer <- cur_dt_sub[cur_dt_sub$cellID %in% non_producer$cellID,] %>%
    distinct(cellID, .keep_all = TRUE) %>%
    group_by(celltype, MM_location_simplified, chemokine) %>%
    summarise(n=n())
  
  non_producer$chemokine <- "no chemokine"
  
  # select producing cells and count chemokines
  producer <- cur_dt_sub[cur_dt_sub$cellID %in% producer$cellID,] %>%
    filter(status == 1) %>%
    group_by(celltype, MM_location_simplified, chemokine) %>%
    summarise(n=n())
  
  summary <- rbind(producer, non_producer)
  
  # celltypes numbers
  summary_celltypes <- summary %>%
    group_by(celltype) %>%
    summarise(n=sum(n)) 
  
  # chemokines per celltype numbers
  summary_chemokines <- summary %>%
    group_by(celltype, chemokine) %>%
    summarise(n=sum(n))
  
  # color_vector for cells and chemokines
  col_vector_cells <- metadata(sce_rna)$colour_vector$celltype
  col_vector_chemokines <- metadata(sce_rna)$colour_vectors$chemokine_single
  col_vector <- c(col_vector_cells, col_vector_chemokines)
  # add "no chemokine" to col_vector
  col_vector <- c(col_vector, "white")
  names(col_vector) <- c(names(col_vector[-length(col_vector)]), "no chemokine")
  
  # create labels for middle of sunburst plot
  
  # Number of detected Patches
  numberOfPatches <- paste(length(unique_comms), ifelse(length(unique_comms)>1," Milieus", " Milieu"), sep = "")
  
  # Median Number of Chemokine XY Producing Cells in a Patch
  medianCells <- cur_dt[cur_dt[,i] > 0 & cur_dt[,chemokine_name] == 1,] %>%
    group_by_at(i) %>%
    summarise(n=n()) %>%
    mutate(median = median(n))
  medianCells <- paste(round(unique(medianCells$median)), " Cells", sep = "")
    
  # Percentage of chemokines produced by milieu cells 
  percentageInPatches <- cur_dt[cur_dt[,chemokine_name] == 1,] %>%
    mutate(in_patch = ifelse(.[,i] > 0, 1, 0)) %>%
    group_by(in_patch) %>%
    summarise(n=n()) %>%
    mutate(percentage = n / sum(n) * 100) %>%
    filter(in_patch == 1)
  percentageInPatches <- paste(round(unique(percentageInPatches$percentage)), "%", sep = "")
  
  label <- paste(paste(numberOfPatches, medianCells, sep = "\n"), percentageInPatches, sep = "\n")
  
  # sunburst plot
  plt <- ggplot() + 
    geom_text(aes(x=0,y=0, label = label, size=1)) +
    geom_col(aes(x = 2, y = n, fill = celltype), 
           data = summary_celltypes, 
           color = "white",
           lwd = 1) + 
    geom_col(aes(x = 3, y = n, group = celltype, fill = chemokine), 
           data = summary_chemokines) +
    xlim(0, 3.5) + labs(x = NULL, y = NULL) + 
    scale_fill_manual(values = unname(col_vector),
                        breaks = names(col_vector),
                        labels = names(col_vector)) + 
    ggtitle(chemokine_name) +
    theme_void() +
    theme(axis.ticks=element_blank(),
          plot.margin = unit(c(0,0,0,0), "cm"),
          axis.text=element_blank(),
          axis.title=element_blank(),
          legend.position = "none",
          text = element_text(size = 18),
          plot.title = element_text(hjust = 0.5)) +
        coord_polar(theta = "y")
  
  # add to list
  plot_list[[i]] <- plot_grid(plt)

}

# plot sunburst plots (without CCL4, CCL22, CCL8 - low abundance communities)
plot_grid(plot_list$cxcl8_pure, plot_list$ccl2_pure, 
          plot_list$cxcl10_pure, plot_list$cxcl9_pure,
          plot_list$ccl18_pure, plot_list$ccl19_pure,
          plot_list$cxcl12_pure, plot_list$cxcl13_pure, 
          plot_list$ccl4_pure, plot_list$ccl22_pure,
          plot_list$ccl8_pure, 
          ncol = 3, aligh = "hv")
Warning in as_grob.default(plot): Cannot convert object of class character into
a grob.

Legend for Plot

# create legend for chemokines
lgd1 = Legend(labels = names(col_vector_chemokines), title = "Outer Circle\nChemokine", legend_gp = gpar(fill = unname(col_vector_chemokines)))

# create legend for celltypes
lgd2 = Legend(labels = names(col_vector_cells), title = "Inner Circle\nCell Type ", legend_gp = gpar(fill = unname(col_vector_cells)))

draw(packLegend(lgd2, lgd1, direction = "horizontal"))

Figure 3E

Expression levels in CD8 cells in milieus

milieus <- data.frame(colData(sce_rna)) %>%
  filter(celltype == "CD8+ T cell") %>%
  select(cellID, contains("pure")) %>%
  mutate_if(is.numeric, ~1 * (. > 0))

milieus$number_of_milieus <- rowSums(milieus[,-1])

# keep CD8+ T cells that are part of at least one milieu
milieus <- milieus %>%
  filter(number_of_milieus > 0) %>%
  select(-number_of_milieus) %>%
  reshape2::melt(id.vars = "cellID", variable.name = "milieu", value.name = "is_part") %>%
  filter(is_part > 0) %>%
  select(cellID, milieu)

Marker Profile for different Milieus (for CD8+)

marker_rna <- c("Lag3", "T8_CXCL13", "T5_CCL4")

# rna data 
dat_rna <- data.frame(t(assay(sce_rna[marker_rna, sce_rna$celltype == "CD8+ T cell"], "asinh")))
dat_rna$cellID <- rownames(dat_rna)
dat_rna <- left_join(milieus, dat_rna)

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

# remove CCL4/CCL8/CXCL8 milieus due to too few data points
dat_rna <- dat_rna %>%
  filter(!(milieu %in% c("ccl4_pure", "ccl8_pure", "cxcl8_pure")))

# rename milieus
dat_rna <- dat_rna %>%
  mutate(milieu_short = toupper(str_split(milieu, "_",  n = 2, simplify = TRUE)[,1]))

col_vector_chemokines <- metadata(sce_rna)$colour_vectors$chemokine_single

# add channel medium
dat_rna <- dat_rna %>%
  group_by(channel) %>%
  mutate(channel_median = median(asinh))

# one-sample t test
stat.test <- data.frame()

# loop through all channels (each has a different µ)
for(j in unique(dat_rna$channel)){
  cur.mu <- unique(dat_rna[dat_rna$channel == j, ]$channel_median)
  
  # calculate p-value for different milieus in one channel and adjust pvalue 
  cur.test <- dat_rna[dat_rna$channel == j, ] %>%
    group_by(channel) %>%
    wilcox_test(asinh ~ milieu_short, ref.group = ".all.") %>%
    adjust_pvalue(method = "BH") %>%
    add_x_position(x="milieu_short")
      
  stat.test <- rbind(stat.test, cur.test)
}

# adjust again for testing across different channels
stat.test <- stat.test %>%
  group_by(channel) %>%
  adjust_pvalue(method = "BH") %>%
  add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1))

# plot
plot_list <- list()
ylim_list <- list("Lag3" = c(0,0.9), "T8_CXCL13" = c(0,2.3), "T5_CCL4" = c(0,1))
for(i in unique(dat_rna$channel)){
  cur.stat.test <- stat.test[stat.test$channel == i, ]
  
  plot_list[[i]] <- ggplot(dat_rna[dat_rna$channel == i,], aes(x=milieu_short, y=asinh)) + 
    geom_boxplot(alpha=1, lwd=0.5, outlier.shape = NA, position = position_dodge(1.1), aes(fill=milieu_short)) +
    theme_bw() +
    theme(text = element_text(size=18),
          axis.title.x=element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank()) +
    guides(fill=guide_legend("Milieu", override.aes = list(alpha=1)), col="none") +
    stat_pvalue_manual(
      cur.stat.test, x = "xmin", y.position = ylim_list[[i]][2]-0.05,
      label = "p.adj.signif",
      position = position_dodge(0.8), 
      size=4) + 
    ylab("Mean Expression (asinh)") + 
    xlab("") + 
    geom_hline(aes(yintercept = channel_median, group = channel), colour = 'black', linetype = 2, size=1) + 
    scale_fill_manual(values = unname(col_vector_chemokines),
                      breaks = names(col_vector_chemokines),
                      labels = names(col_vector_chemokines)) + 
    coord_cartesian(ylim=ylim_list[[i]]) +
    facet_wrap(~channel)
}

leg_c <- cowplot::get_legend(plot_list[[1]])

grid.arrange(plot_list[[1]] + theme(legend.position = "none"),
             plot_list[[2]] + theme(legend.position = "none") + ylab(""),
             plot_list[[3]] + theme(legend.position = "none") + ylab(""),
             ncol=2)

Legend

grid.arrange(leg_c)

sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04 LTS

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

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

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

other attached packages:
 [1] RANN_2.6.1                  concaveman_1.1.0           
 [3] sf_0.9-7                    rstatix_0.6.0              
 [5] ggpubr_0.4.0                viridis_0.5.1              
 [7] viridisLite_0.3.0           cowplot_1.1.1              
 [9] neighbouRhood_0.4           magrittr_2.0.1             
[11] dtplyr_1.0.1                ggpmisc_0.3.7              
[13] gridExtra_2.3               dittoSeq_1.0.2             
[15] scater_1.16.2               destiny_3.2.0              
[17] ggbeeswarm_0.6.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                fpc_2.2-9                  
[25] data.table_1.13.6           umap_0.2.7.0               
[27] forcats_0.5.0               stringr_1.4.0              
[29] dplyr_1.0.2                 purrr_0.3.4                
[31] readr_1.4.0                 tidyr_1.1.2                
[33] tibble_3.0.4                ggplot2_3.3.3              
[35] tidyverse_1.3.0             reshape2_1.4.4             
[37] SingleCellExperiment_1.12.0 SummarizedExperiment_1.20.0
[39] Biobase_2.50.0              GenomicRanges_1.42.0       
[41] GenomeInfoDb_1.26.2         IRanges_2.24.1             
[43] S4Vectors_0.28.1            BiocGenerics_0.36.0        
[45] MatrixGenerics_1.2.0        matrixStats_0.57.0         
[47] workflowr_1.6.2            

loaded via a namespace (and not attached):
  [1] reticulate_1.18           tidyselect_1.1.0         
  [3] ranger_0.12.1             BiocParallel_1.22.0      
  [5] munsell_0.5.0             units_0.6-7              
  [7] codetools_0.2-18          withr_2.3.0              
  [9] colorspace_2.0-0          knitr_1.30               
 [11] rstudioapi_0.13           robustbase_0.93-7        
 [13] ggsignif_0.6.0            vcd_1.4-8                
 [15] VIM_6.0.0                 TTR_0.24.2               
 [17] labeling_0.4.2            git2r_0.28.0             
 [19] GenomeInfoDbData_1.2.4    farver_2.0.3             
 [21] pheatmap_1.0.12           rprojroot_2.0.2          
 [23] vctrs_0.3.6               generics_0.1.0           
 [25] xfun_0.20                 ggthemes_4.2.0           
 [27] diptest_0.75-7            R6_2.5.0                 
 [29] clue_0.3-58               rsvd_1.0.3               
 [31] RcppEigen_0.3.3.9.1       locfit_1.5-9.4           
 [33] flexmix_2.3-17            bitops_1.0-6             
 [35] DelayedArray_0.16.0       assertthat_0.2.1         
 [37] promises_1.1.1            scales_1.1.1             
 [39] nnet_7.3-14               beeswarm_0.2.3           
 [41] gtable_0.3.0              rlang_0.4.10             
 [43] scatterplot3d_0.3-41      GlobalOptions_0.1.2      
 [45] hexbin_1.28.2             broom_0.7.3              
 [47] yaml_2.2.1                abind_1.4-5              
 [49] modelr_0.1.8              backports_1.2.1          
 [51] httpuv_1.5.4              tools_4.0.3              
 [53] ellipsis_0.3.1            ggridges_0.5.3           
 [55] Rcpp_1.0.5                plyr_1.8.6               
 [57] zlibbioc_1.36.0           classInt_0.4-3           
 [59] RCurl_1.98-1.2            openssl_1.4.3            
 [61] GetoptLong_1.0.5          zoo_1.8-8                
 [63] haven_2.3.1               ggrepel_0.9.0            
 [65] cluster_2.1.0             fs_1.5.0                 
 [67] RSpectra_0.16-0           openxlsx_4.2.3           
 [69] lmtest_0.9-38             reprex_0.3.0             
 [71] pcaMethods_1.80.0         whisker_0.4              
 [73] hms_0.5.3                 evaluate_0.14            
 [75] smoother_1.1              rio_0.5.16               
 [77] mclust_5.4.7              readxl_1.3.1             
 [79] shape_1.4.5               compiler_4.0.3           
 [81] V8_3.4.0                  KernSmooth_2.23-18       
 [83] crayon_1.3.4              htmltools_0.5.0          
 [85] later_1.1.0.1             lubridate_1.7.9.2        
 [87] DBI_1.1.0                 dbplyr_2.0.0             
 [89] MASS_7.3-53               boot_1.3-25              
 [91] Matrix_1.3-2              car_3.0-10               
 [93] cli_2.2.0                 pkgconfig_2.0.3          
 [95] foreign_0.8-81            laeken_0.5.1             
 [97] sp_1.4-5                  xml2_1.3.2               
 [99] vipor_0.4.5               XVector_0.30.0           
[101] rvest_0.3.6               digest_0.6.27            
[103] rmarkdown_2.6             cellranger_1.1.0         
[105] edgeR_3.30.3              DelayedMatrixStats_1.10.1
[107] curl_4.3                  kernlab_0.9-29           
[109] modeltools_0.2-23         ggplot.multistats_1.0.0  
[111] rjson_0.2.20              lifecycle_0.2.0          
[113] jsonlite_1.7.2            carData_3.0-4            
[115] BiocNeighbors_1.6.0       askpass_1.1              
[117] limma_3.44.3              fansi_0.4.1              
[119] pillar_1.4.7              lattice_0.20-41          
[121] httr_1.4.2                DEoptimR_1.0-8           
[123] glue_1.4.2                xts_0.12.1               
[125] zip_2.1.1                 png_0.1-7                
[127] prabclus_2.3-2            class_7.3-17             
[129] stringi_1.5.3             RcppHNSW_0.3.0           
[131] BiocSingular_1.4.0        irlba_2.3.3              
[133] e1071_1.7-4