Plotting#

mantra’s utilities to plot metabolic graphs using matplotlib

Functions#

pymantra.plotting.plot_correlation_averages(corrs: Dict[str, DataFrame], pvals: Dict[str, DataFrame], ref_group: str, tgt_group: str, set_zero: bool = True, thresh: float = 0.05, cluster: bool = False, ax: axis | None = None, reorder: bool = False, strip_column_names: bool = False, return_averages: bool = False, remove_all_zeros: bool = False, **kwargs) ClusterGrid | axis | Tuple[DataFrame, ClusterGrid | axis][source]#

Plot the average multi-omics correlation over multiple sample groups

Parameters:
  • corrs (Dict[str, pd.DataFrame]) – Group-wise correlations as returned by pymantra.compute_multiomics_associations

  • pvals (Dict[str, pd.DataFrame]) – Group-wise correlation p-values as returned by pymantra.compute_multiomics_associations

  • ref_group (str) – Name of the reference group.

  • tgt_group (str) – Name of the target group. The correlation values of this group will be subtracted from the correlations of ref_group

  • set_zero (bool, False) – Whether to set correlations with a p-value > some threshold (see thresh) to zero

  • thresh (float, .05) – p-value cutoff above which all correlations will be set to zero. Only relevant if set_zero is True

  • cluster (bool, False) – Whether to cluster features

  • ax (plt.axis, optional) – Axis to plot onto. Only used if cluster if False

  • reorder (bool, False) – Whether to reorder columns and rows by clustering. This essentially means plotting a clustermap but leaving away the clustering trees and only reordering. Only relevant if cluster is False.

  • strip_column_names (bool, False) – Whether to strip the column names (i.e. reaction labels) to only retain the first reaction annotation

  • return_averages (bool, False) – Whether to return the correlation difference data frame

  • remove_all_zeros (bool, False) – Whether to remove features with no significant associations. Only used if pvals is given.

  • kwargs – Keyword arguments to parse to seaborn.heatmap (cluster is False) or seaborn.clustermap

Returns:

Tuple[pd.DataFrame, Union[sns.matrix.ClusterGrid, plt.axis]]] A seaborn ClusterGrid object, if cluster is True, a matplotlib axis otherwise

Return type:

Union[Union[sns.matrix.ClusterGrid, plt.axis],

Examples

>>> from pymantra.datasets import example_multiomics_enrichment_data
>>> from pymantra import (
...     compute_reaction_estimates, compute_multiomics_associations)
>>> metabolite_data, microbiome_data, sample_groups, graph =     ...     example_multiomics_enrichment_data()
>>> residuals =     ...     compute_reaction_estimates(graph, metabolite_data, sample_groups)
>>> corrs, pvals = compute_multiomics_associations(
...     residuals, microbiome_data, sample_groups, comparison=("0", "1"))
>>> diff_associations, clust_map = plot_correlation_averages(
...     corrs, pvals, "0", "1", cluster=True)
pymantra.plotting.plot_correlation_differences(corrs: Dict[str, DataFrame], pvals: Dict[str, DataFrame], ref_group: str, tgt_group: str, set_zero: bool = True, thresh: float = 0.05, cluster: bool = False, ax: axis | None = None, reorder: bool = False, strip_column_names: bool = False, return_differences: bool = False, remove_all_zeros: bool = False, **kwargs) ClusterGrid | axis | Tuple[DataFrame, ClusterGrid | axis][source]#

Plot the multi-omics correlation differences between two sample groups

Parameters:
  • corrs (Dict[str, pd.DataFrame]) – Group-wise correlations as returned by pymantra.compute_multiomics_associations

  • pvals (Dict[str, pd.DataFrame]) – Group-wise correlation p-values as returned by pymantra.compute_multiomics_associations

  • ref_group (str) – Name of the reference group.

  • tgt_group (str) – Name of the target group. The correlation values of this group will be subtracted from the correlations of ref_group

  • set_zero (bool, False) – Whether to set correlations with a p-value > some threshold (see thresh) to zero

  • thresh (float, .05) – p-value cutoff above which all correlations will be set to zero. Only relevant if set_zero is True

  • cluster (bool, False) – Whether to cluster features

  • ax (plt.axis, optional) – Axis to plot onto. Only used if cluster if False

  • reorder (bool, False) – Whether to reorder columns and rows by clustering. Only relevant if cluster is False,

  • strip_column_names (bool, False) – Whether to strip the column names (i.e. reaction labels) to only retain the first reaction annotation

  • return_differences (bool, False) – Whether to return the correlation difference data frame

  • remove_all_zeros (bool, False) – Whether to remove features with no significant associations. Only used if pvals is given.

  • kwargs – Keyword arguments to parse to seaborn.heatmap (cluster is False) or seaborn.clustermap

Returns:

Tuple[pd.DataFrame, Union[sns.matrix.ClusterGrid, plt.axis]]] A seaborn ClusterGrid object, if cluster is True, a matplotlib axis otherwise

