Analysis of single-cell RNA-seq data: building and annotating an atlas¶
This R notebook pre-processes the pbmc_1k v3 dataset from 10X Genomics with kallisto and bustools using kb, and then performs an analysis of the cell types and their marker genes.
If you use the methods in this notebook for your analysis please cite the following publications which describe the tools used in the notebook:
Melsted, P., Booeshaghi, A.S. et al. Modular and efficient pre-processing of single-cell RNA-seq. bioRxiv (2019). doi:10.1101/673285
Stuart, Butler et al. Comprehensive Integration of Single-cell Data. Cell (2019). doi:10.1016/j.cell.2019.05.031
A Python notebook implementing the same analysis is available here. See the kallistobus.tools tutorials site for additional notebooks demonstrating other analyses.
A large fraction of the running time of this notebook is in installing the Seurat R package, since it has lots of dependencies and many of them use Rcpp which results in the need to compile lots of C++ code. Compilation is required because CRAN does not distribute binaries for Linux, which is the operating system here.
The package installation took 20 minutes (elapsed) which is 40% of the running time of the entire notebook. The user time is nearly twice the elapsed time here because 2 cores were used to install all those packages.
'Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.1.2->scanpy>=1.4.4.post1->kb-python) (1.3.1)'
'Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=3.1.2->scanpy>=1.4.4.post1->kb-python) (0.10.0)'
'Requirement already satisfied: numexpr>=2.5.2 in /usr/local/lib/python3.7/dist-packages (from tables->scanpy>=1.4.4.post1->kb-python) (2.7.3)'
'Building wheels for collected packages: pyseq-align'
' Building wheel for pyseq-align (PEP 517): started'
' Building wheel for pyseq-align (PEP 517): finished with status \'done\''
' Created wheel for pyseq-align: filename=pyseq_align-1.0.1-cp37-cp37m-linux_x86_64.whl size=686394 sha256=6500e93a0c7db9c0402435e26ff086a6b2d405f49db84e6618f3732c434a2bf6'
' Stored in directory: /root/.cache/pip/wheels/0c/b1/e3/fa70b771fd8d22b9c258c297b50377554c7a79fedc6f27e755'
' Building wheel for kb-python (setup.py): started'
' Building wheel for kb-python (setup.py): finished with status \'done\''
' Created wheel for kb-python: filename=kb_python-0.26.3-cp37-none-any.whl size=7403478 sha256=d1790b417ee560c5217f8acd100d0497526aebae1663d2ca0aa85f9295230f5a'
' Stored in directory: /root/.cache/pip/wheels/df/fd/0a/b4bb0ebbbc01a3d4db97ea0295f286e93f04c20bd9b6dd12b4'
' Building wheel for loompy (setup.py): started'
' Building wheel for loompy (setup.py): finished with status \'done\''
' Created wheel for loompy: filename=loompy-3.0.6-cp37-none-any.whl size=47906 sha256=7c975a62127fd8c1ac93dd44444b0f7a16a6f690e58fe6fef0a5daa0ffc2f02c'
' Stored in directory: /root/.cache/pip/wheels/f9/a4/90/5a98ad83419732b0fba533b81a2a52ba3dbe230a936ca4cdc9'
' Building wheel for ngs-tools (setup.py): started'
' Building wheel for ngs-tools (setup.py): finished with status \'done\''
' Created wheel for ngs-tools: filename=ngs_tools-1.5.2-cp37-none-any.whl size=51706830 sha256=8ef40ccb4ed6227ed96a7ff8739653754fea9a53e025e4683541fdd2a530841b'
' Stored in directory: /root/.cache/pip/wheels/2e/31/cf/0a6ca9e66d8b858a6b0d060dbefbf1c9299d6aab435930ae74'
' Building wheel for numpy-groupies (setup.py): started'
' Building wheel for numpy-groupies (setup.py): finished with status \'done\''
' Created wheel for numpy-groupies: filename=numpy_groupies-0.9.13-cp37-none-any.whl size=24090 sha256=a05925678069bc250c50be9e072866b419590a32f5696543fe7a0956795919f5'
' Stored in directory: /root/.cache/pip/wheels/ef/97/d7/270bc85eb8b1b84629caac97a3900bff23edb7f834f6ed729e'
' Building wheel for sinfo (setup.py): started'
' Building wheel for sinfo (setup.py): finished with status \'done\''
' Created wheel for sinfo: filename=sinfo-0.3.4-cp37-none-any.whl size=7899 sha256=958f8f7b81e566dffb7e6e19c0b504e8ded1797e3f60318a396e63a379533937'
' Stored in directory: /root/.cache/pip/wheels/43/a4/e5/d4e0a170ccc134e509ea55acad7845f0fdfa62b964e430f0e3'
' Building wheel for umap-learn (setup.py): started'
' Building wheel for umap-learn (setup.py): finished with status \'done\''
' Created wheel for umap-learn: filename=umap_learn-0.5.1-cp37-none-any.whl size=76569 sha256=414f3a7eaa8d0e7f2d50a70d40d6cb6404bed9eabdff0fc62dce327c3e862e9c'
' Stored in directory: /root/.cache/pip/wheels/ad/df/d5/a3691296ff779f25cd1cf415a3af954b987fb53111e3392cf4'
' Building wheel for pynndescent (setup.py): started'
' Building wheel for pynndescent (setup.py): finished with status \'done\''
' Created wheel for pynndescent: filename=pynndescent-0.5.4-cp37-none-any.whl size=52374 sha256=442e4aa56fab942c7e3a3051c3ce51f416ecb8e2e2e622e9472a3f39a0a1ff20'
' Stored in directory: /root/.cache/pip/wheels/42/4b/8c/f6f119c67cf6583bb192431fa8f7278cf95e5b943055077d94'
'Successfully built kb-python loompy ngs-tools numpy-groupies sinfo umap-learn pynndescent'
# Download the data from the 10x websitesystem("wget http://cf.10xgenomics.com/samples/cell-exp/3.0.0/pbmc_1k_v3/pbmc_1k_v3_fastqs.tar",intern=TRUE)system("tar -xvf pbmc_1k_v3_fastqs.tar",intern=TRUE)
# Slightly modified from BUSpaRse, just to avoid installing a few dependencies not used hereread_count_output<-function(dir,name){dir<-normalizePath(dir,mustWork=TRUE)m<-readMM(paste0(dir,"/",name,".mtx"))m<-Matrix::t(m)m<-as(m,"dgCMatrix")# The matrix read has cells in rowsge<-".genes.txt"genes<-readLines(file(paste0(dir,"/",name,ge)))barcodes<-readLines(file(paste0(dir,"/",name,".barcodes.txt")))colnames(m)<-barcodesrownames(m)<-genesreturn(m)}
Lots of points are piled at around 1 gene and 1 count, and those with 0 gene or count were removed for introducing -Inf in log transform. These correspond to empty or near empty droplets.
In this plot cells are ordered by the number of UMI counts associated to them (shown on the x-axis), and the fraction of droplets with at least that number of cells is shown on the y-axis:
1
summary(tot_counts)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.00 1.00 1.00 43.64 6.00 60120.00
#' @rdname knee_plot#' @param mat Gene count matrix, a dgCMatrix.#' @return `get_knee_df` returns a tibble with two columns: \code{total} for #' total UMI counts for each barcode, and \code{rank} for rank of the total #' counts, with number 1 for the barcode with the most counts.#' @export#' @importFrom dplyr row_number desc arrange#' @importFrom Matrix colSumsget_knee_df<-function(mat){total<-rank<-NULLtibble(total=Matrix::colSums(mat),rank=row_number(desc(total)))%>%distinct()%>%dplyr::filter(total>0)%>%arrange(rank)}#' @rdname knee_plot#' @param df The data frame from \code{\link{get_knee_df}}.#' @param lower Minimum total UMI counts for barcode for it to be considered#' when calculating the inflection point; this helps to avoid the noisy part of#' the curve for barcodes with very few counts.#' @return `get_inflection` returns a \code{numeric(1)} for the total UMI count #' at the inflection point.#' @note Code in part adapted from \code{barcodeRanks} from \code{DropetUtils}.#' @export#' @importFrom dplyr transmute#' get_inflection<-function(df,lower=100){log_total<-log_rank<-total<-NULLdf_fit<-df%>%dplyr::filter(total>lower)%>%transmute(log_total=log10(total),log_rank=log10(rank))d1n<-diff(df_fit$log_total)/diff(df_fit$log_rank)right.edge<-which.min(d1n)10^(df_fit$log_total[right.edge])}#' Plot the transposed knee plot and inflection point#' #' Plot a transposed knee plot, showing the inflection point and#' the number of remaining cells after inflection point filtering. It's#' transposed since it's more generalizable to multi-modal data. Taken from the #' BUSpaRse package.#' #' @param df The data frame from \code{\link{get_knee_df}}.#' @param inflection Output of \code{\link{get_inflection}}.#' @return `knee_plot` returns a \code{ggplot2} object.#' @export#' @importFrom ggplot2 ggplot aes geom_path geom_vline geom_hline #' scale_x_log10 scale_y_log10 labs annotation_logticks geom_textknee_plot<-function(df,inflection){total<-rank_cutoff<-NULLannot<-tibble(inflection=inflection,rank_cutoff=max(df$rank[df$total>inflection]))ggplot(df,aes(total,rank))+geom_path()+geom_vline(aes(xintercept=inflection),data=annot,linetype=2,color="gray40")+geom_hline(aes(yintercept=rank_cutoff),data=annot,linetype=2,color="gray40")+geom_text(aes(inflection,rank_cutoff,label=paste(rank_cutoff,"'cells'")),data=annot,vjust=1)+scale_x_log10()+scale_y_log10()+labs(y="Rank",x="Total UMIs")+annotation_logticks()}
plot_pct_genes<-function(mat,tr2g,top_n=20,symbol="ensembl"){pct_tx<-rowSums(mat)gs<-rownames(mat)[order(-pct_tx)]df<-as.data.frame(t(mat[gs[1:20],]))df<-df%>%mutate_all(function(x)x/colSums(mat))%>%pivot_longer(everything(),names_to="gene")if (symbol=="ensembl"){df<-left_join(df,tr2g,by="gene")}else{df<-rename(df,gene_name=gene)}df%>%mutate(gene=fct_reorder(gene_name,value,.fun=median))%>%ggplot(aes(gene,value))+geom_boxplot()+labs(x="",y="Proportion of total counts")+coord_flip()}
For many barcodes, the top genes by proportion of all counts are ribosomal or mitochondrial genes. Also, the proportions plotted above seem to have some discrete values; this effect is a result of computing fractions with small denominator, which happens when droplets produce very few UMI counts.
The steps below constitute a standard analysis worklow for single-cell RNA-seq data.
12
# The [[ operator can add columns to object metadata. This is a great place to stash QC statspbmc[["percent.mt"]]<-PercentageFeatureSet(pbmc,pattern="^MT-")
The number of unique genes and total molecules are automatically calculated when running the CreateSeuratObject command.
The associated data is stored in the object metadata.
12
# Show QC metrics for the first 5 cellshead(pbmc@meta.data,5)
A data.frame: 5 × 4
orig.ident
nCount_RNA
nFeature_RNA
percent.mt
<fct>
<dbl>
<int>
<dbl>
AAACCCAAGGAGAGTA
pbmc1k
9289
3198
11.271396
AAACGCTTCAGCCCAG
pbmc1k
6483
2513
8.252352
AAAGAACAGACGACTG
pbmc1k
5011
2082
6.166434
AAAGAACCAATGGCAG
pbmc1k
3264
1555
6.893382
AAAGAACGTCTGCAAT
pbmc1k
7488
2508
6.610577
Next, we visualize some QC metrics and use the results to set filtering criteria.
123
# Visualize QC metrics as a violin plotoptions(repr.plot.width=12,repr.plot.height=6)VlnPlot(pbmc,features=c("nFeature_RNA","nCount_RNA","percent.mt"),ncol=3)
12345
# FeatureScatter is typically used to visualize feature-feature relationships, but can be used# for anything calculated by the object, i.e. columns in object metadata, PC scores etc.plot1<-FeatureScatter(pbmc,feature1="nCount_RNA",feature2="percent.mt")plot2<-FeatureScatter(pbmc,feature1="nCount_RNA",feature2="nFeature_RNA")plot1+plot2
After removing unwanted cells from the dataset, the next step is to normalize the data. A standard choice is LogNormalize which normalizes the UMI counts for each cell by the total counts, multiplies this by a scale factor (10,000 by default), and finally log-transforms the result.
We recommend the preprint
- Breda, J., Zavolan, M. and van Nimwegen, E. Bayesian inference of the gene expression states of single cells from scRNA-seq data. bioRxiv (2019). doi.org/10.1101/2019.12.28.889956
For clarity, in this previous line of code (and in future commands), we provide the default values for certain parameters in the function call. However, this isn’t required and the same behavior can be achieved with:
To identify a subset of genes that exhibit high cell-to-cell variation in the dataset we apply a procedure implemented in the FindVariableFeatures function. By default, it returns 2,000 genes per dataset. These will be used in downstream analysis.
Seurat documentation describes the method used to find highly variable genes here as such:
First, fits a line to the relationship of log(variance) and log(mean) using local polynomial regression (loess). Then standardizes the feature values using the observed mean and expected variance (given by the fitted line). Feature variance is then calculated on the standardized values after clipping to a maximum (see clip.max parameter).
options(repr.plot.width=9,repr.plot.height=6)pbmc<-FindVariableFeatures(pbmc,selection.method="vst",nfeatures=2000)# Identify the 10 most highly variable genestop10<-head(VariableFeatures(pbmc),10)# plot variable features with and without labelsplot1<-VariableFeaturePlot(pbmc,log=FALSE)LabelPoints(plot=plot1,points=top10,repel=TRUE)
Next, we apply a linear transformation (‘scaling’) that is a standard pre-processing step prior to dimensional reduction techniques like PCA. The ScaleData function shifts the expression of each gene, so that the mean expression across cells is 0 and the variance across cells is 1
This step gives equal weight to genes in downstream analyses, so that highly-expressed genes do not dominate.
We apply this only to the genes identified as highly variable:
1
# pbmc <- ScaleData(pbmc)
The scaling does not affect PCA or clustering results. However, Seurat heatmaps (produced as shown below with DoHeatmap) require genes in the heatmap to be scaled so that highly-expressed genes don’t dominate. To make sure we don’t leave any genes out of the heatmap later, we are scaling all genes in this tutorial.
In Seurat v2 we also use the ScaleData function to remove unwanted sources of variation from a single-cell dataset. For example, we could ‘regress out’ heterogeneity associated with (for example) cell cycle stage, or mitochondrial contamination. These features are still supported in ScaleData in Seurat v3, i.e.:
To overcome the extensive technical noise in any single feature for scRNA-seq data, one can cluster cells based on their PCA projections, with each PC essentially representing a ‘metafeature’ that combines information across a correlated feature set.
A common heuristic method generates an ‘Elbow plot’: a ranking of principle components based on the percentage of variance explained by each one (ElbowPlot function). In this example, we can observe an ‘elbow’ around PC9-10, suggesting that the majority of true signal is captured in the first 10 PCs.
We cluster cells using the Louvain algorithm (a default in Seurat), which iteratively group cells together, with the goal of optimizing the standard modularity function. The FindClusters function implements this procedure, and contains a resolution parameter that sets the ‘granularity’ of the downstream clustering, with increased values leading to a greater number of clusters. We find that setting this parameter between 0.4-1.2 typically returns good results for single-cell datasets of around 3K cells. Optimal resolution often increases for larger datasets. The clusters can be found using the Idents function.
tSNE and UMAP can be used to visualize and explore non-linear aspects of high-dimensional data. Here we apply these methods to the PC projection of the data (with same dimension as used for clustering).
UMAP (UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction) is a manifold learning technique that can also be used to visualize cells. It was published in:
McInnes, Leland, John Healy, and James Melville. "Umap: Uniform manifold approximation and projection for dimension reduction." arXiv preprint arXiv:1802.03426 (2018).
t-SNE is a non-linear dimensionality reduction technique described in:
Maaten, Laurens van der, and Geoffrey Hinton. "Visualizing data using t-SNE." Journal of machine learning research 9.Nov (2008): 2579-2605.
Finding differentially expressed features (cluster biomarkers)¶
A key follow-up step to clustering cells is to find gene markers that are associated with them. We used Seurat's FindAllMarkers function which automates the process for all clusters.
The min.pct argument requires a feature to be detected at a minimum percentage in either of the two groups of cells, and the thresh.test argument requires a feature to be differentially expressed (on average) by some amount between the two groups. You can set both of these to 0, but with a dramatic increase in time - since this will test a large number of features that are unlikely to be highly discriminatory. As another option to speed up these computations, max.cells.per.ident can be set. This will downsample each identity class to have no more cells than whatever this is set to. While there is generally going to be a loss in power, the speed increases can be significiant and the most highly differentially expressed features will likely still rise to the top.
Several methods for differential expression are supported by Seurat. The default is Wilcoxon rank sum test.
123
# find markers for every cluster compared to all remaining cells, report only the positive onespbmc.markers<-FindAllMarkers(pbmc,test.use="wilcox",only.pos=TRUE,min.pct=0.25,logfc.threshold=0.25)
Calculating cluster 0
Calculating cluster 1
Calculating cluster 2
Calculating cluster 3
Calculating cluster 4
Calculating cluster 5
Calculating cluster 6
Calculating cluster 7
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Calculating cluster 8
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: algorithm did not converge”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
Warning message:
“glm.fit: fitted probabilities numerically 0 or 1 occurred”
1
plot_gene_rank(pbmc.markers.lr,25)
Seurat includes several tools for visualizing marker expression. VlnPlot (shows expression probability distributions across clusters), and FeaturePlot (visualizes feature expression on a tSNE or PCA plot) are our most commonly used visualizations. We also suggest exploring RidgePlot, CellScatter, and DotPlot as additional methods to view your dataset.