Last updated: 2024-02-12

Checks: 6 1

Knit directory: synovialscrnaseq/

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(20210105) 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 58eeb06. 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:    '/
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    .empty/
    Ignored:    analysis/.Rhistory
    Ignored:    analysis/iSEE_interactive_document.html
    Ignored:    code/test_files/
    Ignored:    data/Culemann/
    Ignored:    data/E-MTAB-8322/
    Ignored:    data/Synovial scRNA-seq samples - Sheet1.csv
    Ignored:    data/Zhang_top20_singlecell_cluster_markers_fromGithub.csv
    Ignored:    data/findMarkers_results.rds
    Ignored:    data/findMarkers_results_v2.rds
    Ignored:    data/info/
    Ignored:    data/syn_sce_tidy_filtered.rds
    Ignored:    data/syn_sce_tidy_hvg.rds
    Ignored:    data/syn_sce_tidy_hvg_cms.rds
    Ignored:    docs/
    Ignored:    output/Figures_Paper/
    Ignored:    output/Sample_summaries_RA_comparisons.rds
    Ignored:    output/Sample_summaries_direct_dissociation.rds
    Ignored:    output/Sample_summaries_exvivo_treatment.rds
    Ignored:    output/Suppl_Figure_4d.rds
    Ignored:    output/barcodes.txt
    Ignored:    output/barcodes_filtered.txt
    Ignored:    output/column_metadata_filtered.txt
    Ignored:    output/combined_v7_SingleR_markers.rds
    Ignored:    output/combined_v7_SingleR_predictions.rds
    Ignored:    output/combined_v7_SingleR_predictions_lclc.rds
    Ignored:    output/combined_v7_SingleR_predictions_reclc.rds
    Ignored:    output/combined_v7_SingleR_predictions_recrec.rds
    Ignored:    output/combined_v7_SingleR_trained.rds
    Ignored:    output/combined_v7_sce.rds
    Ignored:    output/combined_v7_sce_filtered.rds
    Ignored:    output/combined_v7_sce_hvg.rds
    Ignored:    output/combined_v7_sce_hvg_cms.rds
    Ignored:    output/combined_v7_sce_hvg_cms_annotated.rds
    Ignored:    output/combined_v7_sce_tmp_hvg_cms.rds
    Ignored:    output/combined_v7_upsetplot_genelists.rds
    Ignored:    output/count_matrix_filtered.mtx
    Ignored:    output/count_matrix_unfiltered.mtx
    Ignored:    output/emptyDrops_result_v4.rds
    Ignored:    output/emptyDrops_result_v4_tmp.rds
    Ignored:    output/emptyDrops_result_v4tmptmp.rds
    Ignored:    output/findMarkers_results_v6.rds
    Ignored:    output/findMarkers_results_v6_ec.rds
    Ignored:    output/findMarkers_results_v6_main.rds
    Ignored:    output/findMarkers_results_v6_mp.rds
    Ignored:    output/findMarkers_results_v6_sf.rds
    Ignored:    output/findMarkers_results_v6_tc.rds
    Ignored:    output/findMarkers_results_v7_ec.rds
    Ignored:    output/findMarkers_results_v7_main.rds
    Ignored:    output/findMarkers_results_v7_mp.rds
    Ignored:    output/findMarkers_results_v7_sf.rds
    Ignored:    output/findMarkers_results_v7_tc.rds
    Ignored:    output/genes.txt
    Ignored:    output/genes_filtered.txt
    Ignored:    output/goana_results_v6_ec.rds
    Ignored:    output/goana_results_v6_mp.rds
    Ignored:    output/preprocessing_number_of_cells.rds
    Ignored:    output/syn_v4_sce_emptyDrops_invivo.rds
    Ignored:    output/syn_v4_swappedDrops_24300_after.rds
    Ignored:    output/syn_v4_swappedDrops_24300_before.rds
    Ignored:    output/syn_v4_swappedDrops_24793_after.rds
    Ignored:    output/syn_v4_swappedDrops_24793_before.rds
    Ignored:    output/syn_v6_cluster_cellid_match_invivo.rds
    Ignored:    output/syn_v6_clustering_lookup_invivo.rds
    Ignored:    output/syn_v6_clustering_lookup_multiple_invivo.rds
    Ignored:    output/syn_v6_sce.rds
    Ignored:    output/syn_v6_sce_Figure8.rds
    Ignored:    output/syn_v6_sce_Figure8_dic_ls.rds
    Ignored:    output/syn_v6_sce_ec_invivo.rds
    Ignored:    output/syn_v6_sce_filtered_invivo.rds
    Ignored:    output/syn_v6_sce_hdf5/
    Ignored:    output/syn_v6_sce_hvg_cms_doublet_invivo.rds
    Ignored:    output/syn_v6_sce_hvg_cms_doublet_subcluster_invivo.rds
    Ignored:    output/syn_v6_sce_hvg_invivo.rds
    Ignored:    output/syn_v6_sce_hvg_marker_genes.rds
    Ignored:    output/syn_v6_sce_mp_invivo.rds
    Ignored:    output/syn_v6_sce_sf_invivo.rds
    Ignored:    output/syn_v6_sce_tc_invivo.rds
    Ignored:    output/syn_v6_sfig1.rds
    Ignored:    output/syn_v6_vst_out_invivo.rds
    Ignored:    output/syn_v7_cluster_cellid_match_invivo.rds
    Ignored:    output/syn_v7_clustering_lookup_invivo.rds
    Ignored:    output/syn_v7_clustering_lookup_multiple_invivo.rds
    Ignored:    output/syn_v7_sce.rds
    Ignored:    output/syn_v7_sce_Figure8.rds
    Ignored:    output/syn_v7_sce_Figure8_dic_ls.rds
    Ignored:    output/syn_v7_sce_ec_invivo.rds
    Ignored:    output/syn_v7_sce_ec_invivo_trajectory.rds
    Ignored:    output/syn_v7_sce_ec_invivo_trajectory2.rds
    Ignored:    output/syn_v7_sce_ec_invivo_trajectory2_ATres.rds
    Ignored:    output/syn_v7_sce_ec_invivo_trajectory_icMat.rds
    Ignored:    output/syn_v7_sce_filtered_invivo.rds
    Ignored:    output/syn_v7_sce_hdf5/
    Ignored:    output/syn_v7_sce_hvg_cms_doublet_invivo.rds
    Ignored:    output/syn_v7_sce_hvg_cms_doublet_subcluster_invivo.rds
    Ignored:    output/syn_v7_sce_hvg_cms_doublet_subcluster_invivo_cleaned.rds
    Ignored:    output/syn_v7_sce_hvg_invivo.rds
    Ignored:    output/syn_v7_sce_mp_invivo.rds
    Ignored:    output/syn_v7_sce_sf_invivo.rds
    Ignored:    output/syn_v7_sce_tc_invivo.rds
    Ignored:    output/syn_v7_sfig1.rds
    Ignored:    output/syn_v7_vst_out_invivo.rds

