Figures#
cytepool.plotting draws, in one call each, the figures that limma, edgeR,
DESeq2, speckle and metafor draw, from CytePool’s cubes and results. It needs
matplotlib: install CytePool’s plot extra (pip install "cytepool[plot]"), or
matplotlib itself.
Figures of pseudobulk and bulk analyses, drawn as limma, edgeR, DESeq2, speckle, metafor and variancePartition draw them.
Each function draws one figure from the objects that CytePool’s analyses return: a
cube, a voom result, a fit, the table of a differential-expression or gene-set test,
or a composition or meta-analysis result. It reads the values from them, so that a
figure shows what the analysis computed, draws into ax, a matplotlib Axes, or into
a new figure when ax is None, and returns the Axes, whose title, limits and labels
can then be changed. The artists that show data carry a gid that names what they
show, such as "trend", so that they can be found and restyled; each function lists
its own.
matplotlib is an optional dependency: install CytePool’s plot extra, or matplotlib
3.9 or newer. These functions import it when they draw, and change none of its
settings.
The figures:
Samples:
plot_mds(), the multidimensional scaling plot of limma’splotMDS(Ritchie et al. 2015), whose distances are leading log2 fold changes.Cubes:
plot_cell_numbers(), the cells pooled into each sample and group.Composition:
plot_composition(), the cell-type proportions of every sample, as speckle’splotCellTypePropsdraws them;plot_proportions(), the proportions of every cell type by condition, with the adjusted p-values ofpropeller(Phipson et al. 2022).Mean-variance trends:
plot_mean_variance(), voom’s plot (Law et al. 2014);plot_residual_variances(), limma’splotSA.Sample weights:
plot_sample_weights(), the sample quality weights that limma’svoomWithQualityWeightsplots (Liu et al. 2015).Differential expression:
plot_md(), limma’s mean-difference plotplotMD;plot_volcano(), limma’svolcanoplot;plot_p_values(), a histogram of p-values;plot_significant_genes(), the genes up and down in every group.Gene sets:
plot_barcode(), limma’sbarcodeplot;plot_gene_sets(), the sets of acamera,fryormroasttable;plot_over_representation(), the sets of an over-representation analysis, as clusterProfiler’s dot plots show them (Yu et al. 2012).Count models:
plot_dispersions(), DESeq2’splotDispEsts(Love et al. 2014);plot_quasi_dispersions(), edgeR’splotQLDisp(Chen et al. 2016).Meta-analysis:
plot_forest(), the forest plot (Lewis and Clarke 2001) that metafor’sforestdraws (Viechtbauer 2010).Variance partitioning:
plot_variance_fractions(), the violins (Hintze and Nelson 1998) of the fractions of variance of every variable over the genes, as variancePartition’splotVarPartdraws them (Hoffman and Schadt 2016);plot_gene_variance_fractions(), the fractions of chosen genes as stacked bars, as itsplotPercentBarsdraws them.
validation/plotting.py compares what each figure shows with what the R function it
follows draws for the same data, where one exists.
- Colours:
Categories, such as the cell types of a composition or the levels of a sample variable, take eight hues in a fixed order: blue, orange, aqua, yellow, magenta, green, violet and red. Neighbouring hues stay apart for readers with colour-vision deficiencies, as measured under simulated protanopia and deuteranopia (Machado et al. 2009), and so do any two of the first three. A scatter plot of more than three levels therefore also gives each level a marker of its own, so that colour is never the only cue. Up and down are red and blue, values shown for context are grey, and numbers take shades of blue. A figure that would need more than eight hues raises an error that says how to merge or select the categories.
References
Ritchie ME, Phipson B, Wu D, Hu Y, Law CW, Shi W, Smyth GK (2015). limma powers differential expression analyses for RNA-sequencing and microarray studies. Nucleic Acids Research 43, e47. doi:10.1093/nar/gkv007
Law CW, Chen Y, Shi W, Smyth GK (2014). voom: precision weights unlock linear model analysis tools for RNA-seq read counts. Genome Biology 15, R29. doi:10.1186/gb-2014-15-2-r29
Liu R, Holik AZ, Su S, Jansz N, Chen K, Leong HS, Blewitt ME, Asselin-Labat ML, Smyth GK, Ritchie ME (2015). Why weight? Modelling sample and observational level variability improves power in RNA-seq analyses. Nucleic Acids Research 43, e97. doi:10.1093/nar/gkv412
Smyth GK (2004). Linear models and empirical Bayes methods for assessing differential expression in microarray experiments. Statistical Applications in Genetics and Molecular Biology 3, article 3. doi:10.2202/1544-6115.1027
Phipson B, Lee S, Majewski IJ, Alexander WS, Smyth GK (2016). Robust hyperparameter estimation protects against hypervariable genes and improves power to detect differential expression. Annals of Applied Statistics 10, 946-963. doi:10.1214/16-AOAS920
Benjamini Y, Hochberg Y (1995). Controlling the false discovery rate: a practical and powerful approach to multiple testing. Journal of the Royal Statistical Society B 57, 289-300. doi:10.1111/j.2517-6161.1995.tb02031.x
Gower JC (1966). Some distance properties of latent root and vector methods used in multivariate analysis. Biometrika 53, 325-338. doi:10.1093/biomet/53.3-4.325
Chen Y, Lun ATL, Smyth GK (2016). From reads to genes to pathways: differential expression analysis of RNA-Seq experiments using Rsubread and the edgeR quasi-likelihood pipeline. F1000Research 5, 1438. doi:10.12688/f1000research.8987.2
Phipson B, Sim CB, Porrello ER, Hewitt AW, Powell J, Oshlack A (2022). propeller: testing for differences in cell type proportions in single cell data. Bioinformatics 38, 4720-4726. doi:10.1093/bioinformatics/btac582
Love MI, Huber W, Anders S (2014). Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. Genome Biology 15, 550. doi:10.1186/s13059-014-0550-8
Lund SP, Nettleton D, McCarthy DJ, Smyth GK (2012). Detecting differential expression in RNA-sequence data using quasi-likelihood with shrunken dispersion estimates. Statistical Applications in Genetics and Molecular Biology 11(5), article 8. doi:10.1515/1544-6115.1826
Wu D, Smyth GK (2012). Camera: a competitive gene set test accounting for inter-gene correlation. Nucleic Acids Research 40, e133. doi:10.1093/nar/gks461
Yu G, Wang LG, Han Y, He QY (2012). clusterProfiler: an R package for comparing biological themes among gene clusters. OMICS 16, 284-287. doi:10.1089/omi.2011.0118
Lewis S, Clarke M (2001). Forest plots: trying to see the wood and the trees. BMJ 322, 1479-1480. doi:10.1136/bmj.322.7300.1479
Viechtbauer W (2010). Conducting meta-analyses in R with the metafor package. Journal of Statistical Software 36(3), 1-48. doi:10.18637/jss.v036.i03
Machado GM, Oliveira MM, Fernandes LAF (2009). A physiologically-based model for simulation of color vision deficiency. IEEE Transactions on Visualization and Computer Graphics 15, 1291-1298. doi:10.1109/TVCG.2009.113
Hoffman GE, Schadt EE (2016). variancePartition: interpreting drivers of variation in complex gene expression studies. BMC Bioinformatics 17, 483. doi:10.1186/s12859-016-1323-z
Hintze JL, Nelson RD (1998). Violin plots: a box plot-density trace synergism. The American Statistician 52, 181-184. doi:10.1080/00031305.1998.10480559
Silverman BW (1986). Density Estimation for Statistics and Data Analysis. Chapman and Hall, London.
- cytepool.plotting.plot_barcode(statistics, gene_set, *, gene_ids=None, span=_WORM_SPAN, ax=None)#
Plot where the genes of a set fall among all genes ranked by a statistic.
limma’s
barcodeplot(Ritchie et al. 2015) for one set: the genes ranked from the smallest statistic, on the left, to the largest, as a bed shaded at the ends where the statistic is below -sqrt(2) or above sqrt(2); a bar at the rank of every gene of the set; and above them the enrichment worm, the relative enrichment of the set along the ranking: the moving average of the set’s indicator over the ranked genes, with tricube weights over a window ofspanof the genes (limma’stricubeMovingAverage, whose weights were found by probing), divided by the set’s share of all genes. A worm above 1 (the dashed line) at the right shows a set enriched among the genes with large statistics. The worm is drawn above the bars, scaled to its largest value, which the axis gives, as limma draws it. The x-axis gives the statistic at five ranks.Draws the bed (gid
"bed"), the bars (gid"set") and the worm (gid"worm").- Parameters:
statistics – A table of a differential-expression result, whose
tcolumn (orstatistic, for a meta-analysis) ranks its genes, named by itsfeature_id; or one statistic per gene, finite.gene_set – The genes of the set: ids (of the table’s genes, or of
gene_ids), 0-based positions, or a boolean mask over the genes. Ids that are not among the genes are left out, as limma’sids2indicesleaves them.gene_ids – One id per gene, unique, to name the genes of
gene_setby id whenstatisticsis not a table.span – The share of the genes in each window of the worm, in (0, 1].
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or is or holds a numpy masked array.
ValueError – If the statistics are not finite and 1-D, fewer than two, the ids are not unique or have the wrong length, the set holds no gene, every gene, or a position out of range, or
spanis not in (0, 1].
- cytepool.plotting.plot_cell_numbers(cube, *, min_cells=_MIN_CELLS, numbers=None, ax=None)#
Plot the number of cells pooled into each sample and group of a cube.
A heatmap of
Cube.n_cells, one column per sample and one row per group (cell type) in the cube’s order, shaded in blue on a logarithmic scale. Entries with fewer thanmin_cellscells, whichlimma_voom()leaves out of a group’s fit with the samemin_cells, and entries without cells are pale grey, as the end of the colour bar shows.Draws the image (gid
"cell numbers") and, when asked, the number of each entry (gid"numbers").- Parameters:
cube – A cube that records cell numbers.
min_cells – The fewest cells an entry needs to be shaded, at least 0; None shades every entry with cells.
numbers – Whether to write each entry’s number; by default, when the cube has at most 800 entries.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
cubeis not a Cube or an option has the wrong type.ValueError – If the cube does not record cell numbers, or
min_cellsis negative.
- cytepool.plotting.plot_composition(data, *, by=None, ax=None)#
Plot the cell-type composition of every sample as stacked bars.
speckle’s
plotCellTypeProps: one bar per sample, divided into the proportions of its cells in each group (cell type), the first group on top. A cube gives the proportionsn_cellsover each sample’s cells in all groups, without the samples that have no cells; aCompositionResultgives those thatpropeller()tested, of its samples used and groups tested.bygroups the bars by a sample variable, such as the condition, whose levels are written above their bars.Draws the segments (gid
"proportions"), with a legend of the groups.- Parameters:
data – A cube that records cell numbers, or the result of
propeller.by – A sample variable: a column of the cube’s sample table, a variable of the result’s design, or one label per sample (of the cube, or of the result’s sample table).
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
datais neither a Cube nor a CompositionResult, orbyis or holds a numpy masked array.ValueError – If the cube does not record cell numbers, no sample has cells, there are more than eight groups (merge some with
Cube.regroup, or select some withCube.select, first), orbyhas the wrong length or a missing label.KeyError – If
bynames no variable of the data.
- cytepool.plotting.plot_dispersions(dispersions, *, ax=None)#
Plot DESeq2’s dispersion estimates against the mean normalized count.
DESeq2’s
plotDispEsts(Love et al. 2014), on logarithmic axes: the gene-wise estimates (dispGeneEst), the fitted trend (dispFit), drawn as a curve, and the final estimates (dispersion), the maximum a posteriori estimates shrunk towards the trend, with the dispersion outliers, which keep their gene-wise estimate, as open circles. Genes without counts are not drawn.Draws the gene-wise estimates (gid
"gene-wise"), the trend (gid"fitted"), the final estimates (gid"final") and the outliers (gid"outliers").- Parameters:
dispersions – The result of
deseq2_dispersions(), or a fit offit_deseq2()that estimated them.ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
dispersionsis neither DESeq2Dispersions nor a DESeq2Fit.ValueError – If the fit was given its dispersions, or no gene has counts.
- cytepool.plotting.plot_forest(meta, studies, feature, *, group=None, contrast=None, ax=None)#
Plot each study’s log2 fold change of a gene with its confidence interval, and the pooled estimate.
The forest plot (Lewis and Clarke 2001) that metafor’s
forestdraws for a model without moderators (Viechtbauer 2010), of one gene of adifferential_expression_meta_analysis(): a row per study, in the order ofstudies, with its log2 fold change as a square and the interval y_i +/- z s_i, z the normal quantile of the meta-analysis’s confidence level and s_i the study’s standard error, as metafor draws it whatever the test; and at the bottom the pooled estimate as a diamond spanning its confidence interval. A square’s area grows with the study’s weight in the pooled estimate, 1 / (s_i^2 + tau^2), scaled as metafor scales it. A study that did not test the gene keeps its row, marked “not tested”. The estimates and intervals are written to the right of the plot, and the pooled row is named with the estimator of tau^2 and I^2.Draws the intervals (gid
"intervals"), the squares (gid"estimates"), the diamond (gid"pooled") and a dotted line at zero.- Parameters:
meta – The meta-analysis.
studies – The differential-expression results it combined, by study name.
feature – The id of the gene.
group – The group (cell type) of the meta-analysis; it may be left out when the meta-analysis has one group, or one with
contrast.contrast – The contrast; likewise.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or is a numpy masked array.
ValueError – If the group and contrast are not given and the meta-analysis has several, or
studiesis empty.KeyError – If the group and contrast, or the gene, were not meta-analysed.
- cytepool.plotting.plot_gene_sets(table, *, top=20, alpha=0.05, ax=None)#
Plot the most significant gene sets of a gene-set test, by direction.
For the
topsets with the smallest p-values of a table ofcamera()(Wu and Smyth 2012),fry()ormroast(), a bar of length -log10 of the adjusted p-value, to the right for sets up and to the left for sets down, with dashed lines atalpha. Each set is named with its number of genes.Draws the bars (gid
"gene sets") and the lines (gid"alpha").- Parameters:
table – The table of a gene-set test, with the columns
gene_set,n_genes,direction,p_valueandadjusted_p_value.top – How many sets to show, at least 1.
alpha – The adjusted p-value of the dashed lines, in (0, 1).
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
tableis not a Table or an option has the wrong type.ValueError – If the table lacks a column or has no set with a p-value.
- cytepool.plotting.plot_gene_variance_fractions(data, genes, *, group=None, labels=None, sort=True, ax=None)#
Plot the fractions of variance of chosen genes as stacked bars.
variancePartition’s
plotPercentBars: one horizontal bar per gene, the first at the top, divided into the percentage of the gene’s variance that each variable explains, the residuals last. The variables are in the order ofplot_variance_fractions(): withsort, in decreasing order of their median over every gene of the data, asplotPercentBars(sortCols(x)[genes, ])orders them.Draws the segments of each variable (gid
"fractions", one bar container per variable, labelled with it), with a legend of the variables.- Parameters:
data – The fractions, as for
plot_variance_fractions().genes – The genes: feature ids, or symbols, of a table or result; names given in
labels; or positions among the features.group – The group (cell type) of a result; it may be left out when one group was fitted.
labels – One name per feature of the data, to find and label the genes by; a table’s genes are named by their symbol, or else their id.
sort – Whether to order the variables by their median, the residuals last.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or
genesorlabelsis or holds a numpy masked array.ValueError – As
plot_variance_fractions(), or ifgenesis empty or names a gene twice, a symbol names several genes, a gene has no fractions, orlabelshas the wrong length.KeyError – If a gene is not among the data’s, or
groupwas not analysed or not fitted.IndexError – If a position is out of range.
Explained in: Mixed models, REML and dream
- cytepool.plotting.plot_md(result, *, coefficient=None, alpha=0.05, ax=None)#
Plot log fold changes against average expression, the significant genes highlighted.
limma’s mean-difference plot of a fit,
plotMD(an MA plot), with the genes whose adjusted p-value is belowalphacoloured by direction, asplotMD(fit, status = decideTests(fit))colours them. The average expression is the average log2 counts per million of a table ofDifferentialExpressionResultor of aQuasiLikelihoodTest, the average log-expression of a fit, or, forDESeq2Results, the mean of the normalized counts on a logarithmic axis, as DESeq2’splotMA. The adjusted p-values of a fit are Benjamini and Hochberg’s over its genes, astopTablegives them; those of a quasi-likelihood test of several contrasts are of the test of all of them, whichever contrast’s log fold changes are drawn.Draws the genes up (gid
"up"), down (gid"down") and not significant (gid"not significant"), with a line at zero.- Parameters:
result – A table of a differential-expression result (with the columns
log2_fold_change,average_log2_cpmandadjusted_p_value), a ModeratedFit, a TreatFit, a QuasiLikelihoodTest or DESeq2Results.coefficient – The coefficient or contrast of a fit or test of several, by name or position.
alpha – The adjusted p-value below which genes are highlighted, in (0, 1).
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
resultor an option has the wrong type.ValueError – If a table lacks a column,
coefficientis needed and not given or given for a single test, oralphais not in (0, 1).KeyError, IndexError – If
coefficientnames or points to no coefficient.
- cytepool.plotting.plot_mds(data, *, group=None, color_by=None, marker_by=None, labels=False, top=_MDS_TOP, gene_selection='pairwise', dimensions=(1, 2), min_cells=None, ax=None)#
Plot samples so that their distances are typical log2 fold changes between them.
limma’s
plotMDS(Ritchie et al. 2015). The distance between two samples is their leading log2 fold change: the root mean square of thetoplargest absolute log2 fold changes between them, each pair over its own genes (gene_selection="pairwise"). With"common", or whentopis at least the number of genes, it is the root mean square over thetopgenes with the largest variance over the samples, which makes the plot a principal component plot. The samples are placed by classical multidimensional scaling (Gower 1966): the coordinates of a dimension are an eigenvector of the doubly centred matrix of squared distances, -1/2 J D J, times the square root of its eigenvalue, and the axis labels give each eigenvalue’s share of their sum, limma’svar.explained. A dimension’s sign is arbitrary; here its largest coordinate is positive.A cube gives the pseudobulk samples of one group, prepared as the edgeR User’s Guide prepares counts for
plotMDS: samples with fewer thanmin_cellscells or no counts are left out, aslimma_voom()leaves them out; genes are kept byfilter_by_expression()with the samples as one group; and the log2 counts per million are those that edgeR’splotMDStakes of counts, with TMM normalization factors and an average count of 2 added (log_cpm()).Draws the samples as points (gid
"samples"), coloured bycolor_byand marked bymarker_by, with a legend of their levels, and labels the samples (gid"sample labels") when asked.- Parameters:
data – A
Cube; aVoomResult, whose log2 counts per million are used; or(n_samples, n_genes)log-expression values, finite.group – The group (cell type) of a cube to plot; it may be left out when the cube has one group. Only cubes take it.
color_by – The variable whose levels colour the points: a column of the cube’s sample table, or one label per sample (of the cube, for a cube). With more than three levels and no
marker_by, each level also gets a marker.marker_by – The variable whose levels mark the points, as
color_by; at most 12 levels.labels – True to write each sample’s id next to it (numbers from 1 for data other than a cube), or one label per sample.
top – The number of genes behind each distance, at least 1.
gene_selection –
"pairwise"or"common".dimensions – The two dimensions to plot, counted from 1 in decreasing order of their eigenvalues.
min_cells – The fewest cells a sample needs in the group to be plotted, 10 by default as for
limma_voom; for a cube that records cell numbers.ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or is or holds a numpy masked array.
ValueError – If the values are not finite or not 2-D, too few samples remain for the dimensions, the group of a cube of several groups is not given,
groupormin_cellsis given for data other than a cube, no gene passes the filter, a sample variable has the wrong length, a missing label or too many levels, or an option is out of range.KeyError – If the group, or a variable named, is not in the cube.
- cytepool.plotting.plot_mean_variance(result, *, ax=None)#
Plot voom’s mean-variance trend.
voom’s plot (Law et al. 2014), as limma’s
voom(plot = TRUE)draws it: the square root of every gene’s residual standard deviation against its average log2 count (VoomResult.sqrt_sdagainstmean_log_count), with the LOWESS trend from which the precision weights are read (sqrt_sd_trend). Genes left out of the trend, such as those without counts, are not drawn.Draws the genes (gid
"points") and the trend (gid"trend").- Parameters:
result – The result of
voom()orvoom_with_quality_weights().ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
resultis not a VoomResult.ValueError – If no trend was fitted, because the design leaves no residual degrees of freedom.
- cytepool.plotting.plot_over_representation(table, *, top=20, alpha=0.05, ax=None)#
Plot the most over-represented gene sets, a dot for each list of genes.
For the
topsets with the smallest p-value in any list of a table ofover_representation(), most significant at the top, a dot in the column of each list of selected genes (up, down and either, or the genes given), as clusterProfiler draws the lists of genes it compares (Yu et al. 2012). The area of a dot is proportional to the overlap, the number of the set’s genes among the selected genes, and its colour gives the adjusted p-value as -log10, darker for smaller; a dot whose adjusted p-value is not belowalphais pale grey, and a list that holds none of the set’s genes has no dot. Each set is named with its number of genes in the universe, and each list with its number of selected genes.Draws the dots (gid
"gene sets").- Parameters:
table – The table of
over_representation, with the columnsgene_set,direction,n_genes,overlap,p_value,adjusted_p_valueandn_selected.top – How many sets to show, at least 1.
alpha – The adjusted p-value below which dots are coloured, in (0, 1).
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
tableis not a Table or an option has the wrong type.ValueError – If the table lacks a column or has no set with a p-value.
Explained in: Gene-set tests
- cytepool.plotting.plot_p_values(result, *, coefficient=None, bins=20, ax=None)#
Plot a histogram of p-values, with the count expected without effects.
Without differential expression, p-values are uniform on [0, 1], so every bin holds about as many tests as the dashed line: a peak at small p-values shows tests with effects, and a histogram that rises towards 1, or a peak that holds most tests, shows that the model does not fit the data, as when cells are tested as if they were independent replicates.
Draws the bars (gid
"p-values") and the expected count (gid"uniform").- Parameters:
result – The p-values of a table (its
p_valuecolumn), a fit or a test, as forplot_md(), or the p-values themselves, in [0, 1]; NaN marks a missing one, which is left out.coefficient – The coefficient or contrast of a fit or test of several, by name or position.
bins – The number of bins of equal width over [0, 1], at least 1.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or the p-values are a numpy masked array.
ValueError – If there is no p-value, one lies outside [0, 1], or a table has no
p_valuecolumn.
- cytepool.plotting.plot_proportions(result, *, by, contrast=None, ax=None)#
Plot the proportion of every cell type in every sample, by condition, with the adjusted p-values of propeller.
The figure of a
propeller()result (Phipson et al. 2022): for every group (cell type) tested, the proportion of its cells in each sample used, as a point, side by side for the levels ofby, with a bar at the mean proportion of each level (speckle’sPropMean); above each group, the adjusted p-value (speckle’sFDR) of the F-test, or of a contrast.Draws the points of each level (gid
"proportions"), the means (gid"means") and the adjusted p-values (gid"adjusted p-values"), with a legend of the levels.- Parameters:
result – The result of
propeller.by – A variable of the result’s design, such as the condition, or one label per sample of the result’s sample table.
contrast – The contrast whose adjusted p-values are shown. By default, the F-test’s when the result has one, else those of its only contrast.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
resultis not a CompositionResult, orbyorcontrasthas the wrong type or is a numpy masked array.ValueError – If
byhas the wrong length, a missing label or more than eight levels, or no contrast is named and the result has several and no F-test.KeyError – If
bynames no variable of the design, orcontrastwas not tested.
- cytepool.plotting.plot_quasi_dispersions(fit, *, ax=None)#
Plot edgeR’s quasi-dispersions before and after moderation, with their prior.
edgeR’s
plotQLDisp(Chen et al. 2016) for the quasi-likelihood model of Lund et al. (2012): the quarter-root of every gene’s quasi-dispersion (the adjusted residual deviance over its degrees of freedom), of its moderated value, and of the prior, a trend in the average log2 counts per million or a line, against the abundance the trend was fitted to (covariate), or without a trend the average log2 counts per million.Draws the quasi-dispersions (gid
"raw"), the moderated ones (gid"squeezed") and the prior (gid"prior").- Parameters:
fit – The result of
fit_quasi_likelihood(), or a test of it.ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
fitis neither a QuasiLikelihoodFit nor a QuasiLikelihoodTest.ValueError – If no gene has a quasi-dispersion.
- cytepool.plotting.plot_residual_variances(fit, *, ax=None)#
Plot the residual standard deviations of the genes and the prior they were moderated towards.
limma’s
plotSA: the square root of every gene’s residual standard deviation against its average log-expression, with the square root of the prior standard deviation (Smyth 2004), a line at its value or, with a trend, a curve. After robust moderation (Phipson et al. 2016), the variances that are outliers are marked: those whose two-sided p-value as a variance of the prior, from the F distribution on the gene’s residual and the prior’s degrees of freedom (those of the genes that are not outliers), is below 0.5 once adjusted by Benjamini and Hochberg (1995), as limma marks them (found by probing).Draws the genes (gid
"points"), the outliers (gid"outliers") and the prior (gid"prior").- Parameters:
fit – The result of
moderated_statistics()ortreat().ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
fitis neither a ModeratedFit nor a TreatFit.ValueError – If no gene has a residual standard deviation.
- cytepool.plotting.plot_sample_weights(weights, *, group=None, labels=None, ax=None)#
Plot the weight of every sample, with a line at the weight of equal samples.
The sample-weight panel of limma’s
voomWithQualityWeights(plot = TRUE)(Liu et al. 2015): a bar per sample, and a dashed line at 1. Samples below the line follow the linear model less closely, and count for less in the fits.Draws the bars (gid
"weights") and the line (gid"equal weight").- Parameters:
weights – The
sample_weightsof aVoomResultfromvoom_with_quality_weights(); the quality weights, or prior weights, of the samples used in one group of aDifferentialExpressionResult; or the weights, positive and finite, such as those ofsample_quality_weights().group – The group of a differential-expression result to plot; it may be left out when the result has one group.
labels – One label per sample shown; by default the sample ids of a differential-expression result, and numbers from 1 otherwise.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or is or holds a numpy masked array.
ValueError – If the result holds no sample weights, the group of a result of several groups is not given, the group was not fitted, the weights are not positive and finite, or
labelshas the wrong length.KeyError – If the group was not analysed.
- cytepool.plotting.plot_significant_genes(result, *, contrast=None, alpha=0.05, across_groups=False, ax=None)#
Plot how many genes go up and down in every group of a differential-expression result.
For every group (cell type) of a
DifferentialExpressionResult, in its order from the top, the genes whose adjusted p-value forcontrastis belowalpha: a bar to the right for those up and to the left for those down, each labelled with its number. A group that was not fitted, or cannot estimate the contrast, has no bars, and its label says so.across_groupscounts by the p-values adjusted over every group (adjusted_p_value_across_groups, whichlimma_voom()adds withadjust_across_groups=True) instead of within each group.Draws the bars of genes up (gid
"up") and down (gid"down"), and their numbers (gid"numbers").- Parameters:
result – The result of
limma_voom,limma_trendordream_voom.contrast – The contrast; it may be left out when the result tests one.
alpha – The adjusted p-value below which genes count, in (0, 1).
across_groups – Whether to count by the p-values adjusted across groups.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
resultis not a DifferentialExpressionResult or an option has the wrong type.ValueError – If no contrast is named and the result tests several,
alphais not in (0, 1), or the p-values adjusted across groups are asked for and the result has none.KeyError – If the contrast was not tested.
- cytepool.plotting.plot_variance_fractions(data, *, group=None, sort=True, ax=None)#
Plot the fraction of variance each variable explains over the genes, as violins.
variancePartition’s
plotVarPart(Hoffman and Schadt 2016): for each variable of a variance partition, and the residuals, the distribution over the genes of the percentage of variance it explains, as a violin (Hintze and Nelson 1998) around a narrow box plot. A violin is a Gaussian kernel density of the percentages, with Silverman’s (1986) rule-of-thumb bandwidth (R’sbw.nrd0: 0.9 min(sd, IQR / 1.34) n^(-1/5), the standard deviation alone where the quartiles coincide), drawn from the smallest to the largest percentage; every violin has the same largest width, asplotVarPartscales them. The box spans the quartiles, with the median, whiskers to the furthest percentages within 1.5 interquartile ranges of the box, and the percentages beyond them as points. Withsort, the variables are in decreasing order of their median, the residuals last, asplotVarPart(sortCols(...))orders them. Genes without fractions (NaN) are left out.Draws the violins (gid
"violins", labelled with their variable; none for a variable whose percentages are all equal), the boxes (gid"boxes"), the medians (gid"medians"), the whiskers (gid"whiskers", the lower one of a variable first) and the outlying percentages (gid"outliers", one collection per variable).- Parameters:
data – The fractions: a
VarianceFractions, aVariancePartitioningResult(withgroup), or a table of one.group – The group (cell type) of a result; it may be left out when one group was fitted.
sort – Whether to order the variables by their median, the residuals last; False keeps the order of the design.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If
dataor an option has the wrong type.ValueError – If no gene has fractions, there are more than eight variables besides the residuals, a table has no
residualscolumn, orgroupis needed and not given, or given for data of one group.KeyError – If
groupwas not analysed or not fitted.
Explained in: Mixed models, REML and dream
- cytepool.plotting.plot_volcano(result, *, coefficient=None, alpha=0.05, top=10, labels=None, ax=None)#
Plot -log10 p-values against log fold changes, labelling the top genes.
limma’s
volcanoplot, with the genes whose adjusted p-value is belowalphacoloured by direction, as inplot_md(), and thetopgenes with the smallest p-values labelled: by their symbol, or else their id, in a table, or bylabels. A p-value of 0 is drawn at the smallest positive p-value.Draws the genes up (gid
"up"), down (gid"down") and not significant (gid"not significant"), and the labels (gid"gene labels").- Parameters:
result – A table of a differential-expression or meta-analysis result (with the columns
log2_fold_change,p_valueandadjusted_p_value), a ModeratedFit, a TreatFit, a QuasiLikelihoodTest or DESeq2Results.coefficient – The coefficient or contrast of a fit or test of several, by name or position.
alpha – The adjusted p-value below which genes are highlighted, in (0, 1).
top – How many genes to label, at least 0.
labels – One name per gene; needed to label the genes of fits and tests, which hold no names.
ax – The Axes to draw into, or None for a new figure.
- Returns:
The Axes.
- Raises:
TypeError – If an argument has the wrong type, or
labelsis or holds a numpy masked array.ValueError – As
plot_md(), or iflabelshas the wrong length ortopis negative.KeyError, IndexError – If
coefficientnames or points to no coefficient.