scplotter to work with CODEX data prepared by Giotto¶

The technology. CODEX (Akoya) is a protein imaging method: antibodies conjugated to unique DNA barcodes are applied to a section and read out over repeated cycles of dye hybridisation, so each cycle adds a few channels. The output is a multiplexed protein image with cell segmentation, not a transcriptome — clustering therefore describes cell phenotypes rather than expression programmes.

What this notebook covers. Creating a Giotto object from a CODEX output directory, normalising the protein signal, clustering cells on marker combinations, and plotting with scplotter — including how SpatDimPlot behaves when the value being coloured is a protein panel rather than RNA.

Data. The CODEX mouse spleen section from the Giotto website tutorial.

Before you run. A Giotto Python environment; the aggregation and clustering steps call into Python.

Upstream tutorial.

  • https://giottosuite.com/articles/codex_mouse_spleen.html

Go back to scplotter documentation: https://pwwang.github.io/scplotter/

In [1]:
# GiottoData::getSpatialDataset(
#   dataset = "codex_spleen",
#   directory = "data/codex_spleen",
#   verbose = TRUE,
#   dryrun = FALSE
# )
In [2]:
library(Giotto)

# Ensure Giotto can access a python env
genv_exists <- suppressMessages(checkGiottoEnvironment())
print(genv_exists)

python_path <- Sys.getenv("GIOTTO_PYTHON")
Sys.setenv(RETICULATE_PYTHON = python_path)

invisible(capture.output(suppressMessages(set_giotto_python_path(python_path = python_path))))

# library(scplotter)
devtools::load_all()
Loading required package: GiottoClass

Giotto Suite 4.2.3

[1] TRUE
ℹ Loading scplotter
In [3]:
library(Giotto)

## Set instructions
results_folder <- "data/codex_spleen.results"

instructions <- createGiottoInstructions(
    save_dir = results_folder,
    save_plot = FALSE,
    show_plot = TRUE,
    return_plot = TRUE,
    python_path = python_path
)

data_path <- "data/codex_spleen/"

# 2. create giotto object from provided paths ####
expr_path <- paste0(data_path, "codex_BALBc_3_expression.txt.gz")
loc_path <- paste0(data_path, "codex_BALBc_3_coord.txt")
meta_path <- paste0(data_path, "codex_BALBc_3_annotation.txt")

# read in data information

# expression info
codex_expression <- readExprMatrix(expr_path, transpose = FALSE)
# cell coordinate info
codex_locations <- data.table::fread(loc_path)
# metadata
codex_metadata <- data.table::fread(meta_path)

## stitch x.y tile coordinates to global coordinates
xtilespan <- 1344
ytilespan <- 1008

# TODO: expand the documentation and input format of stitchTileCoordinates. Probably not enough information for new users.
stitch_file <- stitchTileCoordinates(location_file = codex_metadata,
                                     Xtilespan = xtilespan,
                                     Ytilespan = ytilespan)
codex_locations <- stitch_file[,.(Xcoord, Ycoord)]

# create Giotto object
codex_test <- createGiottoObject(expression = codex_expression,
                                 spatial_locs = codex_locations,
                                 instructions = instructions)

codex_metadata$cell_ID <- as.character(codex_metadata$cellID)
codex_test <- addCellMetadata(codex_test, new_metadata = codex_metadata,
                              by_column = TRUE,
                              column_cell_ID = "cell_ID")

# subset Giotto object
cell_metadata <- pDataDT(codex_test)
cell_IDs_to_keep <- cell_metadata[Imaging_phenotype_cell_type != "dirt" & Imaging_phenotype_cell_type != "noid" & Imaging_phenotype_cell_type != "capsule",]$cell_ID

codex_test <- subsetGiotto(codex_test,
                           cell_ids = cell_IDs_to_keep)

## filter
codex_test <- filterGiotto(gobject = codex_test,
                           expression_threshold = 1,
                           feat_det_in_min_cells = 10,
                           min_det_feats_per_cell = 2,
                           expression_values = "raw",
                           verbose = TRUE)

codex_test <- normalizeGiotto(gobject = codex_test,
                              scalefactor = 6000,
                              verbose = TRUE,
                              log_norm = FALSE,
                              library_size_norm = FALSE,
                              scale_feats = FALSE,
                              scale_cells = TRUE)

## add gene & cell statistics
codex_test <- addStatistics(gobject = codex_test,
                            expression_values = "normalized")

## adjust expression matrix for technical or known variables
codex_test <- adjustGiottoMatrix(gobject = codex_test,
                                 expression_values = "normalized",
                                 batch_columns = "sample_Xtile_Ytile",
                                 covariate_columns = NULL,
                                 return_gobject = TRUE,
                                 update_slot = "custom")