Return type:

Union[Union[sns.matrix.ClusterGrid, plt.axis],

Examples

>>> from pymantra.datasets import example_multiomics_enrichment_data
>>> from pymantra import (
...     compute_reaction_estimates, compute_multiomics_associations)
>>> metabolite_data, microbiome_data, sample_groups, graph =     ...     example_multiomics_enrichment_data()
>>> residuals =     ...     compute_reaction_estimates(graph, metabolite_data, sample_groups)
>>> corrs, pvals = compute_multiomics_associations(
...     residuals, microbiome_data, sample_groups, comparison=("0", "1"))
>>> diff_associations, clust_map = plot_correlation_differences(
...     corrs, pvals, "0", "1", cluster=True, return_differences=True)
pymantra.plotting.plot_directed_graph(graph: ~networkx.classes.digraph.DiGraph, layout: callable = <function kamada_kawai_layout>, reaction_graph: bool = True, formula_as_reaction_label: bool = False, ax: ~matplotlib.pyplot.axis | None = None, **label_args) axis[source]#

Plotting a directed network obtained from the database

Parameters:
  • graph (nx.DiGraph) – networkx DiGraph object, that has to contain node and edge type for each element labelled as <node/edge>_type

  • layout (callable, default nx.kamada_kawai_layout) – Function to compute node positions for a nx.DiGraph, that has to be compatible with networkx draw_* functions . Default is nx.kamada_kawai_layout(). If you want to use any of the networkx functions with particular parameter settings please use lambda functions to set the parameters.

  • reaction_graph (bool, default True) – Whether the graph enter contains reaction nodes or not. This should be equivalent to whether the input graph was generated with NetworkGenerator.get_reaction_subgraph() or NetworkGenerator.get_subgraph().

  • formula_as_reaction_label (bool, False) – If True reaction formulas will be used as node labels, otherwise the reaction description as provided in the source database.

  • ax (plt.axis, Optional) – Axis to plot the network onto.

  • label_args – Keyword arguments for networkx.draw_networkx_labels

Examples

>>> from pymantra import datasets
>>> mantra_graph = datasets.example_graph()
>>> plot_directed_graph(mantra_graph)
Returns:

Axis containing the network plot including legend

Return type:

plt.axis

pymantra.plotting.plot_reaction_association(residuals: DataFrame, omics_data: DataFrame, corrs: DataFrame, groups: Series | None = None, top_n: int = 3, axes: List[axis] | None = None, pal: Dict[str, str] | None = None)[source]#

Plot the highest correlating associations between reactions and non-metabolomic omics-data

Parameters:
  • residuals (pd.DataFrame) – Residual values as computed by pymantra.compute_reaction_estimates

  • omics_data (pd.DataFrame) – Multi-omics data associated with residuals. Rows must be features (e.g. microbial species or transcript abundances) and columns samples.

  • corrs (pd.DataFrame) – Correlations between omics-data (rows) and reaction residuals (columns)

  • groups (pd.Series) – Sample groups, index must be the same as the indices in residuals_

  • top_n (int, 3) – Number of associations to plot. If axes is given, len(axes) will be used instead.

  • axes (List[plt.axis], optional) – (Flat) List of axes to plot onto. If None, top_n axes will be created inside the function. If you want to have a multi-row layout, we recommend using plt.subplots with the ncols/nrows parameters and then passing the axes with axes.flatten().

  • pal (Dict[str, str], optional) – Colour palette to use. Only use if groups is given. The keys must be the group names that appear in groups and the values must be strings defining colors in a matplotlib-compatible format.

Returns:

List of axes containing the association plots

Return type:

List[plt.axis]

Examples

>>> from pymantra.datasets import example_multiomics_enrichment_data
>>> from pymantra import (
...     compute_reaction_estimates, compute_multiomics_associations)
>>> metabolite_data, microbiome_data, sample_groups, graph =     ...     example_multiomics_enrichment_data()
>>> residuals =     ...     compute_reaction_estimates(graph, metabolite_data, sample_groups)
>>> corrs, pvals = compute_multiomics_associations(
...     residuals, microbiome_data, sample_groups, comparison=("0", "1"))
>>> diff_associations, clust_map = plot_correlation_differences(
...     corrs, pvals, "0", "1", cluster=True, return_differences=True)
>>> plot_reaction_association(
...     residuals, microbiome_data, corr_associations, sample_groups)
pymantra.plotting.plot_undirected_graph(graph: ~networkx.classes.graph.Graph, layout: callable = <function kamada_kawai_layout>, reaction_graph: bool = False, formula_as_reaction_label: bool = False, ax: ~matplotlib.pyplot.axis | None = None, **label_args) axis[source]#

Plotting an undirected network obtained from the database

Parameters:
  • graph (nx.Graph) – networkx Graph object, that has to contain node and edge type for each element labelled as node-/edge-type

  • layout (callable, default nx.kamada_kawai_layout) – Function to compute node positions for a nx.DiGraph, that has to be compatible with networkx draw_* functions . Default is nx.kamada_kawai_layout(). If you want to use any of the networkx functions with particular parameter settings pleas use lambda functions to set the parameters.

  • reaction_graph (bool, default False) – Whether the graph enter contains reaction nodes or not. This should be equivalent to whether the input graph was generated with NetworkGenerator.get_reaction_subgraph() or NetworkGenerator.get_subgraph(). Generally, It is recommended to use plot_directed_graph() when plotting a reaction graph.

  • formula_as_reaction_label (bool, False) – If True reaction formulas will be used as node labels, otherwise the reaction description as provided in the source database.

  • ax (plt.axis, Optional) – Axis to plot the network onto.

  • label_args – Keyword arguments for networkx.draw_networkx_labels

Examples

>>> from pymantra import datasets
>>> mantra_graph = datasets.example_graph()
>>> plot_undirected_graph(mantra_graph)
Returns:

Axis containing the network plot including legend

Return type:

plt.axis

pymantra.plotting.residual_violinplot(residuals_: DataFrame, groups: Series, pvalues: Series | None = None, ax: axis | None = None, fontsize: int = 12, significance_only: bool = True, legend_position: Tuple[str, Tuple[float, float]] | None = None, drop_legend: bool = False, rotate_labels: bool = False, plot_significant_features: bool = False, thresh: float = 0.05, **kwargs) axis[source]#

Plot the residual values per group as a violinplot

Parameters:
  • residuals (pd.DataFrame) – Residual values as computed by pymantra.compute_reaction_estimates

  • groups (pd.Series) – Sample groups, index must be the same as the indices in residuals_

  • pvalues (pd.Series, optional) – p-values to be added to the plot

  • ax (plt.axis, optional) – Axis to plot onto. If None, a new figure will be initialised inside the function

  • fontsize (int, 7) – Font size for p-value annotations

  • significance_only (bool, True) – If True and pvalues is not None, the p-values will be shown as asterisks or ‘ns’ indicating different levels of significance. If False rounded p-values are displayed. If pvalues is None, this has no effect.

  • legend_position (Tuple[str, Tuple[float, float]], optional) – Where to position the legend. First element is a string compatible with the typical matplotlib legend location names, the second is a 2-tuple giving the x- and y-axis offset (via bbox_to_anchor)

  • drop_legend (bool, False) – If set to True legend drawing will be suppressed

  • rotate_labels (bool, False) – Whether to rotate the x-axis ticklabels by 90 degrees or not

  • plot_significant_features (bool, False) – Whether to show only significant features. Significance is defined via the thresh parameter. Can only be used if pvalues is given.

  • thresh (float, .05) – p-value threshold used to subset if plot_significant_features is True

  • kwargs – Optional keyword arguments to seaborn.violinplot

Returns:

Matplotlib axis used for plotting

Return type:

plt.axis

Examples

>>> from pymantra.datasets import example_multiomics_enrichment_data
>>> from pymantra import (
...     compute_reaction_estimates, compute_multiomics_associations)
>>> metabolite_data, microbiome_data, sample_groups, graph =     ...     example_multiomics_enrichment_data()
>>> residuals =     ...     compute_reaction_estimates(graph, metabolite_data, sample_groups)
>>> residual_violinplot(residuals, sample_groups)