Untracked files:
    Untracked:  analysis/clean_and_save_sce.R
    Untracked:  analysis/description_integration_wei_stephenson
    Untracked:  analysis/scRNAseq_complete_01_preprocessing_comparison.Rmd
    Untracked:  analysis/scRNAseq_complete_05_ec_trajectory_analysis.Rmd
    Untracked:  analysis/scRNAseq_complete_05_ec_trajectory_analysis_2.Rmd
    Untracked:  analysis/scRNAseq_complete_05_ec_trajectory_analysis_3.Rmd
    Untracked:  code/plot_utilities.Rmd
    Untracked:  code/rebuild_ezRun.R
    Untracked:  code/tmp1.R
    Untracked:  code/tmp1.Rmd
    Untracked:  nonhosted_public/
    Untracked:  singRstudio.sh.bak

Unstaged changes:
    Modified:   analysis/scRNAseq_combined_06_Figures.Rmd
    Modified:   analysis/scRNAseq_complete_04-2_celltype_markers.Rmd
    Modified:   analysis/scRNAseq_complete_04-2_celltype_markers_subcelltypes.Rmd
    Modified:   analysis/scRNAseq_complete_04_Annotation_v7.Rmd
    Modified:   analysis/scRNAseq_complete_Figures.Rmd
    Modified:   analysis/write_tsv.Rmd
    Modified:   code/create_hdf5.R

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/scRNAseq_complete_Figures.Rmd) and HTML (public/scRNAseq_complete_Figures.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 58eeb06 Reto Gerber 2023-05-30 add new version
html 58eeb06 Reto Gerber 2023-05-30 add new version
Rmd 4575ba6 Reto Gerber 2022-12-21 Update analyis
Rmd e786402 Reto Gerber 2022-05-28 update figures to final version of paper
html e786402 Reto Gerber 2022-05-28 update figures to final version of paper
Rmd 0f8368f Reto Gerber 2022-05-20 update figures
html 0f8368f Reto Gerber 2022-05-20 update figures
Rmd 5a6aa2a Reto Gerber 2022-04-25 rerun with small resolution
html 5a6aa2a Reto Gerber 2022-04-25 rerun with small resolution
Rmd 3443cc6 Reto Gerber 2022-04-25 Update
html 3443cc6 Reto Gerber 2022-04-25 Update
Rmd b5b139f Reto Gerber 2022-03-29 Update analysis

Set up

suppressPackageStartupMessages({
  library(dplyr)
  library(ggplot2)
  library(purrr)
  library(stringr)
  library(scater)
  library(scran)
  library(igraph)
  library(scuttle)
  library(tidySingleCellExperiment)
  library(magrittr)
  library(ComplexHeatmap)
})
n_workers <- 20
RhpcBLASctl::blas_set_num_threads(n_workers)
here::here()
[1] "/home/retger/Synovial/synovialscrnaseq"
source(here::here("code","utilities_plots.R"))
analysis_version <- 7

set.seed(100)
sce_main <- readRDS(file =here::here("output",paste0("syn_v",analysis_version,"_sce_hvg_cms_doublet_subcluster_invivo.rds")))

Supplementary Figure 8

pltls <- readRDS(file = here::here("output",paste0("syn_v",analysis_version,"_sfig1.rds")))

names(pltls)
 [1] "sfig1a1"            "sfig1a2"            "sfig1b1"           
 [4] "sfig1b2"            "syn_nest_Sample"    "syn_nest_diagnosis"
 [7] "sfig1c1"            "sfig1c2"            "sfig1d1"           
[10] "sfig1d2"           
pltls$sfig1b1 <- ggpubr::ggarrange(
  ggplot(pltls$syn_nest_Sample, aes(x = Sample, y = n_cells, fill = n_nonzero_genes)) +  # Plot with values on top
    geom_bar(stat = "identity") +
    geom_text(aes(label = n_cells), vjust = 0) +
    labs(title = "", x="", fill="Number of genes", y="Number of cells") +
  main_plot_theme() +
    theme(axis.text.x = element_text(angle = 45,hjust=1), axis.ticks.x=element_blank())+ 
    theme(legend.title = element_text(size=6)),
  ggplot(pltls$syn_nest_Sample, aes(x = Sample, y = n_cells, fill = n_1perc_cells_genes)) +  # Plot with values on top
    geom_bar(stat = "identity") +
    geom_text(aes(label = n_cells), vjust = 0) +
    labs(title = "", x="", 
         fill="Number of genes\nin at least \n1% of cells",  y="Number of cells") +
    theme(axis.text.x = element_text(angle = 45,hjust=1), axis.ticks.x=element_blank()) +
  main_plot_theme()+ theme(legend.title = element_text(size=6)), 
  nrow = 2)

samcol <- sample_cols(sort(unique(pltls$syn_nest_Sample$Sample)))
names(samcol) <- sort(unique(pltls$syn_nest_Sample$Sample))

plt <- ggpubr::ggarrange(
  ggpubr::ggarrange((pltls$sfig1a1 + main_plot_theme()+ theme(strip.text = element_text(size=11))), (pltls$sfig1a2 + main_plot_theme()+ theme(strip.text = element_text(size=11))), ncol = 2),
  pltls$sfig1b1 + main_plot_theme(),
                    (pltls$sfig1c2) + scale_fill_manual(values=samcol) + main_plot_theme()+ facet_wrap(~1)+theme(strip.text.x = element_blank()),
                    (pltls$sfig1d2) + scale_fill_manual(values=samcol) + main_plot_theme()+ facet_wrap(~1)+theme(strip.text.x = element_blank()),
  ncol = 1, nrow = 4,labels = "auto", font.label=list(size=8)
)
Scale for 'fill' is already present. Adding another scale for 'fill', which
will replace the existing scale.
Scale for 'fill' is already present. Adding another scale for 'fill', which
will replace the existing scale.
plt

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
0f8368f Reto Gerber 2022-05-20
5a6aa2a Reto Gerber 2022-04-25
figname <- "Suppl_Figure_8"
width <- 22
height <- 30
res = 300
maxwidth <- 8.5
maxheight <- 11
downscale <- max(c(3,height/maxheight, width/maxwidth))
# ideally multiply by 'downscale' but imagemagick throws error for too large images
# initres <- res*1.2
initres <- res
magick_geometry <- paste0(width/downscale*res,"x",height/downscale*res)

plt <- plt +
  labs(title=paste0("Figure S",stringr::str_extract(figname,"[[:digit:]]+$"))) + 
  theme(plot.title = element_text(size=10*downscale))

tiff(here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".tiff")),width=width,height=height,res = initres, units = "in", compression="zip")
plt + theme(plot.title = element_text(size=10*downscale, family="Arial"))
dev.off()
pdf 
  2 
# system(paste0("convert -geometry ",magick_geometry," ", here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".tiff")), " ",here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".tiff"))))

jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".jpeg")),width=width,height=height,res = initres, units = "in")
plt + theme(plot.title = element_text(size=10*downscale, family="Arial"))
dev.off()
pdf 
  2 
# system(paste0("convert -geometry ",magick_geometry," ", here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".jpeg")), " ",here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".jpeg"))))

pdf(here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".pdf")),width=width,height=height)
plt
dev.off()
pdf 
  2 