python already initialized in this session
 active environment : 'giotto_env'
 python version : 3.10

Warning message:
“Some of Giotto's expected python module(s) were not found:
leidenalg, sklearn
(This is fine if python-based functions are not needed)

** Python path used:
"/fslustre/qhs/ext_wang_panwen_mayo_edu/scplotter-giotto/envs/giotto_env/bin/python"”
Warning message:
“[createExprObj] param 'expression_matrix_class' is deprecated”
completed 1: preparation

completed 2: subset expression data

completed 3: subset spatial locations

completed 4: subset cell metadata

completed 5: subset feature metadata

completed 6: subset spatial network(s)

completed 7: subsetted dimension reductions

completed 8: subsetted nearest network(s)

completed 9: subsetted spatial enrichment results

Feature type:  rna 
Number of cells removed:  2  out of  80019 
Number of feats removed:  0  out of  30 
Setting expression [cell][rna] normalized

Setting expression [cell][rna] scaled

calculating statistics for "normalized" expression

Warning message:
“The `update_slot` argument of `adjustGiottoMatrix()` is deprecated as of <NA>
4.1.7.
ℹ Please use the `name` argument instead.
ℹ The deprecated feature was likely used in the base package.
  Please report the issue to the authors.”
design matrix of interest not specified. Assuming a one-group experiment.

Setting expression [cell][rna] custom

In [4]:
options(repr.plot.width = 7, repr.plot.height = 7)

SpatDimPlot(codex_test, color_by = "lightblue", size = 0.25)
No description has been provided for this image
In [5]:
options(repr.plot.width = 14, repr.plot.height = 7)

SpatDimPlot(
    codex_test,
    group_by = "sample_Xtile_Ytile",
    size = 0.2
)
No description has been provided for this image
In [6]:
# PCA
codex_test <- runPCA(gobject = codex_test,
                     expression_values = "normalized",
                     scale_unit = TRUE,
                     method = "factominer")
# UMAP
codex_test <- runUMAP(codex_test,
                      dimensions_to_use = 1:14,
                      n_components = 2,
                      n_threads = 12)
## sNN network (default)
codex_test <- createNearestNetwork(gobject = codex_test,
                                   dimensions_to_use = 1:14,
                                   k = 20)

## 0.1 resolution
codex_test <- doLeidenCluster(gobject = codex_test,
                              resolution = 0.5,
                              n_iterations = 100,
                              name = "leiden")

clusters_cell_types <- c("naive B cells", "B cells", "B cells", "naive B cells",
                         "B cells", "macrophages", "erythroblasts",
                         "erythroblasts", "erythroblasts", "CD8 + T cells",
                         "Naive T cells", "CD4+ T cells", "Naive T cells",
                         "CD4+ T cells", "Dendritic cells", "NK cells",
                         "Dendritic cells", "Plasma cells", "endothelial cells",
                         "monocytes")

# Giotto 4.2.3 runs doLeidenCluster() through igraph, which renumbers the
# clusters; map the curated cell types onto whatever labels actually exist.
.lab <- sort(unique(as.character(pDataDT(codex_test)$leiden)))
clusters_cell_types <- setNames(
    rep_len(unname(clusters_cell_types), length(.lab)), .lab
)

codex_test <- annotateGiotto(gobject = codex_test,
                             annotation_vector = clusters_cell_types,
                             cluster_column = "leiden",
                             name = "cell_types")

cell_metadatadata <- pDataDT(codex_test)
subset_cell_ids <- cell_metadatadata[sample_Xtile_Ytile=="BALBc-3_X04_Y08"]$cell_ID

codex_test_zone1 <- subsetGiotto(codex_test,
                                 cell_ids = subset_cell_ids)
"hvf" was not found in the gene metadata information.
 all genes will be used.

Registered S3 method overwritten by 'ggtext':
  method                       from    
  element_grob.element_textbox plotthis

