Spatial Transcriptomics Deconvolution with SPOTlight

# Spatial Transcriptomics Deconvolution with `SPOTlight`

For a more detailed explanation of `SPOTlight` consider looking at our manuscript: > Elosua-Bayes M, Nieto P, Mereu E, Gut I, Heyn H.
SPOTlight: seeded NMF regression to deconvolute
spatial transcriptomics spots with single-cell transcriptomes.
Nucleic Acids Res. 2021;49(9):e50. doi: 10.1093

# Load packages

    library(ggplot2)
    library(SPOTlight)
    library(SingleCellExperiment)
    library(SpatialExperiment)
    library(scater)
    library(scran)

# Introduction

## What is `SPOTlight`?

`SPOTlight` is a tool that enables the deconvolution of cell types and cell type proportions present within each capture location comprising mixtures of cells. Originally developed for 10X’s Visium - spatial transcriptomics - technology, it can be used for all technologies returning mixtures of cells.

`SPOTlight` is based on learning topic profile signatures, by means of an NMFreg model, for each cell type and finding which combination of cell types fits best the spot we want to deconvolute. Find below a graphical abstract visually summarizing the key steps.

## Starting point

The minimal unit of data required to run `SPOTlight` are:

- ST (sparse) matrix with the expression, raw or normalized, where rows = genes and columns = capture locations.
- Single cell (sparse) matrix with the expression, raw or normalized,
  where rows = genes and columns = cells.
- Vector indicating the cell identity for each column in the single cell expression matrix.

Data inputs can also be objects of class SpatialExperiment (SE), SingleCellExperiment (SCE) objects from which the minimal data will be extracted.

# Getting started

## Data description

For this vignette, we will use a SE put out by 10X Genomics containing a Visium kidney slide. The raw data can be accessed here.

SCE data comes from the The Tabula Muris Consortium which contains >350,000 cells from from male and female mice belonging to six age groups, ranging from 1 to 30 months. From this dataset we will only load the kidney subset to map it to the Visium slide.

## Loading the data