# function to get center of column
get_celltype_centers <- function(sce, dimred, column){
    as.data.frame(reducedDim(sce,"UMAP_corrected")) %>% 
    dplyr::mutate(V3=sce[[column]]) %>% 
    dplyr::group_by(V3) %>% 
    dplyr::summarise(V1=mean(as.numeric(V1)),
                     V2=mean(as.numeric(V2)))
}
# move center of column
move_label <- function(celltype_centers,val=0, ax="X", what=NULL){
  if(is.null(what)){
    if(ax=="X"){
      celltype_centers$V1 <- celltype_centers$V1 + val
    } else if(ax=="Y"){
      celltype_centers$V2 <- celltype_centers$V2 + val
    }
  } else {
    stopifnot(what %in% celltype_centers$V3)
    if(ax=="X"){
      celltype_centers$V1[celltype_centers$V3 == what] <- celltype_centers$V1[celltype_centers$V3 == what] + val
    } else if(ax=="Y"){
      celltype_centers$V2[celltype_centers$V3 == what] <- celltype_centers$V2[celltype_centers$V3 == what] + val
    }
  }
  celltype_centers
}

# umap plot with labels
customUMAP <- function(sce,column,column_colors, celltype_centers,column_labels){
  set.seed(1234)
  si <- sample(seq_along(sce$Protocol))  
    
  plotReducedDim(sce[,si],"UMAP_corrected", colour_by=column, point_alpha=0.8, point_size=0.1)+  
    scale_color_manual(values= column_colors, 
                       breaks=names(column_colors), 
                       labels=column_labels,
                       guide=guide_legend(
                         override.aes = list(
                           shape = c(rep(15,length(column_colors))),
                         size= rep(10,length(column_colors)),
                         alpha=rep(1,length(column_colors))
                           )
                         )) +
    geom_label(aes(V1,V2,label=V3),data=celltype_centers,size=6) +
    # coord_fixed() +
    main_plot_theme() +
    labs(color="", x="UMAP 1", y="UMAP 2") 
}

# function to get proportions df
customBarplotDF <- function(sce, column, facet_by, aggr_by){
  propdf <- table(colData(sce)[[column]], 
                  sce[[facet_by]], sce[[aggr_by]]) %>% 
    as.data.frame() %>% 
    dplyr::rename(!!column := Var1,
                  !!facet_by := Var2,
                  !!aggr_by := Var3,
                  Abundance = Freq) %>% 
    dplyr::group_by(!!sym(aggr_by)) %>% 
    dplyr::filter(Abundance > 0) %>% 
    dplyr::mutate(Proportion = Abundance/sum(Abundance)) %>% 
    dplyr::left_join(colData(sce) %>% 
                     as.data.frame() %>% 
                     dplyr::select(!!dplyr::sym(aggr_by),!!dplyr::sym(facet_by)) %>% 
                     unique()
                   # by="Sample"
                   )
  
  # add missing datapoints
  allcombs <- expand.grid(Var1=unique(sce[[column]]),
              Var2=unique(sce[[aggr_by]]))
  colnames(allcombs) <- c(column, aggr_by)
  allcombs <- dplyr::left_join(allcombs,
                   colData(sce) %>%
                     as.data.frame() %>%
                     dplyr::select(!!dplyr::sym(aggr_by),!!dplyr::sym(facet_by)) %>%
                     unique()
                   # by=aggr_by
  )  
  propdf <- dplyr::right_join(propdf,allcombs) %>% 
    dplyr::mutate(Abundance=ifelse(is.na(Abundance),0,Abundance),
                  Proportion=ifelse(is.na(Proportion),0,Proportion))
}

# barplot based on proportions df
customBarplot <- function(propdf, column, facet_by, aggr_by,fill_lab, column_colors, column_labels){
  propdf %>% 
    ggplot(aes(x = !!sym(aggr_by), y = Proportion, fill=!!sym(column))) +
    geom_bar(stat = "identity") +
    # theme_classic() +
    theme(axis.text.x = element_text(angle = 45,hjust=1),
          strip.text.y = element_text(angle=0,size=7)) +
    labs(x="",fill=fill_lab)+
    scale_fill_manual(values=column_colors, breaks=names(column_colors), labels=column_labels) +
    main_plot_theme()#+ 
    # facet_grid(cols=vars(!!sym(facet_by)),scales = "free_x", space="free")
}

# boxplot based on proportions df
customBoxplot <- function(propdf, column, facet_by,column_colors){
  propdf %>% 
    ggplot() + 
    geom_boxplot(aes(y=Proportion,x=!!sym(column), color=!!sym(column)),outlier.shape = NA) +
    geom_jitter(aes(y=Proportion,x=!!sym(column), color=!!sym(column)), size = 2) +
    scale_color_manual(values=column_colors) +
    labs(y="Proportion",x="") +
    theme(legend.position = "none") +
    # facet_wrap(vars(!!sym(column)), scales = "free_y",nrow = 2)+
    main_plot_theme()  +
    theme(axis.text.x = element_text(angle = 45,hjust=1),
          strip.text.y = element_text(angle=0,size=7),
          strip.text.x = element_text(family = "Helvetica",face = "bold"))
}

Supplementary Figure 9

sce <- sce_main
column <- "main_celltype"
aggr_by="Sample"
facet_by="Sample_prep"
fill_lab = "Main celltypes"

# diagnosis_colors <- get_colors("diagnosis")
# diagnosis_colors <- diagnosis_colors[names(diagnosis_colors) %in% unique(sce$Diagnosis_main)]

main_celltypes_colors <- get_colors("main_celltypes")
main_celltypes_colors <- main_celltypes_colors[names(main_celltypes_colors) %in% unique(sce[[column]])]
main_celltypes_colors <- main_celltypes_colors[match(celltype_order(),names(main_celltypes_colors))]
names(main_celltypes_colors) <- stringr::str_replace_all(names(main_celltypes_colors), "/","\n")

sce[[column]] <- stringr::str_replace_all(sce[[column]], "/","\n")
sce[[column]] <- factor(sce[[column]],levels=stringr::str_replace_all(celltype_order(), "/","\n"))

celltype_centers <- get_celltype_centers(sce, "UMAP_corrected", column)
celltype_centers %<>% move_label(0.6,"Y")
celltype_centers %<>% move_label(1,"X","Plasmacytoid DCs")
celltype_centers %<>% move_label(1.3,"X","Dendritic cells")
# celltype_centers %<>% move_label(0.8,"Y","Dendritic cells")
celltype_centers %<>% move_label(0.5,"Y","Pericytes\nMural cells")
# celltype_centers %<>% move_label(1,"X","Endothelial cells")
# celltype_centers %<>% move_label(0.5,"Y","Endothelial cells")


pl1 <- customUMAP(sce, column, main_celltypes_colors, celltype_centers, names(main_celltypes_colors))
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
propdf <- customBarplotDF(sce, column, facet_by, aggr_by)
Joining, by = c("Sample_prep", "Sample")
Joining, by = "Sample"
Joining, by = c("main_celltype", "Sample_prep", "Sample")
propdf$Sample <- factor(as.character(propdf$Sample),levels=unique(as.character(propdf$Sample)))