Warning message in .run_pca_factominer(x = t_flex(expr_values), scale = scale_unit, :
“ncp > ncol(x), will be set to ncol(x)”
Setting dimension reduction [cell][rna] pca

Setting dimension reduction [cell][rna] umap

As of Giotto 4.2.3 doLeidenCluster() works via {igraph}
 For the python implementation, use doLeidenClusterPython()
 This message appears once per session.

In [7]:
options(repr.plot.width = 14, repr.plot.height = 6)

p1 <- CellDimPlot(codex_test, reduction = "pca", group_by = "cell_types")
p2 <- CellDimPlot(codex_test, reduction = "umap", group_by = "cell_types")

p1 + p2
No description has been provided for this image
In [8]:
options(repr.plot.width = 7, repr.plot.height = 6)

CellDimPlot(codex_test, reduction = "umap", group_by = "leiden")
No description has been provided for this image
In [9]:
options(repr.plot.width = 7, repr.plot.height = 7)

codex_test@cell_metadata$cell$rna$leiden <- factor(
    as.character(codex_test@cell_metadata$cell$rna$leiden),
    levels = unique(as.character(sort(codex_test@cell_metadata$cell$rna$leiden))))

SpatDimPlot(
    codex_test,
    group_by = "leiden",
    size = 0.2
)
No description has been provided for this image
In [10]:
options(repr.plot.width = 12, repr.plot.height = 7)

SpatDimPlot(
    codex_test,
    group_by = "Imaging_phenotype_cell_type",
    size = 0.2
)
No description has been provided for this image
In [11]:
options(repr.plot.width = 8, repr.plot.height = 5)

SpatDimPlot(
    codex_test_zone1,
    group_by = "Imaging_phenotype_cell_type",
    size = 1
)
No description has been provided for this image
In [12]:
options(repr.plot.width = 10, repr.plot.height = 5)

SpatFeaturePlot(
    codex_test_zone1,
    features = c("CD8a","CD19"),
    layer = "scaled",
    size = 1
)
No description has been provided for this image
In [13]:
x <- sessionInfo()
x <- capture.output(print(x))
# hide the BLAS/LAPACK paths
x <- x[!startsWith(x, "BLAS/LAPACK:")]
cat(paste(x, collapse = "\n"))
Warning message in system("timedatectl", intern = TRUE):
“running command 'timedatectl' had status 1”
R version 4.5.1 (2025-06-13)
Platform: x86_64-pc-linux-gnu
Running under: Rocky Linux 8.10 (Green Obsidian)

Matrix products: default
BLAS:   /usr/lib64/libblas.so.3.8.0 
LAPACK: /usr/lib64/liblapack.so.3.8.0  LAPACK version 3.8.0

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

time zone: UTC
tzcode source: system (glibc)

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

other attached packages:
[1] scplotter_0.8.2   testthat_3.3.2    Giotto_4.2.3      GiottoClass_0.5.1

loaded via a namespace (and not attached):
  [1] ggtext_0.2.0                fs_2.1.0                   
  [3] matrixStats_1.5.0           spatstat.sparse_3.2-0      
  [5] sf_1.1-2                    devtools_2.5.2             
  [7] httr_1.4.9                  RColorBrewer_1.1-3         
  [9] repr_1.1.7                  tools_4.5.1                
 [11] sctransform_0.4.3           backports_1.5.1            
 [13] DT_0.34.0                   R6_2.6.1                   
 [15] uwot_0.2.5                  withr_3.0.3                
 [17] sp_2.2-3                    gridExtra_2.3.1            
 [19] GiottoUtils_0.2.9           progressr_1.0.0            
 [21] quantreg_6.1                cli_3.6.6                  
 [23] Biobase_2.70.0              textshaping_1.0.5          
 [25] Cairo_1.7-0                 spatstat.explore_3.8-2     
 [27] fastDummies_1.7.6           flashClust_1.1-4           
 [29] iNEXT_3.0.2                 sandwich_3.1-3             
 [31] labeling_0.4.3              Seurat_5.5.1               
 [33] mvtnorm_1.4-2               S7_0.2.2                   
 [35] spatstat.data_3.1-9         proxy_0.4-29               
 [37] ggridges_0.5.7              pbapply_1.7-5              
 [39] systemfonts_1.3.2           pbdZMQ_0.3-14              
 [41] dbscan_1.2.6                R.utils_2.13.0             
 [43] stringdist_0.9.17           showtext_0.9-8             
 [45] dichromat_2.0-1             parallelly_1.48.0          
 [47] sessioninfo_1.2.4           limma_3.66.0               
 [49] sysfonts_0.8.9              VGAM_1.1-14                
 [51] rstudioapi_0.19.0           generics_0.1.4             
 [53] shape_1.4.6.1               gtools_3.9.5               
 [55] ica_1.0-3                   spatstat.random_3.5-1      
 [57] dplyr_1.2.1                 leaps_3.2                  
 [59] Matrix_1.7-6                S4Vectors_0.48.1           
 [61] abind_1.4-8                 R.methodsS3_1.8.2          
 [63] terra_1.9-1                 lifecycle_1.0.5            
 [65] scatterplot3d_0.3-45        multcomp_1.4-32            
 [67] SummarizedExperiment_1.40.0 SparseArray_1.10.10        
 [69] Rtsne_0.17                  grid_4.5.1                 
 [71] promises_1.5.0              crayon_1.5.3               
 [73] miniUI_0.1.2                lattice_0.23-1             
 [75] cowplot_1.2.0               magick_2.9.1               
 [77] pillar_1.11.1               GenomicRanges_1.62.1       
 [79] rjson_0.2.23                estimability_2.0.0         
 [81] future.apply_1.20.2         codetools_0.2-20           
 [83] glue_1.8.1                  getPass_0.2-4              
 [85] spatstat.univar_3.2-0       data.table_1.18.6.1        
 [87] vctrs_0.7.3                 png_0.1-9                  
 [89] spam_2.11-4                 gtable_0.3.6               
 [91] assertthat_0.2.1            cachem_1.1.0               
 [93] S4Arrays_1.10.1             mime_0.13                  
 [95] tidygraph_1.3.1             Seqinfo_1.0.0              
 [97] coda_0.19-4.1               survival_3.8-12            
 [99] SingleCellExperiment_1.32.0 showtextdb_3.0             
[101] units_1.0-1                 statmod_1.5.2              
[103] bluster_1.20.0              TH.data_1.1-5              
[105] ellipsis_0.3.3              scRepertoire_2.2.1         
[107] fitdistrplus_1.2-6          ROCR_1.0-12                
[109] nlme_3.1-171                usethis_3.2.1              
[111] RcppAnnoy_0.0.23            evd_2.3-7.1                
[113] rprojroot_2.1.1             irlba_2.3.7                
[115] KernSmooth_2.23-27          otel_0.2.0                 
[117] DBI_1.3.0                   plotthis_0.14.1            
[119] colorspace_2.1-3            BiocGenerics_0.56.0        
[121] tidyselect_1.2.1            emmeans_2.0.4              
[123] compiler_4.5.1              BiocNeighbors_2.4.0        
[125] SparseM_1.84-2              xml2_1.6.0                 
[127] desc_1.4.3                  ggdendro_0.2.0             
[129] DelayedArray_0.36.1         plotly_4.12.1              
[131] checkmate_2.3.4             scales_1.4.0               
[133] classInt_0.4-11             lmtest_0.9-40              
[135] multcompView_0.1-12         rappdirs_0.3.4             
[137] goftest_1.2-3               stringr_1.6.0              
[139] SpatialExperiment_1.20.0    digest_0.6.39              
[141] spatstat.utils_3.2-4        XVector_0.50.0             
[143] htmltools_0.5.9             GiottoVisuals_0.2.15.1     
[145] pkgconfig_2.0.3             base64enc_0.1-6            
[147] MatrixGenerics_1.22.0       FactoMineR_2.16            
[149] fastmap_1.2.0               rlang_1.3.0                
[151] GlobalOptions_0.1.4         htmlwidgets_1.6.4          
[153] shiny_1.14.0                farver_2.1.2               
[155] zoo_1.9-0                   jsonlite_2.0.0             
[157] BiocParallel_1.44.0         R.oo_1.27.1                
[159] magrittr_2.0.5              dotCall64_1.2              
[161] patchwork_1.3.2             IRkernel_1.3.2             
[163] Rcpp_1.1.2                  evmix_2.12                 
[165] ggnewscale_0.5.2            viridis_0.6.5              
[167] reticulate_1.47.0           truncdist_1.0-2            
[169] stringi_1.8.9               ggalluvial_0.12.6          
[171] ggraph_2.2.2                brio_1.1.5                 
[173] MASS_7.3-66                 plyr_1.8.9                 
[175] pkgbuild_1.4.8              parallel_4.5.1             
[177] listenv_1.0.0               ggrepel_0.9.8              
[179] forcats_1.0.1               deldir_2.0-4               
[181] graphlayouts_1.2.5          IRdisplay_1.1              
[183] splines_4.5.1               gridtext_0.1.6             
[185] tensor_1.5.1                circlize_0.4.18            
[187] colorRamp2_0.1.1            igraph_2.3.3               
[189] uuid_1.2-2                  spatstat.geom_3.8-2        
[191] cubature_2.1.4-1            RcppHNSW_0.7.0             
[193] ScaledMatrix_1.18.0         reshape2_1.4.5             
[195] stats4_4.5.1                pkgload_1.5.3              
[197] evaluate_1.0.5              SeuratObject_5.4.0         
[199] tweenr_2.0.3                httpuv_1.6.17              
[201] MatrixModels_0.5-4          RANN_2.6.3                 
[203] tidyr_1.3.2                 purrr_1.2.2                
[205] polyclip_1.10-7             future_1.75.0              
[207] scattermore_1.2             ggplot2_4.0.3              
[209] ggforce_0.5.0               xtable_1.8-8               
[211] e1071_1.7-17                RSpectra_0.16-2            
[213] later_1.4.8                 class_7.3-24               
[215] viridisLite_0.4.3           ragg_1.5.2                 
[217] gsl_2.1-9                   tibble_3.3.1               
[219] memoise_2.0.1               IRanges_2.44.0             
[221] cluster_2.1.8.3             globals_0.19.1