Both datasets are available through Biocondcutor packages and can be loaded into R as follows. ` Load the spatial data:

    library(TENxVisiumData)
    spe <- MouseKidneyCoronal()

    # Use symbols instead of Ensembl IDs as feature names
    rownames(spe) <- rowData(spe)$symbol

Load the single cell data. Since our data comes from the Tabula Muris Sensis dataset, we can directly load the SCE object as follows:

    library(TabulaMurisSenisData)
    sce <- TabulaMurisSenisDroplet(tissues = "Kidney")$Kidney

Quick data exploration:

    table(sce$free_annotation, sce$age)

    ##
    ##                                                                1m   3m  18m
    ##   CD45                                                         11   32   76
    ##   CD45    B cell                                                7    5   45
    ##   CD45    NK cell                                               1    4    8
    ##   CD45    T cell                                                8   18   48
    ##   CD45    macrophage                                           59  132  254
    ##   CD45    plasma cell                                           0    0    9
    ##   Epcam     kidney distal convoluted tubule epithelial cell    78  126  169
    ##   Epcam    brush cell                                          52   15   78
    ##   Epcam    kidney collecting duct principal cell               77  110  132
    ##   Epcam    kidney proximal convoluted tubule epithelial cell  945  684 1120
    ##   Epcam    podocyte                                            92   94   64
    ##   Epcam    proximal tube epithelial cell                       25  195  296
    ##   Epcam    thick ascending tube S epithelial cell             465  312  248
    ##   Pecam    Kidney cortex artery cell                           75   78   91
    ##   Pecam    fenestrated capillary endothelial                  164  182  164
    ##   Pecam    kidney capillary endothelial cell                   49   38   25
    ##   Stroma    fibroblast                                         15   16   37
    ##   Stroma    kidney mesangial cell                              80   51   18
    ##   nan                                                         285  238  256
    ##
    ##                                                               21m  24m  30m
    ##   CD45                                                         54 1010  106
    ##   CD45    B cell                                               54 2322   62
    ##   CD45    NK cell                                               2   47    4
    ##   CD45    T cell                                               42  846  177
    ##   CD45    macrophage                                          101  259  514
    ##   CD45    plasma cell                                          12  169   42
    ##   Epcam     kidney distal convoluted tubule epithelial cell   153    0  131
    ##   Epcam    brush cell                                         169    0   31
    ##   Epcam    kidney collecting duct principal cell               58    0  370
    ##   Epcam    kidney proximal convoluted tubule epithelial cell  868    0  817
    ##   Epcam    podocyte                                            66    0  170
    ##   Epcam    proximal tube epithelial cell                        5    0 1977
    ##   Epcam    thick ascending tube S epithelial cell             228    0  313
    ##   Pecam    Kidney cortex artery cell                           69    0  115
    ##   Pecam    fenestrated capillary endothelial                  134    0  211
    ##   Pecam    kidney capillary endothelial cell                   18    0    7
    ##   Stroma    fibroblast                                         13    0   80
    ##   Stroma    kidney mesangial cell                              22    0    7
    ##   nan                                                         189 1068  579

We see how there is a good representation of all the cell types across ages except at 24m. In order to reduce the potential noise introduced by age and batch effects we are going to select cells all coming from the same age.

    # Keep cells from 18m mice
    sce <- sce[, sce$age == "18m"]
    # Keep cells with clear cell type annotations
    sce <- sce[, !sce$free_annotation %in% c("nan", "CD45")]

# Workflow

## Preprocessing

If the dataset is very large we want to downsample it to train the model, both in of number of cells and number of genes. To do this, we want to keep a representative amount of cells per cluster and the most biologically relevant genes.

In the paper we show how downsampling the number of cells per cell identity to ~100 doesn’t affect the performance of the model. Including >100 cells per cell identity provides marginal improvement while greatly increasing computational time and resources. Furthermore, restricting the gene set to the marker genes for each cell type along with up to 3.000 highly variable genes further optimizes performance and computational resources. You can find a more detailed explanation in the original paper.

### Feature selection

Our first step is to get the marker genes for each cell type. We follow the Normalization procedure as described in OSCA. We first carry out library size normalization to correct for cell-specific biases:

    sce <- logNormCounts(sce)

    ## Warning in .library_size_factors(assay(x, assay.type), ...): 'librarySizeFactors' is deprecated.
    ## Use 'scrapper::centerSizeFactors' instead.
    ## See help("Deprecated")

    ## Warning in .local(x, ...): 'normalizeCounts' is deprecated.
    ## Use 'scrapper::normalizeCounts' instead.
    ## See help("Deprecated")

### Variance modelling

We aim to identify highly variable genes that drive biological heterogeneity. By feeding these genes to the model we improve the resolution of the biological structure and reduce the technical noise.

    # Get vector indicating which genes are neither ribosomal or mitochondrial
    genes <- !grepl(pattern = "^Rp[l|s]|Mt", x = rownames(sce))

    dec <- modelGeneVar(sce, subset.row = genes)

    ## Warning in .model_gene_var(x = assay(x, i = assay.type), ...): 'modelGeneVar' is deprecated.
    ## Use 'scrapper::modelGeneVariances' instead.
    ## See help("Deprecated")

    ## Warning in fitTrendVar(fm, fv, ...): 'fitTrendVar' is deprecated.
    ## Use 'scrapper::fitVarianceTrend' instead.
    ## See help("Deprecated")

    ## Warning in combineBlocks(collected, method = method, equiweight = equiweight, : 'combineBlocks' is deprecated.
    ## See help("Deprecated")

    plot(dec$mean, dec$total, xlab = "Mean log-expression", ylab = "Variance")
    curve(metadata(dec)$trend(x), col = "blue", add = TRUE)

    # Get the top 3000 genes.
    hvg <- getTopHVGs(dec, n = 3000)

    ## Warning in getTopHVGs(dec, n = 3000): 'getTopHVGs' is deprecated.
    ## Use 'scrapper::chooseHighlyVariableGenes' instead.
    ## See help("Deprecated")

Next we obtain the marker genes for each cell identity. You can use whichever method you want as long as it returns a weight indicating the importance of that gene for that cell type. Examples include `avgLogFC`, `AUC`, `pct.expressed`, `p-value`…

    colLabels(sce) <- colData(sce)$free_annotation

    # Compute marker genes
    mgs <- scoreMarkers(sce, subset.row = genes)

    ## Warning in .local(x, ...): 'summarizeAssayByGroup' is deprecated.
    ## Use 'scrapper::aggregateAcrossCells' or 'beachmat::tatami.sums.by.group' instead.
    ## Warning in .local(x, ...): 'summarizeAssayByGroup' is deprecated.
    ## Use 'scrapper::aggregateAcrossCells' or 'beachmat::tatami.sums.by.group' instead.
    ## Warning in .local(x, ...): 'summarizeAssayByGroup' is deprecated.
    ## Use 'scrapper::aggregateAcrossCells' or 'beachmat::tatami.sums.by.group' instead.
    ## Warning in .local(x, ...): 'summarizeAssayByGroup' is deprecated.
    ## Use 'scrapper::aggregateAcrossCells' or 'beachmat::tatami.sums.by.group' instead.
    ## Warning in .local(x, ...): 'summarizeAssayByGroup' is deprecated.
    ## Use 'scrapper::aggregateAcrossCells' or 'beachmat::tatami.sums.by.group' instead.

    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")
    ## Warning in computeMinRank(res[[i]][[j]]): 'computeMinRank' is deprecated.
    ## Use 'scrapper::summarizeEffects' instead.
    ## See help("Deprecated")

Then we want to keep only those genes that are relevant for each cell identity:

    mgs_fil <- lapply(names(mgs), function(i) {
        x <- mgs[[i]]
        # Filter and keep relevant marker genes, those with AUC > 0.8
        x <- x[x$mean.AUC > 0.8, ]
        # Sort the genes from highest to lowest weight
        x <- x[order(x$mean.AUC, decreasing = TRUE), ]
        # Add gene and cluster id to the dataframe
        x$gene <- rownames(x)
        x$cluster <- i
        data.frame(x)
    })
    mgs_df <- do.call(rbind, mgs_fil)

### Cell Downsampling

Next, we randomly select at most 100 cells per cell identity. If a cell type is comprised of <100 cells, all the cells will be used. If we have very biologically different cell identities (B cells vs. T cells vs. Macrophages vs. Epithelial) we can use fewer cells since their transcriptional profiles will be very different. In cases when we have more transcriptionally similar cell identities we need to increase our N to capture the biological heterogeneity between them.

In our experience we have found that for this step it is better to select the cells from each cell type from the same batch if you have a joint dataset from multiple runs. This will ensure that the model removes as much signal from the batch as possible and actually learns the biological signal.

For the purpose of this vignette and to speed up the analysis, we are going to use 20 cells per cell identity:

    # split cell indices by identity
    idx <- split(seq(ncol(sce)), sce$free_annotation)
    # downsample to at most 20 per identity & subset
    # We are using 5 here to speed up the process but set to 75-100 for your real
    # life analysis
    n_cells <- 50
    cs_keep <- lapply(idx, function(i) {
        n <- length(i)
        if (n < n_cells)
            n_cells <- n
        sample(i, n_cells)
    })
    sce <- sce[, unlist(cs_keep)]

## Deconvolution

You are now set to run `SPOTlight` to deconvolute the spots!

Briefly, here is how it works:

1. NMF is used to factorize a matrix into two lower dimensionality matrices without negative elements. We first have an initial matrix V (SCE count matrix), which is factored into W and H. Unit variance normalization by gene is performed in V and in order to standardize discretized gene expression levels, ‘counts-umi’. Factorization is then carried out using the non-smooth NMF method, implemented in the R package NMF NMF (14). This method is intended to return sparser results during the factorization in W and H, thus promoting cell-type-specific topic profile and reducing overfitting during training. Before running factorization, we initialize each topic, column, of W with the unique marker genes for each cell type with weights. In turn, each topic of H in `SPOTlight` is initialized with the corresponding membership of each cell for each topic, 1 or 0. This way, we seed the model with prior information, thus guiding it towards a biologically relevant result. This initialization also aims at reducing variability and improving the consistency between runs.

2. NNLS regression is used to map each capture location’s transcriptome in V’ (SE count matrix) to H’ using W as the basis. We obtain a topic profile distribution over each capture location which we can use to determine its composition.

3. we obtain Q, cell-type specific topic profiles, from H. We select all cells from the same cell type and compute the median of each topic for a consensus cell-type-specific topic signature. We then use NNLS to find the weights of each cell type that best fit H’ minimizing the residuals.

You can visualize the above explanation in the following workflow scheme:

    res <- SPOTlight(
        x = sce,
        y = spe,
        groups = as.character(sce$free_annotation),
        mgs = mgs_df,
        hvg = hvg,
        weight_id = "mean.AUC",
        group_id = "cluster",
        gene_id = "gene")

    ## Scaling count matrix

    ## Seeding NMF model...

    ## Training NMF model...

    ##
    ## iter |      tol
    ## ---------------
    ##    1 | 3.55e-01
    ##    2 | 1.70e-02
    ##    3 | 5.42e-03
    ##    4 | 2.61e-03
    ##    5 | 2.44e-03
    ##    6 | 4.11e-03
    ##    7 | 5.75e-03
    ##    8 | 3.23e-03
    ##    9 | 7.79e-04
    ##   10 | 2.45e-04
    ##   11 | 1.97e-04
    ##   12 | 2.11e-04
    ##   13 | 1.54e-04
    ##   14 | 9.20e-05
    ##   15 | 7.23e-05
    ##   16 | 6.54e-05
    ##   17 | 5.64e-05
    ##   18 | 5.33e-05
    ##   19 | 5.36e-05
    ##   20 | 5.76e-05
    ##   21 | 6.67e-05
    ##   22 | 8.24e-05
    ##   23 | 1.08e-04
    ##   24 | 1.50e-04
    ##   25 | 2.18e-04
    ##   26 | 3.26e-04
    ##   27 | 4.91e-04
    ##   28 | 7.17e-04
    ##   29 | 9.58e-04
    ##   30 | 1.07e-03
    ##   31 | 9.63e-04
    ##   32 | 7.00e-04
    ##   33 | 4.18e-04
    ##   34 | 2.14e-04
    ##   35 | 1.01e-04
    ##   36 | 4.76e-05
    ##   37 | 2.34e-05
    ##   38 | 1.21e-05
    ##   39 | 6.43e-06

    ## Time for training: 0.01min

    ## Removing genes in mixture matrix that are all 0s

    ## Keep intersection of genes between W and mixture matrix

    ## Deconvoluting mixture data...

Alternatively you can run `SPOTlight` in two steps so that you can have the trained model. Having the trained model allows you to reuse with other datasets you also want to deconvolute with the same reference. This allows you to skip the training step, the most time consuming and computationally expensive.

    mod_ls <- trainNMF(
        x = sce,
        groups = sce$free_annotation,
        mgs = mgs_df,
        hvg = hvg,
        weight_id = "mean.AUC",
        group_id = "cluster",
        gene_id = "gene")

     # Run deconvolution
    res <- runDeconvolution(
        x = spe,
        mod = mod_ls[["mod"]],
        ref = mod_ls[["topic"]])

Extract data from `SPOTlight`:

    # Extract deconvolution matrix
    head(mat <- res$mat)[, seq_len(3)]

    ##                    CD45    B cell CD45    macrophage CD45    NK cell
    ## AAACCGTTCGTCCAGG-1    0.000000000         0.04771785     0.041574190
    ## AAACCTAAGCAGCCGG-1    0.000000000         0.02996666     0.000000000
    ## AAACGAGACGGTTGAT-1    0.000000000         0.07767285     0.000773744
    ## AAACGGTTGCGAACTG-1    0.000000000         0.05843002     0.020128945
    ## AAACTCGGTTCGCAAT-1    0.000000000         0.04835413     0.212395231
    ## AAACTGCTGGCTCCAA-1    0.004710682         0.03734324     0.006813614

    # Extract NMF model fit
    mod <- res$NMF

# Visualization

In the next section we show how to visualize the data and interpret `SPOTlight`’s results.

## Topic profiles

We first take a look at the Topic profiles. By setting `facet = FALSE` we want to evaluate how specific each topic signature is for each cell identity. Ideally each cell identity will have a unique topic profile associated to it as seen below.

    plotTopicProfiles(
        x = mod,
        y = sce$free_annotation,
        facet = FALSE,
        min_prop = 0.01,
        ncol = 1) +
        theme(aspect.ratio = 1)

Next we also want to ensure that all the cells from the same cell identity share a similar topic profile since this will mean that `SPOTlight` has learned a consistent signature for all the cells from the same cell identity.

    plotTopicProfiles(
        x = mod,
        y = sce$free_annotation,
        facet = TRUE,
        min_prop = 0.01,
        ncol = 6)

Lastly we can take a look at which genes the model learned for each topic. Higher values indicate that the gene is more relevant for that topic. In the below table we can see how the top genes for `Topic1` are characteristic for B cells (i.e. Cd79a, Cd79b, Ms4a1…).

    # library(NMF)
    sign <- mod$w
    # colnames(sign) <- paste0("Topic", seq_len(ncol(sign)))
    head(sign)

    ##            topic_1      topic_2      topic_3      topic_4    topic_5
    ## Cd79a 0.0000000000 0.0000000000 0.000000e+00 0.0000000000 0.00000000
    ## Ly6d  0.0000000000 0.0000000000 0.000000e+00 0.0000000000 0.00000000
    ## Fau   0.0005155717 0.0006179161 5.940948e-04 0.0007164288 0.00111325
    ## Cd37  0.0000000000 0.0000000000 0.000000e+00 0.0000000000 0.00000000
    ## Cd79b 0.0000000000 0.0000000000 2.396451e-05 0.0000000000 0.00000000
    ## Cd74  0.0000000000 0.0000000000 0.000000e+00 0.0000000000 0.00000000
    ##            topic_6      topic_7      topic_8      topic_9     topic_10
    ## Cd79a 0.0000000000 0.000000e+00 0.0000000000 0.0000000000 0.000000e+00
    ## Ly6d  0.0000000000 0.000000e+00 0.0000000000 0.0000000000 5.410819e-05
    ## Fau   0.0015971966 6.636186e-04 0.0005490065 0.0007601035 1.095875e-03
    ## Cd37  0.0001509932 0.000000e+00 0.0000000000 0.0000000000 0.000000e+00
    ## Cd79b 0.0000000000 2.666646e-06 0.0000000000 0.0000000000 0.000000e+00
    ## Cd74  0.0028184601 0.000000e+00 0.0000000000 0.0000000000 0.000000e+00
    ##          topic_11    topic_12     topic_13    topic_14     topic_15
    ## Cd79a 0.000000000 0.000000000 0.000000e+00 0.006144174 0.0000000000
    ## Ly6d  0.000000000 0.000000000 4.651268e-05 0.005917158 0.0000000000
    ## Fau   0.000598881 0.001951595 6.789650e-04 0.004109234 0.0006846626
    ## Cd37  0.000000000 0.001881337 0.000000e+00 0.006392151 0.0000000000
    ## Cd79b 0.000000000 0.000000000 2.770860e-06 0.006551189 0.0000000000
    ## Cd74  0.000000000 0.000000000 0.000000e+00 0.001094615 0.0000000000
    ##           topic_16     topic_17
    ## Cd79a 0.0000000000 0.0027225159
    ## Ly6d  0.0000000000 0.0007827911
    ## Fau   0.0004306058 0.0011140137
    ## Cd37  0.0000000000 0.0007874762
    ## Cd79b 0.0000000000 0.0006622532
    ## Cd74  0.0000000000 0.0006566777

    # This can be dynamically visualized with DT as shown below
    # DT::datatable(sign, fillContainer = TRUE, filter = "top")

## Spatial Correlation Matrix

See here for additional graphical parameters.

    plotCorrelationMatrix(mat)

    ## Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
    ## ℹ Please use tidy evaluation idioms with `aes()`.
    ## ℹ See also `vignette("ggplot2-in-packages")` for more information.
    ## ℹ The deprecated feature was likely used in the ggcorrplot package.
    ##   Please report the issue at <https://github.com/kassambara/ggcorrplot/issues>.
    ## This warning is displayed once per session.
    ## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    ## generated.

## Co-localization

Now that we know which cell types are found within each spot we can make a graph representing spatial interactions where cell types will have stronger edges between them the more often we find them within the same spot.

See here for additional graphical parameters.

    plotInteractions(mat, which = "heatmap", metric = "prop")

    plotInteractions(mat, which = "heatmap", metric = "jaccard")

    plotInteractions(mat, which = "network")

## Scatterpie

We can also visualize the cell type proportions as sections of a pie chart for each spot. You can modify the colors as you would a standard ggplot2.

    ct <- colnames(mat)
    mat[mat < 0.1] <- 0

    # Define color palette
    # (here we use 'paletteMartin' from the 'colorBlindness' package)
    paletteMartin <- c(
        "#000000", "#004949", "#009292", "#ff6db6", "#ffb6db",
        "#490092", "#006ddb", "#b66dff", "#6db6ff", "#b6dbff",
        "#920000", "#924900", "#db6d00", "#24ff24", "#ffff6d")

    pal <- colorRampPalette(paletteMartin)(length(ct))
    names(pal) <- ct

    plotSpatialScatterpie(
        x = spe,
        y = mat,
        cell_types = colnames(mat),
        img = FALSE,
        scatterpie_alpha = 1,
        pie_scale = 0.4) +
        scale_fill_manual(
            values = pal,
            breaks = names(pal))

With the image underneath - we are rotating it 90 degrees counterclockwise and mirroring across the horizontal axis to show how to align if the spots don’t overlay the image.

    plotSpatialScatterpie(
        x = spe,
        y = mat,
        cell_types = colnames(mat),
        img = FALSE,
        scatterpie_alpha = 1,
        pie_scale = 0.4,
        # Rotate the image 90 degrees counterclockwise
        degrees = -90,
        # Pivot the image on its x axis
        axis = "h") +
        scale_fill_manual(
            values = pal,
            breaks = names(pal))

## Residuals

Lastly we can also take a look at how well the model predicted the proportions for each spot. We do this by looking at the residuals of the sum of squares for each spot which indicates the amount of biological signal not explained by the model.

    spe$res_ss <- res[[2]][colnames(spe)]
    xy <- spatialCoords(spe)
    spe$x <- xy[, 1]
    spe$y <- xy[, 2]
    ggcells(spe, aes(x, y, color = res_ss)) +
        geom_point() +
        scale_color_viridis_c() +
        coord_fixed() +
        theme_bw()

# Session information

    sessionInfo()

    ## R version 4.6.0 (2026-04-24)
    ## Platform: x86_64-pc-linux-gnu
    ## Running under: Ubuntu 24.04.4 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
    ## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.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: Etc/UTC
    ## tzcode source: system (glibc)
    ##
    ## attached base packages:
    ## [1] stats4    stats     graphics  grDevices utils     datasets  methods
    ## [8] base
    ##
    ## other attached packages:
    ##  [1] rhdf5_2.57.1                TabulaMurisSenisData_1.19.0
    ##  [3] TENxVisiumData_1.21.0       ExperimentHub_3.3.0
    ##  [5] AnnotationHub_4.3.0         BiocFileCache_3.3.0
    ##  [7] dbplyr_2.5.2                scran_1.41.1
    ##  [9] scater_1.41.1               scuttle_1.23.1
    ## [11] SpatialExperiment_1.23.0    SingleCellExperiment_1.35.1
    ## [13] SummarizedExperiment_1.43.0 Biobase_2.73.1
    ## [15] GenomicRanges_1.65.0        Seqinfo_1.3.0
    ## [17] IRanges_2.47.2              S4Vectors_0.51.3
    ## [19] BiocGenerics_0.59.6         generics_0.1.4
    ## [21] MatrixGenerics_1.25.0       matrixStats_1.5.0
    ## [23] SPOTlight_1.17.0            ggplot2_4.0.3
    ## [25] BiocStyle_2.41.0
    ##
    ## loaded via a namespace (and not attached):
    ##   [1] RColorBrewer_1.1-3       sys_3.4.3                jsonlite_2.0.0
    ##   [4] magrittr_2.0.5           ggbeeswarm_0.7.3         magick_2.9.1
    ##   [7] farver_2.1.2             rmarkdown_2.31           fs_2.1.0
    ##  [10] vctrs_0.7.3              memoise_2.0.1            htmltools_0.5.9
    ##  [13] S4Arrays_1.13.0          curl_7.1.0               BiocNeighbors_2.7.2
    ##  [16] Rhdf5lib_2.1.0           SparseArray_1.13.2       sass_0.4.10
    ##  [19] bslib_0.11.0             plyr_1.8.9               httr2_1.2.2
    ##  [22] cachem_1.1.0             buildtools_1.0.0         igraph_2.3.1
    ##  [25] lifecycle_1.0.5          pkgconfig_2.0.3          rsvd_1.0.5
    ##  [28] Matrix_1.7-5             R6_2.6.1                 fastmap_1.2.0
    ##  [31] digest_0.6.39            AnnotationDbi_1.75.0     dqrng_0.4.1
    ##  [34] irlba_2.3.7              RSQLite_3.53.1           beachmat_2.29.0
    ##  [37] filelock_1.0.3           labeling_0.4.3           gdata_3.0.1
    ##  [40] polyclip_1.10-7          httr_1.4.8               abind_1.4-8
    ##  [43] compiler_4.6.0           bit64_4.8.2              withr_3.0.2
    ##  [46] S7_0.2.2                 ggcorrplot_0.1.4.1       BiocParallel_1.47.0
    ##  [49] viridis_0.6.5            DBI_1.3.0                ggforce_0.5.0
    ##  [52] HDF5Array_1.41.0         MASS_7.3-65              rappdirs_0.3.4
    ##  [55] DelayedArray_0.39.3      rjson_0.2.23             bluster_1.23.0
    ##  [58] gtools_3.9.5             tools_4.6.0              vipor_0.4.7
    ##  [61] beeswarm_0.4.0           scatterpie_0.2.6         glue_1.8.1
    ##  [64] h5mread_1.5.0            rhdf5filters_1.25.0      grid_4.6.0
    ##  [67] cluster_2.1.8.2          reshape2_1.4.5           gtable_0.3.6
    ##  [70] tidyr_1.3.2              BiocSingular_1.29.0      ScaledMatrix_1.21.0
    ##  [73] metapod_1.21.0           XVector_0.53.0           ggrepel_0.9.8
    ##  [76] BiocVersion_3.24.0       pillar_1.11.1            stringr_1.6.0
    ##  [79] yulab.utils_0.2.4        limma_3.69.1             tweenr_2.0.3
    ##  [82] dplyr_1.2.1              lattice_0.22-9           bit_4.6.0
    ##  [85] tidyselect_1.2.1         locfit_1.5-9.12          maketools_1.3.2
    ##  [88] Biostrings_2.81.2        knitr_1.51               gridExtra_2.3
    ##  [91] edgeR_4.11.1             xfun_0.57                statmod_1.5.2
    ##  [94] stringi_1.8.7            ggfun_0.2.0              yaml_2.3.12
    ##  [97] evaluate_1.0.5           codetools_0.2-20         tibble_3.3.1
    ## [100] BiocManager_1.30.27      cli_3.6.6                jquerylib_0.1.4
    ## [103] Rcpp_1.1.1-1.1           png_0.1-9                parallel_4.6.0
    ## [106] blob_1.3.0               sparseMatrixStats_1.25.0 viridisLite_0.4.3
    ## [109] scales_1.4.0             purrr_1.2.2              crayon_1.5.3
    ## [112] rlang_1.2.0              KEGGREST_1.53.0