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:

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 of span of the genes (limma’s tricubeMovingAverage, 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 t column (or statistic, for a meta-analysis) ranks its genes, named by its feature_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’s ids2indices leaves them.

  • gene_ids – One id per gene, unique, to name the genes of gene_set by id when statistics is 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 span is 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 than min_cells cells, which limma_voom() leaves out of a group’s fit with the same min_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 cube is not a Cube or an option has the wrong type.

  • ValueError – If the cube does not record cell numbers, or min_cells is 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 proportions n_cells over each sample’s cells in all groups, without the samples that have no cells; a CompositionResult gives those that propeller() tested, of its samples used and groups tested. by groups 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 data is neither a Cube nor a CompositionResult, or by is 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 with Cube.select, first), or by has the wrong length or a missing label.

  • KeyError – If by names 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:
Returns:

The Axes.

Raises:
  • TypeError – If dispersions is 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 forest draws for a model without moderators (Viechtbauer 2010), of one gene of a differential_expression_meta_analysis(): a row per study, in the order of studies, 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 studies is 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 top sets with the smallest p-values of a table of camera() (Wu and Smyth 2012), fry() or mroast(), 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 at alpha. 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_value and adjusted_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 table is 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 of plot_variance_fractions(): with sort, in decreasing order of their median over every gene of the data, as plotPercentBars(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 genes or labels is or holds a numpy masked array.

  • ValueError – As plot_variance_fractions(), or if genes is empty or names a gene twice, a symbol names several genes, a gene has no fractions, or labels has the wrong length.

  • KeyError – If a gene is not among the data’s, or group was 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 below alpha coloured by direction, as plotMD(fit, status = decideTests(fit)) colours them. The average expression is the average log2 counts per million of a table of DifferentialExpressionResult or of a QuasiLikelihoodTest, the average log-expression of a fit, or, for DESeq2Results, the mean of the normalized counts on a logarithmic axis, as DESeq2’s plotMA. The adjusted p-values of a fit are Benjamini and Hochberg’s over its genes, as topTable gives 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_cpm and adjusted_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 result or an option has the wrong type.

  • ValueError – If a table lacks a column, coefficient is needed and not given or given for a single test, or alpha is not in (0, 1).

  • KeyError, IndexError – If coefficient names 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 the top largest absolute log2 fold changes between them, each pair over its own genes (gene_selection="pairwise"). With "common", or when top is at least the number of genes, it is the root mean square over the top genes 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’s var.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 than min_cells cells or no counts are left out, as limma_voom() leaves them out; genes are kept by filter_by_expression() with the samples as one group; and the log2 counts per million are those that edgeR’s plotMDS takes of counts, with TMM normalization factors and an average count of 2 added (log_cpm()).

Draws the samples as points (gid "samples"), coloured by color_by and marked by marker_by, with a legend of their levels, and labels the samples (gid "sample labels") when asked.

Parameters:
  • data – A Cube; a VoomResult, 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, group or min_cells is 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_sd against mean_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:
Returns:

The Axes.

Raises:
  • TypeError – If result is 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 top sets with the smallest p-value in any list of a table of over_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 below alpha is 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 columns gene_set, direction, n_genes, overlap, p_value, adjusted_p_value and n_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 table is 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_value column), a fit or a test, as for plot_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_value column.

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 of by, with a bar at the mean proportion of each level (speckle’s PropMean); above each group, the adjusted p-value (speckle’s FDR) 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 result is not a CompositionResult, or by or contrast has the wrong type or is a numpy masked array.

  • ValueError – If by has 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 by names no variable of the design, or contrast was 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 fit is 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:
Returns:

The Axes.

Raises:
  • TypeError – If fit is 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_weights of a VoomResult from voom_with_quality_weights(); the quality weights, or prior weights, of the samples used in one group of a DifferentialExpressionResult; or the weights, positive and finite, such as those of sample_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 labels has 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 for contrast is below alpha: 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_groups counts by the p-values adjusted over every group (adjusted_p_value_across_groups, which limma_voom() adds with adjust_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_trend or dream_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 result is not a DifferentialExpressionResult or an option has the wrong type.

  • ValueError – If no contrast is named and the result tests several, alpha is 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’s bw.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, as plotVarPart scales 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. With sort, the variables are in decreasing order of their median, the residuals last, as plotVarPart(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, a VariancePartitioningResult (with group), 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 data or 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 residuals column, or group is needed and not given, or given for data of one group.

  • KeyError – If group was 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 below alpha coloured by direction, as in plot_md(), and the top genes with the smallest p-values labelled: by their symbol, or else their id, in a table, or by labels. 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_value and adjusted_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 labels is or holds a numpy masked array.

  • ValueError – As plot_md(), or if labels has the wrong length or top is negative.

  • KeyError, IndexError – If coefficient names or points to no coefficient.