pl2 <- propdf %>% 
    dplyr::mutate(!!column := factor(as.character(!!sym(column)), levels = stringr::str_replace_all(celltype_order(), "/","\n"))) %>% 
  customBarplot(column, facet_by, aggr_by, fill_lab,main_celltypes_colors, names(main_celltypes_colors))

pl3 <- propdf %>% 
  dplyr::mutate(!!column := factor(as.character(!!sym(column)), levels = stringr::str_replace_all(celltype_order(), "/","\n")))  %>% 
  customBoxplot(column, facet_by,main_celltypes_colors)

plt <- ggpubr::ggarrange(pl1,pl2,pl3,nrow=3, labels = "auto", heights = c(5,3,3), font.label=list(size=26), vjust=1)
plt

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
0f8368f Reto Gerber 2022-05-20
5a6aa2a Reto Gerber 2022-04-25
figname <- "Suppl_Figure_9"
width <- 15 
height <- 25
res = 300
maxwidth <- 8.5
maxheight <- 11
downscale <- max(c(3,height/maxheight, width/maxwidth))
# ideally multiply by 'downscale' but imagemagick throws error for too large images
# initres <- res*1.2
initres <- res
magick_geometry <- paste0(width/downscale*res,"x",height/downscale*res)

plt <- plt +
  labs(title=paste0("Figure S",stringr::str_extract(figname,"[[:digit:]]+$"))) + 
  theme(plot.title = element_text(size=10*downscale))

tiff(here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".tiff")),width=width,height=height,res = initres, units = "in", compression="zip")
plt + theme(plot.title = element_text(size=10*downscale, family="Arial"))
dev.off()
pdf 
  2 
# system(paste0("convert -geometry ",magick_geometry," ", here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".tiff")), " ",here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".tiff"))))

jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".jpeg")),width=width,height=height,res = initres, units = "in")
plt + theme(plot.title = element_text(size=10*downscale, family="Arial"))
dev.off()
pdf 
  2 
# system(paste0("convert -geometry ",magick_geometry," ", here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".jpeg")), " ",here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".jpeg"))))

pdf(here::here("..","synovialscrnaseq","output","Figures_Paper",paste0(figname,".pdf")),width=width,height=height)
plt
dev.off()
pdf 
  2 

Figure 4

celltype_name_pre <- "tc"
order_celltypes <- c(4,5,1,6,7,8,2,3,9)
# order_celltypes <- NULL
used_clustering <- "tc_clusters_final"
tmpfilename <- paste0("syn_v",analysis_version,"_sce_",celltype_name_pre,"_invivo",".rds")
sce_sub_tc <- readRDS(file = here::here("output",tmpfilename))
sce <- sce_sub_tc
column <- "tc_clusters_final"
column_labels <- "tc_celltype"
aggr_by="Sample"
facet_by="Sample_prep"
fill_lab = "T cells / NK cells"
sce[[column]] <- factor(sce[[column]],levels = order_celltypes)
dic_tc <- unique(as.data.frame(colData(sce)[,c(column,column_labels)])) %>% 
  dplyr::arrange(!!dplyr::sym(column))

# subcelltype_colors <- viridis::viridis(length(dic_tc[[column]]))
subcelltype_colors <- rainbow(length(dic_tc[[column]]))[order(as.character(dic_tc[[column]]))]
names(subcelltype_colors) <- dic_tc[[column]]
column_names <- paste0(dic_tc[[column]], " - ",dic_tc[[column_labels]])
dic_tc$colors <- subcelltype_colors
dic_tc$column_names <- column_names

celltype_centers <- get_celltype_centers(sce, "UMAP_corrected", column)
celltype_centers %<>% move_label(0.5,"Y",9)

# customUMAP(sce, column, subcelltype_colors, celltype_centers)

pl1tc <- customUMAP(sce, column, subcelltype_colors, celltype_centers,column_names) +
  labs(color=fill_lab)
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
propdf <- customBarplotDF(sce, column, facet_by, aggr_by)
Joining, by = c("Sample_prep", "Sample")
Joining, by = "Sample"
Joining, by = c("tc_clusters_final", "Sample_prep", "Sample")
propdf$Sample <- factor(as.character(propdf$Sample),levels=unique(as.character(propdf$Sample)))

pl2tc <- propdf %>% 
    dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n")) %>% 
  customBarplot(column, facet_by, aggr_by, fill_lab, subcelltype_colors,column_names)


leg <- ggpubr::get_legend(pl2tc)
# str(leg)
# Convert to a ggplot and print
# ggpubr::as_ggplot(leg) 
subsets <- list(`CD3+ CD4+ T cells                                `=c(4,5,1),
                `CD3+ CD8+ T cells                                `=c(6,7,8),
                `Proliferating T and NK cells                `=c(2),
                `NK cells                                               `=c(3),
                `Innate lymphoid cells                        `=c(9))
legls <- purrr::map(seq_along(subsets),~{
  propdf %>% 
      dplyr::filter(tc_clusters_final %in% subsets[[.x]]) %>% 
      dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n"),
                    !!sym(column):=droplevels(!!sym(column))) %>% 
    customBarplot(column, facet_by, aggr_by, names(subsets)[.x], subcelltype_colors[names(subcelltype_colors) %in% subsets[[.x]]],column_names[names(subcelltype_colors) %in% subsets[[.x]]]) %>% 
    ggpubr::get_legend() %>% 
    ggpubr::as_ggplot() 
})
legls <- c(legls,list(ggplot() + theme_void()))
pl2tc_lg <- ggpubr::ggarrange(plotlist=legls,ncol=1, align="hv", heights = c(2,2,2,2,2,6))



pl3tc <- propdf %>% 
  customBoxplot(column, facet_by,subcelltype_colors) +
  theme(axis.text.x = element_text(angle = 0,hjust=0.5, face="bold", size=16))

pl4tc <- readRDS(here::here("..","synovialscrnaseq","output","Suppl_Figure_4d.rds"))



