knitr::opts_chunk$set(echo = TRUE) options(bitmapType="cairo")
This is a quick walkthrough demonstrating how to generate SWNE plots starting from a counts matrix using a 3k PBMC dataset as an example. You can download the matrix here
First let's load the required libraries
library(irlba) library(Matrix) library(swne)
Next let's load the matrix, convert it to a sparse matrix to save memory, and filter and trim the genes
counts <- read.table("~/swne/Data/pbmc3k_matrix.tsv.gz", header = T, sep = "\t") counts <- as(as.matrix(counts), "dgCMatrix") counts <- FilterData(counts, min.samples.frac = 0.001, trim = 3, min.nonzero.features = 0, max.sample.sum = Inf)
Most scRNA-seq pipelines only use a subset of highly overdispersed genes for analysis. We'll pull out those variable genes here, as well as the cluster labels
## Pull out overdispersed genes as defined by Seurat var.genes <- SelectFeatures(counts, n.features = 3000) length(var.genes) ## Pull out cell clusters as defined by Seurat cell.clusters <- factor(sapply(colnames(counts), ExtractField, field = 2, delim = "_")) names(cell.clusters) <- colnames(counts) table(cell.clusters)
Next we will normalize and run variance stabilization on the counts matrix
norm.counts <- ScaleCounts(counts)
The easiest way to generate an SWNE embedding is to use the wrapper function RunSWNE
## Run SWNE genes.embed <- c("MS4A1", "GNLY", "CD3E", "CD14", "FCER1A", "FCGR3A", "LYZ", "PPBP", "CD8A") swne.embedding <- RunSWNE(norm.counts, k = 16, var.genes = var.genes, genes.embed = genes.embed, sample.groups = cell.clusters) ## Plot SWNE PlotSWNE(swne.embedding, alpha.plot = 0.4, sample.groups = cell.clusters, do.label = T, label.size = 3.5, pt.size = 1, show.legend = F, seed = 42)
We can validate the embedded genes by overlaying the expression of one of these key genes onto the plot.
gene.use <- "CD8A" gene.expr <- norm.counts[gene.use,] FeaturePlotSWNE(swne.embedding, gene.expr, gene.use, alpha.plot = 0.4, label.size = 3.5, pt.size = 1.25)
Finally, we can extract cluster colors for compatibility with other plotting methods (i.e. Monocle)
color.mapping <- ExtractSWNEColors(swne.embedding, sample.groups = cell.clusters, seed = 42) color.mapping
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.