# ggpubr::ggarrange(pl1tc,pl2tc,nrow=1, ncol=2, labels = "AUTO", widths = c(5,4), 
#                   common.legend = TRUE, legend = "right")
plt <- ggpubr::ggarrange(
  ggpubr::ggarrange(pl1tc + theme(legend.position = "none"),
                    pl2tc + theme(legend.position = "none"),
                    pl2tc_lg,nrow=1, ncol=3, widths = c(5,5,3), legend = NULL, 
                  labels=c("a", "b",""), font.label=list(size=26)),
  pl3tc,
      grid.grabExpr(draw(pl4tc,align_annotation_legend="heatmap_center",newpage = FALSE, merge_legends=TRUE,align_heatmap_legend="heatmap_center",padding = unit(c(10, 10, 10, 10), "mm")), width = 22, height = 20,wrap=TRUE),
  labels = c("","c","d"), ncol=1, nrow=3, font.label=list(size=26), heights = c(2,1,2)
)
plt

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
tiff(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_4.tiff"),width=22,height=26,res = 300, units = "in", compression="zip")
plt
dev.off()
pdf 
  2 
jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_4.jpeg"),width=22,height=26,res = 300, units = "in")
plt
dev.off()
pdf 
  2 
pdf(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_4.pdf"),width=22,height=26)
plt
dev.off()
pdf 
  2 

Figure 5

celltype_name_pre <- "sf"
# order_celltypes <- c(5,8,2,3,4,6,1,7)
order_celltypes <- c(3,7,5,4,6,1,2)
tmpfilename <- paste0("syn_v",analysis_version,"_sce_",celltype_name_pre,"_invivo",".rds")
sce_sub_sf <- readRDS(file = here::here("output",tmpfilename))
sce <- sce_sub_sf
column <- "sf_clusters_final"
column_labels <- "sf_celltype"
aggr_by="Sample"
facet_by="Sample_prep"
fill_lab = "Fibroblasts"
sce[[column]] <- factor(sce[[column]],levels = order_celltypes)
dic_sf <- unique(as.data.frame(colData(sce)[,c(column,column_labels)])) %>% 
  dplyr::arrange(!!dplyr::sym(column))
# subcelltype_colors <- viridis::viridis(length(dic_sf[[column]]))
subcelltype_colors <- rainbow(length(dic_sf[[column]]))[order(as.character(dic_sf[[column]]))]
names(subcelltype_colors) <- dic_sf[[column]]
column_names <- paste0(dic_sf[[column]], " - ",dic_sf[[column_labels]])
dic_sf$colors <- subcelltype_colors
dic_sf$column_names <- column_names

celltype_centers <- get_celltype_centers(sce, "UMAP_corrected", column)

pl1sf <- customUMAP(sce, column, subcelltype_colors, celltype_centers,column_names) +
  labs(color=fill_lab) +
  coord_fixed()
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
propdf <- customBarplotDF(sce, column, facet_by, aggr_by)
Joining, by = c("Sample_prep", "Sample")
Joining, by = "Sample"
Joining, by = c("sf_clusters_final", "Sample_prep", "Sample")
propdf$Sample <- factor(as.character(propdf$Sample),levels=unique(as.character(propdf$Sample)))

pl2sf <- propdf %>% 
    dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n")) %>% 
  customBarplot(column, facet_by, aggr_by, fill_lab, subcelltype_colors,column_names)

leg <- ggpubr::get_legend(pl2sf)
# str(leg)
# Convert to a ggplot and print
# ggpubr::as_ggplot(leg)
subsets <- list(`Lining SF PRG4high/med THY1low         `=c(3),
                `Transitional SF PRG4med THY1low/high`=c(7,5,4),
                `Sublining SF PRG4low THY11high          `=c(6,1,2))
legls <- purrr::map(seq_along(subsets),~{
  propdf %>% 
      dplyr::filter(sf_clusters_final %in% subsets[[.x]]) %>% 
      dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n"),
                    !!sym(column):=droplevels(!!sym(column))) %>% 
    customBarplot(column, facet_by, aggr_by, names(subsets)[.x], subcelltype_colors[names(subcelltype_colors) %in% subsets[[.x]]],column_names[names(subcelltype_colors) %in% subsets[[.x]]]) %>% 
    ggpubr::get_legend() %>% 
    ggpubr::as_ggplot() 
})
legls <- c(legls,list(ggplot() + theme_void()))
pl2sf_lg <- ggpubr::ggarrange(plotlist=legls,ncol=1, align="hv", heights = c(1,2,2,5))

pl3sf <- propdf %>% 
  customBoxplot(column, facet_by,subcelltype_colors) +
  theme(axis.text.x = element_text(angle = 0,hjust=0.5, face="bold", size=16))

# pl4sftmp <- scater::plotExpression(sce, c("SDC4","SAA1", "SAA2", "CCL20"), 
#                        x=column,colour_by=column, ncol=5) +
#     scale_color_manual(values=subcelltype_colors, breaks=names(subcelltype_colors), labels=column_names) +
#   main_plot_theme() +
#   labs(x="")
# 
# pl4sf <- ggpubr::ggarrange(pl4sftmp + theme(legend.position = "none"),ggplot() + theme_void(), ncol = 2, nrow=1, widths = c(4,1))

genes_to_plot <- c("SDC4","SAA1", "SAA2", "CCL20")
genes_to_plot <- genes_to_plot[genes_to_plot %in% rownames(sce)]

pltls <- purrr::map(genes_to_plot, ~{
  plotReducedDim(sce,"UMAP_corrected",colour_by = .x, point_size=0.1) +
    labs(x="UMAP 1", y="UMAP 2") +
    geom_label(aes(V1,V2,label=V3),data=celltype_centers) +
    main_plot_theme() +
    labs(title=.x) +
    coord_fixed()
  })
pl4sf <- ggpubr::ggarrange(plotlist=pltls, ncol = 4, nrow = 1, font.label=list(size=26))


pl5sf <- scater::plotExpression(sce, c("SERPINE1", "COL5A3", "LOXL2", "TGFBI", "TGFB1"), 
                       x=column,colour_by=column, ncol=5, point_size=0.1) +
    scale_color_manual(values=subcelltype_colors, breaks=names(subcelltype_colors), labels=column_names) +
  main_plot_theme() +
  labs(x="") +
  coord_fixed()
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
genes_to_plot <- c("C3", "CXCL14")
genes_to_plot <- genes_to_plot[genes_to_plot %in% rownames(sce)]

pltls <- purrr::map(genes_to_plot, ~{
  plotReducedDim(sce,"UMAP_corrected",colour_by = .x, point_size=0.1) +
    labs(x="UMAP 1", y="UMAP 2") +
    geom_label(aes(V1,V2,label=V3),data=celltype_centers) +
    main_plot_theme() +
    labs(title=.x) +
    coord_fixed()
  })
pl6sf <- ggpubr::ggarrange(plotlist=pltls, ncol = 2, nrow = 1, font.label=list(size=26))

pl7sf <-   plotReducedDim(sce,"UMAP_corrected",colour_by = "MMP13", point_size=0.1) +
    labs(x="UMAP 1", y="UMAP 2") +
    geom_label(aes(V1,V2,label=V3),data=celltype_centers) +
    main_plot_theme() +
    labs(title="MMP13")

pl7sf <- scater::plotExpression(sce, c("MMP13"), 
                       x=column,colour_by=column, ncol=1, point_size=0.1) +
    scale_color_manual(values=subcelltype_colors, breaks=names(subcelltype_colors), labels=column_names) +
  main_plot_theme() +
  labs(x="",colour="")
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
# ggpubr::ggarrange(pl1sf,pl2sf,nrow=1, ncol=2, labels = "AUTO", widths = c(5,4),
#                   common.legend = TRUE, legend = "right")
plt <- ggpubr::ggarrange(
  ggpubr::ggarrange(pl1sf + theme(legend.position = "none"),
                    pl2sf + theme(legend.position = "none"),
                    pl2sf_lg,nrow=1, ncol=3, widths = c(5,5,3), legend = NULL, 
                  labels=c("a", "b",""), font.label=list(size=26)),
  pl3sf + theme(legend.position = "none"),
  pl5sf + theme(legend.position = "none"),
  pl4sf,
  ggpubr::ggarrange(pl6sf,pl7sf, widths = c(2,2),labels=c("f","g"),font.label=list(size=26)),
  labels = c("","c","d","e",""), ncol=1, nrow=5, font.label=list(size=26), heights = c(2,1,2,1,1)
)
plt

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
tiff(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_5.tiff"),width=22,height=26,res = 300, units = "in", compression="zip")
plt
dev.off()
pdf 
  2 
jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_5.jpeg"),width=22,height=26,res = 300, units = "in")
plt
dev.off()
pdf 
  2 
pdf(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_5.pdf"),width=22,height=26)
plt
dev.off()
pdf 
  2 

Figure 7

celltype_name_pre <- "ec"
order_celltypes <- c(2,6,3,5,8,1,4,7)
tmpfilename <- paste0("syn_v",analysis_version,"_sce_",celltype_name_pre,"_invivo",".rds")
sce_sub_ec <- readRDS(file = here::here("output",tmpfilename))
sce <- sce_sub_ec
column <- "ec_clusters_final"
column_labels <- "ec_celltype"
aggr_by="Sample"
facet_by="Sample_prep"
fill_lab = "Endothelial cells"

sce[[column]] <- factor(sce[[column]],levels = order_celltypes)
dic_ec <- unique(as.data.frame(colData(sce)[,c(column,column_labels)])) %>% 
  dplyr::arrange(!!dplyr::sym(column))
# subcelltype_colors <- viridis::viridis(length(dic_ec[[column]]))
subcelltype_colors <- rainbow(length(dic_ec[[column]]))[order(as.character(dic_ec[[column]]))]
names(subcelltype_colors) <- as.character(dic_ec[[column]])
column_names <- paste0(dic_ec[[column]], " - ",dic_ec[[column_labels]])
dic_ec$colors <- subcelltype_colors
dic_ec$column_names <- column_names

celltype_centers <- get_celltype_centers(sce, "UMAP_corrected", column)
celltype_centers %<>% move_label(0.4,"Y","5")
celltype_centers %<>% move_label(0.4,"Y","8")
celltype_centers %<>% move_label(0.4,"Y","4")
celltype_centers %<>% move_label(0.2,"Y","7")
celltype_centers %<>% move_label(-0.4,"X","7")

pl1ec <- customUMAP(sce, column, subcelltype_colors, celltype_centers,column_names)
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
propdf <- customBarplotDF(sce, column, facet_by, aggr_by)
Joining, by = c("Sample_prep", "Sample")
Joining, by = "Sample"
Joining, by = c("ec_clusters_final", "Sample_prep", "Sample")
propdf$Sample <- factor(as.character(propdf$Sample),levels=unique(as.character(propdf$Sample)))

pl2ec <- propdf %>% 
    dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n")) %>% 
  customBarplot(column, facet_by, aggr_by, fill_lab, subcelltype_colors,column_names)

pl3ec <- propdf %>% 
  customBoxplot(column, facet_by,subcelltype_colors) +
  theme(axis.text.x = element_text(angle = 0,hjust=0.5, face="bold", size=16))

plt <- ggpubr::ggarrange(pl1ec+ theme(legend.position = "none"),pl2ec,pl3ec,nrow=3, labels = "auto", heights = c(5,3,3), font.label=list(size=26))
plt

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
0f8368f Reto Gerber 2022-05-20
5a6aa2a Reto Gerber 2022-04-25
tiff(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_7.tiff"),width=14,height=20,res = 300, units = "in", compression="zip")
plt
dev.off()
pdf 
  2 
jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_7.jpeg"),width=14,height=20,res = 300, units = "in")
plt
dev.off()
pdf 
  2 
pdf(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_7.pdf"),width=14,height=20,)
plt
dev.off()
pdf 
  2 

Figure 6

celltype_name_pre <- "mp"
order_celltypes <- c(9,6,5,1,4,8,2,10,3,11,12,7)
tmpfilename <- paste0("syn_v",analysis_version,"_sce_",celltype_name_pre,"_invivo",".rds")
sce_sub_mp <- readRDS(file = here::here("output",tmpfilename))
sce <- sce_sub_mp
column <- "mp_clusters_final"
column_labels <- "mp_celltype"
aggr_by="Sample"
facet_by="Sample_prep"
fill_lab = "Macrophages / Dendritic cells"

sce[[column]] <- factor(sce[[column]],levels = order_celltypes)
sce[[column_labels]] <- stringr::str_replace(sce[[column_labels]],"&","&\n    ")
dic_mp <- unique(as.data.frame(colData(sce)[,c(column,column_labels)])) %>% 
  dplyr::arrange(!!dplyr::sym(column))
# subcelltype_colors <- viridis::viridis(length(dic_mp[[column]]))
subcelltype_colors <- rainbow(length(dic_mp[[column]]))[order(as.character(dic_mp[[column]]))]
names(subcelltype_colors) <- as.character(dic_mp[[column]])
tmp <- subcelltype_colors[names(subcelltype_colors)=="1"]
subcelltype_colors[names(subcelltype_colors)=="1"] <- subcelltype_colors[names(subcelltype_colors)=="7"]
subcelltype_colors[names(subcelltype_colors)=="7"] <- tmp
tmp <- subcelltype_colors[names(subcelltype_colors)=="3"]
subcelltype_colors[names(subcelltype_colors)=="3"] <- subcelltype_colors[names(subcelltype_colors)=="10"]
subcelltype_colors[names(subcelltype_colors)=="10"] <- tmp

column_names <- paste0(dic_mp[[column]], " - ",dic_mp[[column_labels]])
dic_mp$colors <- subcelltype_colors
dic_mp$column_names <- column_names

celltype_centers <- get_celltype_centers(sce, "UMAP_corrected", column)
celltype_centers %<>% move_label(0.5,"Y","7")
celltype_centers %<>% move_label(0.5,"Y","4")
celltype_centers %<>% move_label(0.5,"Y","12")

pl1mp <- customUMAP(sce, column, subcelltype_colors, celltype_centers,column_names)
Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
propdf <- customBarplotDF(sce, column, facet_by, aggr_by)
Joining, by = c("Sample_prep", "Sample")
Joining, by = "Sample"
Joining, by = c("mp_clusters_final", "Sample_prep", "Sample")
propdf$Sample <- factor(as.character(propdf$Sample),levels=unique(as.character(propdf$Sample)))

pl2mp <- propdf %>% 
    dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n")) %>% 
  customBarplot(column, facet_by, aggr_by, fill_lab, subcelltype_colors,column_names)

diagnosis_colors <- get_colors("diagnosis")
diagnosis_colors <- diagnosis_colors[names(diagnosis_colors) %in% unique(sce$Diagnosis_main)]

pl3mp <- propdf %>% 
  customBoxplot(column, facet_by,subcelltype_colors) +
  theme(axis.text.x = element_text(angle = 0,hjust=0.5, face="bold", size=16))

leg <- ggpubr::get_legend(pl1mp)
# str(leg)
# Convert to a ggplot and print
# ggpubr::as_ggplot(leg)
subsets <- list(`C1QA/B/C+ FOLR2+ CCR2neg macrophages       `=c(9,6,5,1,4),
                `C1QA/B/C+ FOLR2low CCR2+ CD48+ CLEC10A macrophages   `=c(8),
                `C1QA/B/Cneg FOLR2neg CCR2+ MERTKneg macrophages       `=c(2,10,3),
                `Dendritic cells                                                                                `=c(11,12,7))

legls <- purrr::map(seq_along(subsets),~{
  propdf %>% 
      dplyr::filter(mp_clusters_final %in% subsets[[.x]]) %>% 
      dplyr::mutate(!!sym(facet_by) := stringr::str_replace_all(!!sym(facet_by), " ","\n"),
                    !!sym(column):=droplevels(!!sym(column))) %>% 
    customBarplot(column, facet_by, aggr_by, names(subsets)[.x], subcelltype_colors[names(subcelltype_colors) %in% subsets[[.x]]],column_names[names(subcelltype_colors) %in% subsets[[.x]]]) %>% 
    ggpubr::get_legend() %>% 
    ggpubr::as_ggplot() 
})

legls <- c(legls,list(ggplot() + theme_void()))

plt <- ggpubr::ggarrange(pl1mp + theme(legend.position = "none"),
                  ggpubr::ggarrange(pl2mp + theme(legend.position = "none"),
                    ggpubr::ggarrange(plotlist=legls,ncol=1, align="hv", heights = c(3,1,2,2,1)),
                    ncol = 2, widths = c(3,2)),
                  pl3mp,nrow=3, labels = "auto", heights = c(5,3,3), font.label=list(size=26))
plt

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
0f8368f Reto Gerber 2022-05-20
5a6aa2a Reto Gerber 2022-04-25
tiff(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_6.tiff"),width=18,height=26,res = 300, units = "in", compression="zip")
plt
dev.off()
pdf 
  2 
jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_6.jpeg"),width=18,height=26,res = 300, units = "in")
plt
dev.off()
pdf 
  2 
pdf(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_6.pdf"),width=18,height=26)
plt
dev.off()
pdf 
  2 

Figure 8

library(ggnewscale)

sce <- sce_main
sce <- sce[,!is.na(sce$minor_celltype)]
# # rename main celltype where needed
# tmptab <- table(as.data.frame((colData(sce)[sce$main_celltype%in%c("Macrophages"),c("main_celltype","minor_celltype")])))
# wrong_main_celltype <- rownames(tmptab)[apply(tmptab,2,which.min)]
# true_main_celltype <- rownames(tmptab)[apply(tmptab,2,which.max)]
# for (i in seq_along(colnames(tmptab))) {
#   sce$main_celltype[sce$minor_celltype==colnames(tmptab)[i] & sce$main_celltype==wrong_main_celltype[i]] <- true_main_celltype[i]
# }
# annot_df <- as.data.frame(unique(colData(sce)[,c("main_celltype","minor_celltype")]))
# 
# tmptab <- table(colData(sce)[sce$minor_celltype%in%names(table(annot_df$minor_celltype))[table(annot_df$minor_celltype)>1],c("main_celltype","minor_celltype")])
# wrong_main_celltype <- rownames(tmptab)[apply(tmptab,2,function(x) seq_along(x)[order(x)==2])]
# true_main_celltype <- rownames(tmptab)[apply(tmptab,2,which.max)]
# for (i in seq_along(colnames(tmptab))) {
#   sce$main_celltype[sce$minor_celltype==colnames(tmptab)[i] & sce$main_celltype==wrong_main_celltype[i]] <- true_main_celltype[i]
# }


# rename undefined macrophages subpopulation
sce$minor_celltype[sce$main_celltype=="Macrophages" & sce$minor_celltype=="Macrophages"] <- "Other Macrophages"
table(sce$minor_celltype != "Other Macrophages")

 FALSE   TRUE 
   710 102048 
sce <- sce[,sce$minor_celltype != "Other Macrophages"]


annot_df <- as.data.frame(unique(colData(sce)[,c("main_celltype","minor_celltype")]))
uq_main_celltypes <- unique(sce$main_celltype)

main_celltypes_colors <- get_colors("main_celltypes")
annot_df <- dplyr::inner_join(
  annot_df,
  data.frame(main_celltype=names(main_celltypes_colors),
             colors=main_celltypes_colors),
  by="main_celltype")

dic_dc <- dic_mp[dic_mp$mp_celltype %in% annot_df$minor_celltype[annot_df$main_celltype == "Dendritic cells"],]
dic_mp_sub <- dic_mp[dic_mp$mp_celltype %in% annot_df$minor_celltype[annot_df$main_celltype == "Macrophages"],]

dic_ls <- list(`Endothelial cells` = dic_ec, 
               Macrophages = dic_mp_sub,
               `Dendritic cells` = dic_dc,
               Fibroblasts = dic_sf,
               `T cells/NK cells` = dic_tc )
saveRDS(dic_ls, file =here::here("output",paste0("syn_v",analysis_version,"_sce_Figure8_dic_ls.rds")))

main_celltype_names <- names(dic_ls)
for(i in seq_along(dic_ls)){
  tmpuq_minor_ct <- unique(sce$minor_celltype[sce$main_celltype==main_celltype_names[[i]]])
  annot_df <- dplyr::left_join(
    annot_df,
    dplyr::rename(dic_ls[[main_celltype_names[i]]], 
                  subcelltype_colors = colors,
                  minor_celltype = colnames(dic_ls[[main_celltype_names[i]]])[stringr::str_detect(colnames(dic_ls[[main_celltype_names[i]]]),"_celltype")]) %>% 
      dplyr::mutate(main_celltype=main_celltype_names[i]) %>% 
      dplyr::select(minor_celltype, main_celltype, subcelltype_colors),
    by=c("main_celltype","minor_celltype")) %>% 
    dplyr::mutate(colors=ifelse(is.na(subcelltype_colors),colors,subcelltype_colors)) %>% 
    dplyr::select(-subcelltype_colors)
}

# filter missing subannotations
sce <- sce[,!((sce$main_celltype==sce$minor_celltype) & (sce$minor_celltype %in% names(dic_ls)))]
annot_df <- annot_df[!((annot_df$main_celltype==annot_df$minor_celltype) & (annot_df$minor_celltype %in% names(dic_ls))),]


saveRDS(sce, file =here::here("output",paste0("syn_v",analysis_version,"_sce_Figure8.rds")))


set.seed(123)
tmpldatls <- purrr::map(uq_main_celltypes, function(ct){
  tmp <- reducedDim(sce, "UMAP_corrected")[sce$main_celltype == ct,] %>% 
  as.data.frame() %>% 
  dplyr::mutate(!!ct := sce$minor_celltype[sce$main_celltype == ct],
                `UMAP 1` = V1,
                `UMAP 2` = V2)
  tmp[sample(nrow(tmp)),]
})
names(tmpldatls) <- uq_main_celltypes


pl <- ggplot()+
    main_plot_theme() +
    labs(color="", x="UMAP 1", y="UMAP 2") 

celltypes_plotting <- c("Pericytes/Mural cells", "Neutrophils", "Plasmablasts","B cells","Mast cells","Plasmacytoid DCs","Macrophages","Dendritic cells" , "T cells/NK cells", "Fibroblasts","Endothelial cells")

for(ct in celltypes_plotting){
  tmpcols <- annot_df$colors[annot_df$main_celltype == ct]
  pl <- pl +
    new_scale_color() + 
    geom_point(data=tmpldatls[[ct]], aes(x=`UMAP 1`,y=`UMAP 2`, color=!!sym(ct)),size=0.1) +
    scale_color_manual(values=tmpcols,
                       breaks=annot_df$minor_celltype[annot_df$main_celltype == ct],
                       labels=annot_df$minor_celltype[annot_df$main_celltype == ct],
                       guide=guide_legend(
                         ncol=2,
                         order=i,
                         override.aes = list(
                           shape = c(rep(15,length(tmpcols))),
                         size= rep(10,length(tmpcols)),
                         alpha=rep(1,length(tmpcols))
                           )
                         ))
}


celltype_centers <- get_celltype_centers(sce, "UMAP_corrected", "main_celltype")
celltype_centers %<>% move_label(0.5,"Y")
celltype_centers %<>% move_label(1,"X","Plasmacytoid DCs")
celltype_centers %<>% move_label(0.5,"X","Dendritic cells")
celltype_centers %<>% move_label(0.8,"Y","Dendritic cells")
celltype_centers %<>% move_label(0.2,"Y","Pericytes/Mural cells")
celltype_centers %<>% move_label(-1,"X","Pericytes/Mural cells")
celltype_centers %<>% move_label(0.5,"Y","Endothelial cells")

pl <- pl + geom_label(aes(V1,V2,label=V3),data=celltype_centers, size=6) 
pl

Version Author Date
58eeb06 Reto Gerber 2023-05-30
e786402 Reto Gerber 2022-05-28
5a6aa2a Reto Gerber 2022-04-25
tiff(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_8.tiff"),width=27,height=18,res = 300, units = "in", compression="zip")
pl
dev.off()
pdf 
  2 
jpeg(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_8.jpeg"),width=27,height=18,res = 300, units = "in")
pl
dev.off()
pdf 
  2 
pdf(here::here("..","synovialscrnaseq","output","Figures_Paper","Figure_8.pdf"),width=27,height=18)
pl
dev.off()
pdf 
  2 

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] ggnewscale_0.4.5               gdtools_0.2.3                 
 [3] ComplexHeatmap_2.6.2           magrittr_2.0.1                
 [5] tidySingleCellExperiment_1.0.0 scuttle_1.0.4                 
 [7] igraph_1.2.6                   scran_1.18.7                  
 [9] scater_1.18.6                  SingleCellExperiment_1.12.0   
[11] SummarizedExperiment_1.20.0    Biobase_2.50.0                
[13] GenomicRanges_1.42.0           GenomeInfoDb_1.26.7           
[15] IRanges_2.24.1                 S4Vectors_0.28.1              
[17] BiocGenerics_0.36.1            MatrixGenerics_1.2.1          
[19] matrixStats_0.58.0             stringr_1.4.0                 
[21] purrr_0.3.4                    ggplot2_3.3.3                 
[23] dplyr_1.0.4                    workflowr_1.6.2               

loaded via a namespace (and not attached):
  [1] readxl_1.3.1              backports_1.2.1          
  [3] circlize_0.4.12           systemfonts_1.0.1        
  [5] lazyeval_0.2.2            BiocParallel_1.24.1      
  [7] digest_0.6.27             htmltools_0.5.1.1        
  [9] viridis_0.5.1             fansi_0.4.2              
 [11] cluster_2.1.1             openxlsx_4.2.3           
 [13] limma_3.46.0              svglite_1.2.3.2          
 [15] colorspace_2.0-0          haven_2.3.1              
 [17] xfun_0.21                 crayon_1.4.1             
 [19] RCurl_1.98-1.2            jsonlite_1.7.2           
 [21] glue_1.4.2                gtable_0.3.0             
 [23] zlibbioc_1.36.0           XVector_0.30.0           
 [25] GetoptLong_1.0.5          DelayedArray_0.16.3      
 [27] car_3.0-10                BiocSingular_1.6.0       
 [29] shape_1.4.5               abind_1.4-5              
 [31] scales_1.1.1              DBI_1.1.1                
 [33] edgeR_3.32.1              rstatix_0.7.0            
 [35] Rcpp_1.0.6                isoband_0.2.3            
 [37] viridisLite_0.3.0         clue_0.3-58              
 [39] dqrng_0.2.1               foreign_0.8-81           
 [41] rsvd_1.0.3                htmlwidgets_1.5.3        
 [43] httr_1.4.2                RColorBrewer_1.1-2       
 [45] ellipsis_0.3.1            pkgconfig_2.0.3          
 [47] farver_2.0.3              locfit_1.5-9.4           
 [49] here_1.0.1                tidyselect_1.1.0         
 [51] labeling_0.4.2            rlang_0.4.10             
 [53] later_1.1.0.1             munsell_0.5.0            
 [55] cellranger_1.1.0          tools_4.0.3              
 [57] cli_2.3.0                 generics_0.1.0           
 [59] broom_0.7.4               evaluate_0.14            
 [61] yaml_2.2.1                RhpcBLASctl_0.20-137     
 [63] knitr_1.31                fs_1.5.0                 
 [65] zip_2.1.1                 sparseMatrixStats_1.2.1  
 [67] whisker_0.4               compiler_4.0.3           
 [69] beeswarm_0.2.3            plotly_4.9.3             
 [71] curl_4.3                  png_0.1-7                
 [73] ggsignif_0.6.0            tibble_3.0.6             
 [75] statmod_1.4.35            stringi_1.5.3            
 [77] highr_0.8                 forcats_0.5.1            
 [79] lattice_0.20-41           bluster_1.0.0            
 [81] Matrix_1.3-2              vctrs_0.3.6              
 [83] pillar_1.4.7              lifecycle_1.0.0          
 [85] GlobalOptions_0.1.2       BiocNeighbors_1.8.2      
 [87] data.table_1.13.6         cowplot_1.1.1            
 [89] bitops_1.0-6              irlba_2.3.3              
 [91] httpuv_1.5.5              R6_2.5.0                 
 [93] promises_1.2.0.1          gridExtra_2.3            
 [95] rio_0.5.16                vipor_0.4.5              
 [97] MASS_7.3-53.1             assertthat_0.2.1         
 [99] rprojroot_2.0.2           rjson_0.2.20             
[101] withr_2.4.1               GenomeInfoDbData_1.2.4   
[103] hms_1.0.0                 beachmat_2.6.4           
[105] tidyr_1.1.2               rmarkdown_2.6            
[107] DelayedMatrixStats_1.12.3 carData_3.0-4            
[109] Cairo_1.5-12.2            git2r_0.28.0             
[111] ggpubr_0.4.0              ggbeeswarm_0.6.0