Plot Modules

OncoPlot

class pymaftools.plot.OncoPlot.OncoPlot(pivot_table, **kwargs)[source]

Bases: BasePlot

OncoPlot class for creating oncoplots (mutation heatmaps) with metadata annotations.

This class provides comprehensive functionality for visualizing mutation data along with sample and feature metadata, including TMB (Tumor Mutation Burden) plots, frequency plots, and categorical/numeric metadata annotations.

Inherits from BasePlot to utilize unified legend management and save functionality.

set_config(line_color='white', cmap='nonsynonymous', figsize=(20, 15), width_ratios=None, height_ratios=None, wspace=0.015, hspace=0.02, categorical_columns=None, numeric_columns=None, ytick_fontsize=10)[source]

Configure OncoPlot appearance and layout settings.

Parameters:
  • line_color (str, default "white") – Color of lines between heatmap cells

  • cmap (str or dict, default "nonsynonymous") – Color map for mutation types

  • figsize (tuple, default (20, 15)) – Figure size (width, height)

  • width_ratios (list, default [25, 1, 1, 2]) – Layout hint; only the main-matrix width (width_ratios[0]) is used by render() to size the heatmap column relative to side tracks.

  • height_ratios (list, default [1, 20]) – Layout hint; only the main-matrix height (height_ratios[-1]) is used by render().

  • wspace (float, default 0.015) – Default inter-axis width spacing for render().

  • hspace (float, default 0.02) – Default inter-axis height spacing for render().

  • categorical_columns (list, default []) – Categorical metadata columns drawn by plot_categorical_metadata().

  • numeric_columns (list, default []) – Numeric metadata columns drawn by plot_numeric_metadata().

  • ytick_fontsize (int, default 10) – Font size for y-axis tick labels

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

plot_numeric_metadata(annotate=False, annotation_font_size=10, fmt='.2f', cmap='Blues', cmap_dict=None, alpha=1, linewidths=1, colorbar='legend')[source]

Register one numeric sample-annotation track per numeric_columns.

Backward-compatible convenience over add_sample_annotation(): registers the tracks (drawn on the next render()). The columns come from numeric_columns configured in set_config().

Parameters:
  • annotate (bool, default False) – Whether to display numeric values on the heatmap

  • annotation_font_size (int, default 10) – Font size for annotations

  • fmt (str, default ".2f") – Format string for numeric annotations

  • cmap (str, default "Blues") – Default colormap for numeric data

  • cmap_dict (dict, optional) – Dictionary mapping column names to specific colormaps

  • alpha (float, default 1) – Transparency level (0-1)

  • linewidths (float, default 1) – Width of lines between cells

  • colorbar ({"legend", "inset", "off"}, default "legend") – Where to draw each column’s colorbar: "legend" stacks them in the shared legend area (best with several numeric columns), "inset" puts a small one beside each strip, "off" none. Accepts a bool (True→inset, False→off). (PLOTTING_REVIEW P1#3.)

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

static categorical_heatmap(table, category_cmap, ax=None, fig_size=(10, 6), unknown_color='white', linecolor='white', **kwargs)[source]

Backward-compatible delegate to Track.draw_categorical_heatmap().

mutation_heatmap(cmap_dict=None, linecolor='white', linewidths=1, show_frame=False, n=3, yticklabels=True, ytick_fontsize=None, show_ylabel=False, show_all_categories=False)[source]

Plot the main mutation heatmap using categorical color coding.

Legacy shorthand for the canonical main(kind="mutation"); prefer main() in new code.

Parameters:
  • cmap_dict (dict, optional) – Color mapping for mutation types

  • linecolor (str, default "white") – Color of lines between cells

  • linewidths (int, default 1) – Width of lines between cells

  • show_frame (bool, default False) – Whether to show frames around groups of columns

  • n (int, default 3) – Number of columns per frame group

  • yticklabels (bool, default True) – Whether to show y-tick labels (feature names)

  • ytick_fontsize (int, optional) – Font size for y-axis tick labels (defaults to self.ytick_fontsize)

  • show_ylabel (bool, default False) – Whether to show y-axis label

  • show_all_categories (bool, default False) – If False (default), the legend lists only mutation categories that occur in the data and are not wild-type; set True to force the full colormap (PLOTTING_REVIEW P1#4).

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

main(kind='mutation', cmap_dict=None, **kwargs)[source]

Register the main matrix track for the declarative render() path.

Parameters:
  • kind ({"mutation", "cnv"}, default "mutation") – "mutation" registers a categorical MainMatrixTrack; "cnv" (alias "numeric") registers a continuous NumericMatrixTrack for log2-ratio data.

  • cmap_dict (dict, optional) – Categorical colormap (mutation only); defaults to self.cmap.

  • **kwargs – Forwarded to the matrix track (e.g. show_frame, yticklabels for mutation; cmap, symmetric for cnv).

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining.

add_track(track)[source]

Register an arbitrary pre-built Track for render().

The escape hatch behind the curated add_* helpers: any Track subclass (e.g. a BarTrack placed on any side) can be attached here. Position and order follow (side, registration order) — the track’s side places it on top/bottom/left/right, and the order in which tracks are added sets distance from the matrix (first added = outermost). No separate ordering parameter is needed.

Return type:

OncoPlot

Examples

>>> op.add_track(BarTrack(
...     pt.sample_metadata[[f"tmb_{g}" for g in ColorManager.FUNCTIONAL_ORDER]],
...     side="top", label="TMB", cmap=ColorManager.FUNCTIONAL_CMAP))
add_bar(bar_col='TMB', side='top', **kwargs)[source]

Register a per-sample bar track (e.g. TMB) for render().

Return type:

OncoPlot

add_freq(freq_columns=None, side='right', **kwargs)[source]

Register a per-feature frequency track for render().

Parameters:
  • freq_columns (list of str, default ["freq"]) – feature_metadata columns to draw, one strip each (e.g. ["LUAD_freq", "LUSC_freq"]). Populate group-specific columns with PivotTable.add_freq() (groups= or group_col=).

  • side ({"right", "left"}, default "right") – Which side of the matrix to place the strip(s) on.

  • **kwargs – Forwarded to Track.FreqTrack (e.g. annot, linewidths, vmin/vmax — defaults pin the scale to 0–1).

Return type:

OncoPlot

Notes

For a signed per-feature numeric column (e.g. delta_freq) use add_feature_annotation() with a diverging cmap instead; add_freq is for 0–1 proportions on a shared scale.

add_sample_annotation(columns, side='bottom', *, cmap_dict=None, default_cmap='pastel', **kwargs)[source]

Register sample-aligned annotation tracks (one per column) for render(). Numeric columns become NumericTrack (with colorbar), others CategoricalTrack.

Parameters:
  • columns (list of str) – sample_metadata columns to draw, one track each.

  • side ({"bottom", "top"}, default "bottom") – Which side of the matrix to place the strips on.

  • cmap_dict (dict, optional) – Per-column colour override (numeric cmap name or categorical {category: color} mapping); see _add_annotation().

  • default_cmap (str, default "pastel") – Palette for categorical categories without an explicit colour.

  • **kwargs – Forwarded to the per-column track (NumericTrack / CategoricalTrack), e.g. annotate, linewidths, size.

Return type:

OncoPlot

See also

add_feature_annotation

same, on the feature (row) axis.

add_feature_annotation(columns, side='right', *, cmap_dict=None, default_cmap='pastel', **kwargs)[source]

Register feature-aligned annotation tracks (one per column) for render() — e.g. pathway / is_driver from feature_metadata drawn as row-side strips. This is the feature-dimension gap (S3 / P1#2) that the eager layout never had a slot for.

Parameters:
  • columns (list of str) – feature_metadata columns to draw, one track each.

  • side ({"right", "left"}, default "right") – Which side of the matrix to place the strips on.

  • cmap_dict (dict, optional) – Per-column colour override. For a numeric column the entry is a cmap name and takes precedence over a global cmap in kwargs; a "coolwarm" cmap centres a signed column (e.g. delta_freq) symmetrically around 0. For a categorical column it is a {category: color} mapping. See _add_annotation().

  • default_cmap (str, default "pastel") – Palette for categorical categories without an explicit colour.

  • **kwargs – Forwarded to the per-column track (NumericTrack / CategoricalTrack), e.g. annotate, linewidths.

Return type:

OncoPlot

Notes

Use this (not add_freq()) for signed/continuous feature columns: add_freq is for 0–1 frequency proportions on a shared 0–1 scale, while add_feature_annotation infers the scale per column (and goes symmetric for coolwarm).

Examples

>>> # diverging delta_freq strip, symmetric around 0
>>> op.add_feature_annotation(
...     ["delta_freq"], side="right",
...     cmap_dict={"delta_freq": "coolwarm"}, annotate=True,
... )
group_features(by, *, gap=0.5, show_titles=True, title_fontsize=11, title_align='start')[source]

Split rows (features) into groups from a feature_metadata column.

render() draws each group as its own section with a whitespace gap (in matrix-cell units) between them and, if show_titles, a rotated group label on the left (title_align = "start" top / "center" / "end" bottom). Features must already be contiguous by group — sort first, e.g. table.sort_features(by="pathway").

Return type:

OncoPlot

group_samples(by, *, gap=0.5, show_titles=True, title_fontsize=11, title_align='start', freq=False, freq_suffix='_freq', freq_size=1.0, freq_annot=True)[source]

Split columns (samples) into groups from a sample_metadata column.

render() draws each group as its own section with a whitespace gap (in matrix-cell units) between them and, if show_titles, a group label on top (title_align = "start" left / "center" / "end" right). Samples must already be contiguous by group — sort first, e.g. table.sort_samples_by_group(group_col="subtype", ...).

Return type:

OncoPlot

Per-section frequency

With freq=True each section gets its own frequency strip immediately to its right, reading feature_metadata[f"{label}{freq_suffix}"] (e.g. the LUAD_freq / LUSC_freq columns produced by PivotTable.add_freq(groups=...)). The strips share a 0–1 colour scale so groups are comparable. An overall frequency bar is independent — add it the usual way with .add_freq(freq_columns=["freq"]).

type freq:

bool, default: False

param freq:

Draw a per-section frequency strip right of each sample section.

type freq:

bool, default False

type freq_suffix:

str, default: '_freq'

param freq_suffix:

Suffix appended to each section label to find its frequency column.

type freq_suffix:

str, default “_freq”

type freq_size:

float, default: 1.0

param freq_size:

Width of each per-section frequency strip (matrix-cell units).

type freq_size:

float, default 1.0

type freq_annot:

bool, default: True

param freq_annot:

Annotate each strip cell with its frequency value.

type freq_annot:

bool, default True

render(fig=None, *, main_width=None, main_height=None, legend_width=3, legend_pad=1, colorbar_width=0.55, wspace=None, hspace=None, show_sample_labels=None, feature_labels=None, sample_labels=None, feature_gutter_size=None, sample_gutter_size=3.0)[source]

Derive the layout from registered tracks and draw them in one pass.

The sole draw path. Groups registered tracks by side and builds a GridSpec whose rows are [top..] + main + [bottom..] and columns are [left..] + main + [right..] + legend; sample-aligned tracks (top/ bottom) share the matrix width, feature-aligned tracks (left/right) share its height. The convenience methods (mutation_heatmap / plot_freq / plot_bar / plot_categorical_metadata / plot_numeric_metadata / numeric_heatmap) only register tracks; this method draws them.

Parameters:
  • fig (matplotlib.figure.Figure, optional) – Existing figure to draw into. If None, a new figure is created via plt.figure (the only remaining global-pyplot touch; pass fig to embed the oncoplot in a larger figure).

  • main_width (float, optional) – Relative size of the main matrix column / row. Default to width_ratios[0] / height_ratios[-1] from set_config.

  • main_height (float, optional) – Relative size of the main matrix column / row. Default to width_ratios[0] / height_ratios[-1] from set_config.

  • legend_width (float, default 3) – Relative width of the legend column.

  • legend_pad (float, default 1) – Relative width of an explicit empty spacer column inserted between the right-side tracks and the legend. Use 0 to remove the spacer.

  • colorbar_width (float, default 0.55) – Width (axes fraction) of the stacked numeric colorbars drawn in the legend area for tracks with colorbar="legend".

  • wspace (float, optional) – Inter-axis spacing; default to the configured self.wspace / self.hspace.

  • hspace (float, optional) – Inter-axis spacing; default to the configured self.wspace / self.hspace.

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining.

plot_bar(fontsize=6, bar_value=False, bar_col='TMB', ylabel_size=8)[source]

Plot bar chart showing values (typically TMB) for each sample.

Legacy shorthand for the canonical add_bar(); prefer add_bar() in new code.

Parameters:
  • fontsize (int, default 6) – Font size for bar value annotations

  • bar_value (bool, default False) – Whether to show values on top of bars

  • bar_col (str, default "TMB") – Column name in sample_metadata to use for bar values

  • ylabel_size (int, default 8) – Font size for y-axis label

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

plot_freq(freq_columns=None, annot_fontsize=8, linewidths=1, xtick_fontsize=9)[source]

Plot frequency heatmap showing mutation frequencies for each gene.

Legacy shorthand for the canonical add_freq(); prefer add_freq() in new code.

Parameters:
  • freq_columns (list, default ["freq"]) – List of frequency columns to display

  • annot_fontsize (int, default 8) – Font size for annotations

  • linewidths (float, default 1) – Width of lines between cells

  • xtick_fontsize (int, default: 9) – Font size for x-axis tick labels (defaults 9)

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

plot_categorical_metadata(annotate=False, cmap_dict=None, alpha=1.0, default_cmap='pastel', annotation_font_size=10, annotate_text_color='black', linewidths=1)[source]

Plot categorical metadata as color-coded heatmaps below the main mutation heatmap.

Parameters:
  • annotate (bool, default False) – Whether to display category labels on the heatmap

  • cmap_dict (dict, optional) –

    Dictionary mapping columns to {category: color} mappings, e.g.:

    {
        "subtype": {"LUAD": "orange", "LUSC": "blue", "ASC": "green"},
        "smoke": {"is_smoke": "gray", "no_smoke": "white"},
    }
    

  • alpha (float, default 1.0) – Transparency level (0-1)

  • default_cmap (str, default "pastel") – Default color palette for categories without specified colors

  • annotation_font_size (int, default 10) – Font size for annotations

  • annotate_text_color (str, default "black") – Color of annotation text

  • linewidths (float, default 0.1) – Width of lines between cells

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

add_xticklabel(fontsize=None, rotation=90)[source]

Legacy: restyle the auto-drawn sample-name gutter labels.

Sample names are now rendered in a dedicated bottom gutter block by render() (pass sample_labels= to override them, or show_sample_labels= to force on/off). This shim is kept for backward compatibility: it re-applies rotation / fontsize to the already-drawn gutter labels. Call it after render().

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

numeric_heatmap(cmap='Blues', vmin=None, vmax=None, symmetric=False, yticklabels=True, annot=False, fmt='.2f', ytick_fontsize=None, linewidths=1, show_ylabel=False)[source]

Plot numeric heatmap with customizable y-axis tick label font size.

Legacy shorthand for the canonical main(kind="cnv"); prefer main(kind="cnv") in new code.

Parameters:
  • cmap (str, default "Blues") – Colormap for the heatmap

  • vmin (float, optional) – Minimum value for color scale

  • vmax (float, optional) – Maximum value for color scale

  • symmetric (bool, default False) – Whether to use symmetric color scale

  • yticklabels (bool, default True) – Whether to show y-axis labels (gene names)

  • annot (bool, default False) – Whether to annotate cells with values

  • fmt (str, default ".2f") – Format string for annotations

  • ytick_fontsize (int, optional) – Font size for y-axis tick labels (defaults to self.ytick_fontsize)

  • linewidths (int, default 1) – Width of lines between cells

  • show_ylabel (bool, default False)

Return type:

OncoPlot

Returns:

self (OncoPlot) – Returns self for method chaining

static default_oncoplot(pivot_table, figsize=(30, 15))[source]

Create a default oncoplot with standard components.

Convenience constructor that registers the main mutation heatmap, the frequency column and the TMB bar, then renders.

Parameters:
  • pivot_table (PivotTable) – The PivotTable instance containing mutation data

  • figsize (tuple, default (30, 15)) – Figure size (width, height)

Return type:

OncoPlot

Returns:

oncoplot (OncoPlot) – Configured and rendered OncoPlot instance

Track

Track abstractions for declarative OncoPlot composition.

A Track owns a strip of the oncoplot aligned to one axis of the main matrix. Each track knows how to draw itself onto a matplotlib Axes (render()) and what it contributes to the shared legend (legend_entries()).

See PLOTTING_REVIEW.md (“目標架構”) for the full design. Stage 1 introduces only the abstract Track and the MainMatrixTrack; the sample/feature annotation tracks come in later stages.

pymaftools.plot.Track.draw_categorical_heatmap(table, category_cmap, ax=None, fig_size=(10, 6), unknown_color='white', linecolor='white', **kwargs)[source]

Draw a categorical heatmap and return (fig, ax, legend_info).

Implementation shared by MainMatrixTrack and (from Stage 2) the annotation tracks. Moved verbatim from OncoPlot.categorical_heatmap, which now delegates here so external callers keep working.

class pymaftools.plot.Track.Track[source]

Bases: ABC

Abstract strip of an oncoplot aligned to one axis of the main matrix.

side: str = 'main'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

size: float = 1.0

Relative thickness of the track’s slot in the derived layout.

Type:

float

abstractmethod render(ax)[source]

Draw this track onto ax.

Return type:

Axes

legend_entries()[source]

Return {legend_name: {category: color}} contributed to the shared legend, or None if this track has no legend.

Return type:

dict[str, dict] | None

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

Track

class pymaftools.plot.Track.MainMatrixTrack(table, cmap_dict, *, linecolor='white', linewidths=1, show_frame=False, n=3, yticklabels=True, ytick_fontsize=10, show_ylabel=False, show_all_categories=False)[source]

Bases: Track

Main mutation heatmap (categorical variant matrix).

Owns every drawing parameter that OncoPlot.mutation_heatmap used to apply inline, so that method can stay a thin wrapper around this track.

side: str = 'main'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

render(ax)[source]

Draw this track onto ax.

Return type:

Axes

legend_entries()[source]

Return {legend_name: {category: color}} contributed to the shared legend, or None if this track has no legend.

Return type:

dict[str, dict]

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

MainMatrixTrack

class pymaftools.plot.Track.NumericMatrixTrack(table, *, cmap='Blues', vmin=None, vmax=None, symmetric=False, yticklabels=True, annot=False, fmt='.2f', ytick_fontsize=10, linewidths=1, show_ylabel=False, cbar=True)[source]

Bases: Track

Continuous main matrix (e.g. CNV log2 ratios).

Drawn as a heatmap with a colorbar instead of categorical swatches. The colorbar is its legend, so legend_entries is None. render draws a compact inset colorbar (the declarative path); the legacy freq-column colorbar lives in draw_colorbar() for the eager numeric_heatmap.

side: str = 'main'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

render(ax)[source]

Draw this track onto ax.

Return type:

Axes

draw_colorbar(cax)[source]

Legacy freq-column colorbar (used by the eager numeric_heatmap so its output stays byte-identical). Must be called after render().

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

NumericMatrixTrack

class pymaftools.plot.Track.BarTrack(data, label=None, *, side='top', cmap=None, color='gray', grow='out', bar_value=False, fontsize=6, ylabel_size=8, size=1.0)[source]

Bases: Track

Bar strip aligned to one matrix axis; single-series or stacked.

side in ("top", "bottom") is sample-aligned and draws vertical bars (ax.bar); ("left", "right") is feature-aligned and draws horizontal bars (ax.barh). grow controls direction: "out" (default) grows away from the matrix, "in" toward it.

data is normalized to an internal frame whose rows are axis positions (samples or features, in matrix order) and whose columns are stack categories (column order = stack / legend order):

  • a 1-D input (Series / ndarray) becomes a single-column frame — a single series drawn in color with no legend;

  • a DataFrame stacks its columns, coloured by cmap (which also drives the legend), e.g. sample_metadata[["tmb_Truncating", ...]].

side: str = 'top'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

property values: ndarray

the per-position stacked total.

Type:

Backward-compatible 1-D view

render(ax)[source]

Draw this track onto ax.

Return type:

Axes

legend_entries()[source]

Return {legend_name: {category: color}} contributed to the shared legend, or None if this track has no legend.

Return type:

dict[str, dict] | None

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

BarTrack

class pymaftools.plot.Track.FreqTrack(freq_data, *, line_color='white', annot=True, annot_fontsize=8, linewidths=1, xtick_fontsize=9, vmin=0.0, vmax=1.0)[source]

Bases: Track

Per-feature frequency annotation column drawn right of the matrix.

side: str = 'right'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

render(ax)[source]

Draw this track onto ax.

Return type:

Axes

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

FreqTrack

class pymaftools.plot.Track.CategoricalTrack(data, column_cmap, name, *, side='bottom', line_color='white', linewidths=1, alpha=1.0, annotate=False, annotation_font_size=10, annotate_text_color='black', ytick_fontsize=10, size=1.0)[source]

Bases: Track

Single categorical annotation strip.

Bound to either axis of the main matrix via side (S3 — feature and sample annotations are the same kind of track):

  • side in ("top", "bottom") → sample-aligned, horizontal strip; data is 1xN (the metadata field as a row), its name labels the y-axis.

  • side in ("left", "right") → feature-aligned, vertical strip; data is Nx1 (the metadata field as a column), its name labels the x-axis; feature ticks are left to the main heatmap.

side: str = 'bottom'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

render(ax)[source]

Draw this track onto ax.

Return type:

Axes

legend_entries()[source]

Return {legend_name: {category: color}} contributed to the shared legend, or None if this track has no legend.

Return type:

dict[str, dict]

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

CategoricalTrack

class pymaftools.plot.Track.NumericTrack(data, *, side='bottom', cmap='Blues', name=None, line_color='white', linewidths=1, alpha=1, annotate=False, annotation_font_size=10, fmt='.2f', ytick_fontsize=10, colorbar='legend', vmin=None, vmax=None)[source]

Bases: Track

Single numeric annotation strip with a configurable colorbar.

The value scale (a colorbar) can be placed in three ways via colorbar:

  • "legend" (default): contributed to the shared legend area as a stacked colorbar — readable even with several numeric columns (the inset bars get cramped when stacked on thin strips, PLOTTING_REVIEW P1#3).

  • "inset": a small colorbar beside the strip itself.

  • "off": no colorbar.

side: str = 'bottom'

"main" for the central matrix; "top"/"bottom" align to samples (columns); "left"/"right" align to features (rows).

Type:

str

property label: str
render(ax)[source]

Draw this track onto ax.

Return type:

Axes

colorbar_legend()[source]

Colorbar spec for the shared legend area, or None unless colorbar="legend" and a range is known (explicit, or set by render). Explicit range is preferred so grouped rendering — which renders sliced copies, not this instance — still contributes the legend.

Return type:

dict | None

subset(feat=None, samp=None)[source]

Return a copy restricted to the given feature / sample integer positions, for grouped (sectioned) rendering. feat/samp are position arrays over the matrix rows / columns, or None for all. Overridden by tracks that hold axis-aligned data.

Return type:

NumericTrack

LollipopPlot

class pymaftools.plot.LollipopPlot.LollipopPlot(protein_name, protein_length, domains, mutations, config=None, domain_label_map=None, mutation_label_map=None)[source]

Bases: BasePlot

LollipopPlot class for creating protein domain and mutation visualizations.

This class provides functionality for visualizing protein domains and mutations as lollipop plots, inheriting unified legend management and save functionality from BasePlot.

plot(ax=None, fig=None)[source]

Plot lollipop plot with protein domains and mutations.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – Axes to plot on.

  • fig (matplotlib.figure.Figure, optional) – Figure to use.

Returns:

self (LollipopPlot) – Returns self for method chaining.

show()[source]

Show the plot.

Returns:

self (LollipopPlot) – Returns self for method chaining.

classmethod plot_multi_cohort(gene, cohorts_data, figsize=(20, 15), width_ratios=None, config=None, domain_label_map=None, mutation_label_map=None, save_path=None, dpi=300, title=None)[source]

Create lollipop plots for multiple cohorts with unified legend.

Parameters:
  • gene (str) – Gene name.

  • cohorts_data (dict) – Dictionary with cohort names as keys and values as tuples: (AA_length, mutations_data, domains_data, refseq_ID).

  • figsize (tuple, default (20, 15)) – Figure size.

  • width_ratios (list, default [9, 1]) – Width ratios for main plots and legend.

  • config (dict, optional) – Configuration options.

  • domain_label_map (dict, optional) – Dictionary to map original domain labels to custom display names.

  • mutation_label_map (dict, optional) – Dictionary to map original mutation types to custom display names.

  • save_path (str, optional) – Path to save the figure.

  • dpi (int, default 300) – DPI for saving.

  • title (str, optional) – Title for the figure.

Returns:

LollipopPlot – The main plot instance with unified legends.

Examples

>>> cohorts_data = {
...     'LUAD': (AA_length, mutations_data, domains_data, refseq_ID),
...     'ASC': (AA_length, mutations_data, domains_data, refseq_ID),
...     'LUSC': (AA_length, mutations_data, domains_data, refseq_ID),
... }
>>> plot = LollipopPlot.plot_multi_cohort('TP53', cohorts_data)

PivotStatsPlot

Note

PivotTablePlot was renamed to PivotStatsPlot. The old name remains importable as a deprecated alias via from pymaftools.plot.PivotTablePlot import PivotTablePlot.

PivotStatsPlot Module

Statistical / exploratory plots for PivotTable objects (PCA, boxplots with annotations, …). Named to make clear this is not the base for all PivotTable plotting — the composite oncoplot lives in OncoPlot. Kept separate from the core PivotTable class.

PivotTablePlot remains importable as a backward-compatible alias (v0.5.0).

class pymaftools.plot.PivotStatsPlot.PivotStatsPlot(pivot_table)[source]

Bases: BasePlot

Statistical / exploratory plots for PivotTable objects.

Provides one-shot statistical visualizations (PCA, annotated boxplots) plus an oncoplot() entry point. Inherits from BasePlot for legend management and figure saving.

Parameters:

pivot_table (PivotTable) – The PivotTable instance to create plots for.

Examples

>>> # Using property accessor (recommended)
>>> pivot_table.plot.plot_pca_samples(color_col="subtype")
>>> pivot_table.plot.plot_boxplot_with_annot(test_col="TMB")
>>> # Composite oncoplot via the same accessor
>>> pivot_table.plot.oncoplot(figsize=(15, 10)).main().add_freq().render()
oncoplot(**kwargs)[source]

Create an OncoPlot for this table.

Unifies the entry point so the composite oncoplot is reachable from the same table.plot accessor as the statistical plots, e.g.:

table.plot.oncoplot(figsize=(15, 10)).main().add_freq().render()

**kwargs are forwarded to OncoPlot (e.g. figsize, cmap).

somatic_interactions(**kwargs)[source]

Draw co-occurrence / mutual exclusivity heatmap for mutated genes.

somatic_interactions_stats(**kwargs)[source]

Return pairwise co-occurrence / mutual exclusivity Fisher tests.

plot_boxplot_with_annot(data=None, group_col='subtype', test_col='mutations_count', palette=None, title=None, xlabel=None, ylabel=None, ax=None, test='Mann-Whitney', comparisons_correction=None, alpha=0.8, order=None, fontsize=12, rotation=0, save_path=None, dpi=300, is_paired=False, pair_col=None, verbose=False)[source]

Create boxplot with statistical annotations.

Creates a boxplot comparing groups with statistical significance testing and annotations. Supports pairwise comparisons between all groups using various statistical tests.

Parameters:
  • data (pd.DataFrame, optional) – DataFrame containing the data to plot. If None, uses the PivotTable’s sample_metadata.

  • group_col (str, default "subtype") – Column name in data to use for grouping samples.

  • test_col (str, default "mutations_count") – Column name in data containing values to plot on y-axis.

  • palette (str or dict, optional) – Color palette for the boxplot. Can be a seaborn palette name or a dictionary mapping group values to colors.

  • title (str, optional) – Plot title. If None, auto-generates title from column names.

  • xlabel (str, optional) – X-axis label. If None, uses group_col name.

  • ylabel (str, optional) – Y-axis label. If None, uses test_col name.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. If None, creates new figure and axes.

  • test (str, default 'Mann-Whitney') – Statistical test for pairwise comparisons. Options include: ‘Mann-Whitney’, ‘Wilcoxon’, ‘t-test_ind’, ‘Welch’, etc.

  • comparisons_correction (str, optional) – Method for multiple comparisons correction (e.g., “benjamini-hochberg”). If None, no correction is applied.

  • alpha (float, default 0.8) – Transparency level for boxplot fill colors (0-1).

  • order (list of str, optional) – Order of groups on x-axis. If None, uses natural order.

  • fontsize (int, default 12) – Font size for axis labels and tick labels.

  • rotation (int, default 0) – Rotation angle for x-axis tick labels in degrees.

  • save_path (str, optional) – Path to save the figure. Format determined by file extension.

  • dpi (int, default 300) – Resolution for saved figure.

  • is_paired (bool, default False) – Whether to perform paired statistical tests. When True, requires pair_col.

  • pair_col (str, optional) – Column name identifying paired samples. Required when is_paired=True.

  • verbose (bool, default False) – Whether to show detailed statistical test output.

Return type:

Axes

Returns:

matplotlib.axes.Axes – The axes object containing the plot.

Notes

This method uses statannotations library for statistical annotations. P-values are displayed as stars: * p<0.05, ** p<0.01, *** p<0.001.

Examples

>>> # Basic boxplot comparing TMB by subtype
>>> pivot_table.plot.plot_boxplot_with_annot(
...     test_col="TMB",
...     group_col="subtype"
... )
>>> # Custom styling with specific order and colors
>>> pivot_table.plot.plot_boxplot_with_annot(
...     test_col="MSI",
...     group_col="subtype",
...     palette={"LUAD": "orange", "ASC": "green", "LUSC": "blue"},
...     order=["LUAD", "ASC", "LUSC"],
...     title="MSI Score by Cancer Subtype",
...     xlabel="Cancer Subtype",
...     ylabel="MSI Score",
...     rotation=45  # Rotate x-axis labels 45 degrees
... )
>>> # Paired comparison (e.g., before/after treatment)
>>> pivot_table.plot.plot_boxplot_with_annot(
...     test_col="expression_level",
...     group_col="treatment_status",  # "before", "after"
...     xlabel="Treatment Status",
...     ylabel="Expression Level",
...     is_paired=True,
...     pair_col="patient_id",  # Column identifying paired samples
...     test='Wilcoxon'  # Wilcoxon signed-rank test for paired data
... )
plot_pca_samples(color_col='subtype', shape_col=None, figsize=(12, 6), to_binary=False, palette=None, alpha=0.8, title=None, titlesize=14, is_numeric=False, save_path=None, fontsize=12, width_ratios=(4, 1), legend_item_spacing=0.04, legend_group_spacing=0.06, dpi=300, s=60)[source]

Plot PCA scatter plot using ColorManager and LegendManager for unified styling.

This method leverages the full power of ColorManager for color generation and LegendManager for consistent legend appearance across all plot types. Provides better integration with the overall plotting architecture. Supports both categorical and numeric color encoding, with optional shape encoding.

Parameters:
  • color_col (str, default "subtype") – Column name for color encoding. Can be categorical or numeric.

  • shape_col (str, optional) – Column name for shape encoding. Works with both categorical and numeric color_col.

  • figsize (tuple of int, default (12, 6)) – Figure size as (width, height).

  • to_binary (bool, default False) – Whether to convert mutation data to binary before PCA.

  • palette (str or dict, optional) – Color palette. For categorical: seaborn palette name or color dict. For numeric: matplotlib colormap name (e.g., ‘viridis’, ‘plasma’).

  • alpha (float, default 0.8) – Transparency level for scatter points (0-1).

  • title (str, optional) – Plot title. If None, no title is displayed.

  • titlesize (int, default 14) – Font size for the title.

  • is_numeric (bool, default False) – Whether to treat color_col as numeric data (uses colormap instead of discrete colors).

  • save_path (str, optional) – Path to save the figure. Format determined by file extension.

  • fontsize (int, default 12) – Font size for axis labels and legend.

  • width_ratios (tuple of int, default (4, 1)) – Width ratios for plot and legend subplots.

  • legend_item_spacing (float, default 0.04) – Spacing between legend items.

  • legend_group_spacing (float, default 0.06) – Spacing between legend groups.

  • dpi (int, default 300) – Resolution for saved figure.

  • s (int, default 60) – Size of scatter points.

Return type:

tuple[DataFrame, ndarray, PCA]

Returns:

tuple –

  • pca_result_dfpd.DataFrame

    PCA results with PC1, PC2 columns and metadata

  • explained_variancenp.ndarray

    Explained variance ratio for each component

  • pcasklearn.decomposition.PCA

    Fitted PCA object

Notes

This method uses ColorManager for automatic color generation and LegendManager for legend rendering, providing the most consistent styling with other plot types in the package.

For numeric color encoding (is_numeric=True): - Uses continuous colormap for color representation - Displays colorbar instead of discrete legend - Still supports shape encoding via shape_col parameter

For categorical color encoding (is_numeric=False): - Uses discrete colors for each category - Displays standard legend with color patches - Supports shape encoding for additional dimension

Examples

>>> # Basic PCA plot with categorical colors
>>> pca_df, variance, pca_obj = pivot_table.plot.plot_pca_samples(
...     color_col="subtype"
... )
>>> # PCA with numeric colors and shape encoding
>>> pca_df, variance, pca_obj = pivot_table.plot.plot_pca_samples(
...     color_col="TMB",  # numeric column
...     shape_col="subtype",  # categorical shapes
...     is_numeric=True,
...     palette="viridis"
... )
>>> # PCA with both categorical color and shape encoding
>>> pca_df, variance, pca_obj = pivot_table.plot.plot_pca_samples(
...     color_col="subtype",
...     shape_col="sample_type",
...     palette={"LUAD": "red", "ASC": "green", "LUSC": "blue"}
... )

ExpressionTablePlot

ExpressionTablePlot Module

Plotting functionality specific to ExpressionTable objects, including volcano plots for differential expression results.

class pymaftools.plot.ExpressionTablePlot.ExpressionTablePlot(pivot_table)[source]

Bases: PivotStatsPlot

Plotting functionality for ExpressionTable objects.

Inherits all PivotStatsPlot methods (PCA, boxplot, etc.) and adds expression-specific visualisations such as volcano plots.

Parameters:

expression_table (ExpressionTable) – The ExpressionTable instance to create plots for.

volcano(padj=0.05, log2fc=1.0, top_n=10, label_col='gene_name', ax=None, figsize=(8, 6), save_path=None, dpi=150)[source]

Draw a volcano plot from DESeq2 results in feature_metadata.

Parameters:
  • padj (float, default 0.05) – Adjusted p-value threshold for significance.

  • log2fc (float, default 1.0) – Absolute log2 fold-change threshold.

  • top_n (int, default 10) – Number of top DEGs to label.

  • label_col (str, default "gene_name") – Column in feature_metadata used for gene labels.

  • ax (Axes, optional) – Matplotlib axes to draw on. Created if None.

  • figsize (tuple, default (8, 6)) – Figure size when creating a new figure.

  • save_path (str, optional) – Path to save the figure.

  • dpi (int, default 150) – Resolution for saved figure.

Return type:

Axes

Returns:

Axes

CopyNumberVariationTablePlot

CopyNumberVariationTablePlot Module

Plotting functionality specific to CopyNumberVariationTable objects. Reachable via cnv_table.plot.

class pymaftools.plot.CopyNumberVariationTablePlot.CopyNumberVariationTablePlot(pivot_table)[source]

Bases: PivotStatsPlot

Plotting interface for CopyNumberVariationTable objects.

Inherits the shared plotters from PivotStatsPlot (oncoplot, plot_pca_samples, plot_boxplot_with_annot) and adds CNV-specific visualisations.

band_ratio(**kwargs)[source]

Plot gain/loss frequency across cytobands for a CNV cluster.

Delegates to the table implementation; see CopyNumberVariationTable._cnv_band_ratio() for parameters.

SignatureTablePlot

SignatureTablePlot Module

Plotting functionality specific to SignatureTable objects. Reachable via signature_table.plot.

class pymaftools.plot.SignatureTablePlot.SignatureTablePlot(pivot_table)[source]

Bases: PivotStatsPlot

Plotting interface for SignatureTable objects.

Inherits the shared plotters from PivotStatsPlot (oncoplot, plot_pca_samples, plot_boxplot_with_annot) and adds the signature-specific exposure landscape (stacked_bar()).

A SignatureTable is oriented signatures (rows) × samples (columns), with each value the activity / exposure of that signature in that sample.

stacked_bar(*, normalize=True, ax=None, figsize=(20, 6), colormap='tab20', legend=True, width=1.0, show_sample_labels=None)[source]

Per-sample signature exposure as a stacked bar chart.

Samples run along the x-axis; each bar stacks its signature contributions (one colour per signature). This is the canonical “signature landscape” view of an exposure matrix.

Parameters:
  • normalize (bool, default True) – Scale each sample’s bar to sum to 1 (relative contributions). When False, bars use the raw exposure totals (variable bar heights).

  • ax (matplotlib.axes.Axes, optional) – Axes to draw on; a new figure/axes is created when None.

  • figsize (tuple, default (20, 6)) – Figure size, used only when ax is None.

  • colormap (str, default "tab20") – Matplotlib colormap mapping signatures to colours.

  • legend (bool, default True) – Draw the signature legend (placed outside, upper-right).

  • width (float, default 0.9) – Bar width passed to the pandas bar plot.

Returns:

matplotlib.axes.Axes – The axes the bars were drawn on.

Examples

>>> signature_table.plot.stacked_bar()                 # relative
>>> signature_table.plot.stacked_bar(normalize=False)  # raw exposures

SmallVariationTablePlot

SmallVariationTablePlot Module

Plotting functionality specific to SmallVariationTable objects. Reachable via small_variation_table.plot.

class pymaftools.plot.SmallVariationTablePlot.SmallVariationTablePlot(pivot_table)[source]

Bases: PivotStatsPlot

Plotting interface for SmallVariationTable objects.

Inherits the shared plotters from PivotStatsPlot (oncoplot, plot_pca_samples, plot_boxplot_with_annot). This is a reserved extension point for mutation-specific plots; add them here as methods.

ModelPlot

ModelPlot class for machine learning model visualization Inherits from BasePlot to use common plotting functionality

class pymaftools.plot.ModelPlot.ModelPlot[source]

Bases: BasePlot

Plotting class for machine learning models.

Inherits from BasePlot to use save method and legend management.

plot_metric_comparison_with_annotation(data, metrics=None, group_col='model', order=None, palette='Set2', test='Mann-Whitney', alpha=0.8, fontsize=14, title_fontsize=None, label_fontsize=None, tick_fontsize=None, figsize=None, title_prefix=None, rotation=45, save_path=None, **save_kwargs)[source]

Plot metric comparison with statistical annotation.

Parameters:
  • data (pd.DataFrame) – DataFrame with model metrics.

  • metrics (list[str] or None, optional) – List of metrics to plot. Defaults to ['acc', 'f1', 'auc'].

  • group_col (str, optional) – Column name for grouping. Default is 'model'.

  • order (list[str] or None, optional) – Order of groups. Defaults to ["SNV", "CNV-gene", "CNV-cluster", "STACK"].

  • palette (str, optional) – Color palette. Default is "Set2".

  • test (str, optional) – Statistical test method. Default is "Mann-Whitney".

  • alpha (float, optional) – Transparency level. Default is 0.8.

  • fontsize (int, optional) – Base font size (used as default for other sizes if not specified). Default is 14.

  • title_fontsize (int or None, optional) – Font size for titles. Defaults to fontsize + 2.

  • label_fontsize (int or None, optional) – Font size for axis labels. Defaults to fontsize.

  • tick_fontsize (int or None, optional) – Font size for tick labels. Defaults to fontsize - 2.

  • figsize (tuple[int, int] or None, optional) – Figure size. Defaults to (6 * len(metrics), 6).

  • title_prefix (str or None, optional) – Title prefix. Set to None to disable titles.

  • rotation (int, optional) – Rotation angle for x-axis tick labels in degrees. Default is 45.

  • save_path (str or None, optional) – Path to save figure.

  • **save_kwargs (Any) – Additional arguments for the save method.

Return type:

ModelPlot

Returns:

ModelPlot – Self, for method chaining.

plot_top_feature_importance_heatmap(importance_df, omic, title=None, top_n=10, cmap='viridis', figsize=(10, 6), save_path=None, xticklabel=False, **save_kwargs)[source]

Plot top feature importance heatmap.

Parameters:
  • importance_df (pd.DataFrame) – DataFrame with feature importance data.

  • omic (str) – Omics type name.

  • title (str or None, optional) – Plot title.

  • top_n (int, optional) – Number of top features to show. Default is 10.

  • cmap (str, optional) – Color map. Default is "viridis".

  • figsize (tuple[int, int], optional) – Figure size. Default is (10, 6).

  • save_path (str or None, optional) – Path to save figure.

  • xticklabel (bool, optional) – Whether to show x-axis tick labels. Default is False.

  • **save_kwargs (Any) – Additional arguments for the save method.

Return type:

ModelPlot

Returns:

ModelPlot – Self, for method chaining.

plot_rfecv_curve(selector, scoring='accuracy', palette='tab10', title=None, figsize=(15, 5), save_path=None, **save_kwargs)[source]

Plot recursive feature elimination with cross-validation curve.

Parameters:
  • selector (Any) – Fitted RFECV selector object with cv_results_ attribute.

  • scoring (str, optional) – Scoring metric name. Default is "accuracy".

  • palette (str, optional) – Color palette. Default is "tab10".

  • title (str or None, optional) – Plot title.

  • figsize (tuple[int, int], optional) – Figure size. Default is (15, 5).

  • save_path (str or None, optional) – Path to save figure.

  • **save_kwargs (Any) – Additional arguments for the save method.

Return type:

ModelPlot

Returns:

ModelPlot – Self, for method chaining.

plot_feature_importance_distribution(importance_df, model_name, top_n=20, figsize=(10, 8), save_path=None, **save_kwargs)[source]

Plot feature importance distribution across CV folds.

Parameters:
  • importance_df (pd.DataFrame) – Long format DataFrame with feature importance.

  • model_name (str) – Name of the model to plot.

  • top_n (int, optional) – Number of top features to show. Default is 20.

  • figsize (tuple[int, int], optional) – Figure size. Default is (10, 8).

  • save_path (str or None, optional) – Path to save figure.

  • **save_kwargs (Any) – Additional arguments for the save method.

Return type:

ModelPlot

Returns:

ModelPlot – Self, for method chaining.

MethodsPlot

class pymaftools.plot.MethodsPlot.MethodsPlot[source]

Bases: BasePlot

Plotting class for methodology visualizations.

Inherits from BasePlot to use save method and common plotting functionality. Provides 3D cohort demonstration plots and helper drawing utilities.

static draw_cube(ax, origin, width, depth, height, color='skyblue', alpha=0.8)[source]

Draw a 3D cube on the given axes.

Parameters:
  • ax (plt.Axes) – The 3D matplotlib axes to draw on.

  • origin (tuple[float, float, float]) – (x, y, z) coordinates for the cube origin corner.

  • width (float) – Size along the x-axis.

  • depth (float) – Size along the y-axis.

  • height (float) – Size along the z-axis.

  • color (str, optional) – Face color of the cube. Default is 'skyblue'.

  • alpha (float, optional) – Transparency level. Default is 0.8.

Return type:

None

plot_cohort_demo(save_path=None, dpi=300)[source]

Plot a 3D cohort demonstration with stacked omics cubes.

Creates a 3D visualization with two groups of cubes representing omics data dimensions (features x samples) for different data types.

Parameters:
  • save_path (str or None, optional) – Path to save the figure. If None, the figure is only displayed.

  • dpi (int, optional) – Resolution for saved figure. Default is 300.

Return type:

None

BasePlot

Base plotting class that provides legend management functionality.

class pymaftools.plot.BasePlot.BasePlot[source]

Bases: object

Base class for all plotting classes.

Provides common functionality for legend management and color management.

add_legend(legend_name, color_dict)[source]

Add legend information to LegendManager.

Parameters:
  • legend_name (str) – Legend name, such as ‘mutation’, ‘sex’, ‘subtype’, etc.

  • color_dict (dict[str, str]) – Color mapping dictionary, such as {'M': 'blue', 'F': 'red'}.

Return type:

BasePlot

Returns:

BasePlot – Self, to support method chaining.

plot_all_legends(ax=None, fontsize=8, title_fontsize=10, legend_spacing=0.08, item_spacing=0.02, **kwargs)[source]

Plot all legends on the specified axis.

Parameters:
  • ax (Axes or None, optional) – Axis to plot legends on. Uses self.ax_legend if None.

  • fontsize (int, optional) – Legend text font size.

  • title_fontsize (int, optional) – Legend title font size.

  • legend_spacing (float, optional) – Spacing between different legends.

  • item_spacing (float, optional) – Spacing between items within the same legend.

Return type:

BasePlot

Returns:

BasePlot – Self, to support method chaining.

get_legend_manager()[source]

Get the legend manager instance.

Return type:

LegendManager

Returns:

LegendManager – The legend manager instance.

remove_legend(legend_name)[source]

Remove a specified legend.

Parameters:

legend_name (str) – Name of the legend to remove.

Return type:

BasePlot

Returns:

BasePlot – Self, to support method chaining.

clear_legends()[source]

Clear all legends.

Return type:

BasePlot

Returns:

BasePlot – Self, to support method chaining.

has_legend(legend_name)[source]

Check if a legend with the specified name exists.

Parameters:

legend_name (str) – Legend name.

Return type:

bool

Returns:

bool – Whether the legend exists.

get_legend_names()[source]

Get all legend names.

Return type:

list[str]

Returns:

list[str] – List of legend names.

get_color_manager()[source]

Get the color manager instance.

Return type:

ColorManager

Returns:

ColorManager – The color manager instance.

save(filename, dpi=300, bbox_inches='tight', pad_inches=0.08, transparent=False, **kwargs)[source]

Save figure to file.

Parameters:
  • filename (str) – File name.

  • dpi (int, optional) – Resolution.

  • bbox_inches (str, optional) – Bounding box setting.

  • pad_inches (float, optional) – Padding around the tight bounding box.

  • transparent (bool, optional) – Whether to use transparent background.

  • **kwargs (Any) – Other save parameters passed to fig.savefig.

Return type:

None

close()[source]

Close the figure.

Return type:

None

ColorManager

class pymaftools.plot.ColorManager.ColorManager[source]

Bases: object

Unified color mapping and palette management for OncoPlot visualizations.

This class provides centralized management of color schemes, including predefined color maps for different mutation types, CNV data, and utilities for generating categorical color mappings.

NONSYNONYMOUS_CMAP = {'False': '#FFFFFF', 'Frame_Shift_Del': '#3E85C0', 'Frame_Shift_Ins': '#FF4500', 'In_Frame_Del': '#ADDBEA', 'In_Frame_Ins': '#E8656E', 'Missense_Mutation': 'gray', 'Multi_Hit': '#222222', 'Nonsense_Mutation': '#98E28F', 'Splice_Site': '#D0875D'}
ALL_MUTATION_CMAP = {"3'UTR": '#bbbbcc', "5'UTR": '#bbbbcc', 'False': '#FFFFFF', 'Frame_Shift_Del': '#3E85C0', 'Frame_Shift_Ins': '#FF4500', 'IGR': '#bbbbcc', 'In_Frame_Del': '#ADDBEA', 'In_Frame_Ins': '#E8656E', 'Intron': '#bbbbcc', 'Missense_Mutation': 'gray', 'Multi_Hit': '#222222', 'Nonsense_Mutation': '#98E28F', 'RNA': '#bbbbcc', 'Silent': '#eeeeee', 'Splice_Site': '#D0875D'}
CNV_CMAP = {'AMP': 'salmon', 'AMP&DEL': 'gray', 'DEL': 'steelblue'}
TITV_CMAP = {'C>A': '#02BCED', 'C>G': '#1A1A1A', 'C>T': '#E32926', 'T>A': '#999999', 'T>C': '#A1CE63', 'T>G': '#EDBFC2'}
FUNCTIONAL_GROUP = {"3'Flank": 'Other', "3'UTR": 'Other', "5'Flank": 'Other', "5'UTR": 'Other', 'Frame_Shift_Del': 'Truncating', 'Frame_Shift_Ins': 'Truncating', 'IGR': 'Other', 'In_Frame_Del': 'In-frame', 'In_Frame_Ins': 'In-frame', 'Intron': 'Other', 'Missense_Mutation': 'Missense', 'Nonsense_Mutation': 'Truncating', 'Nonstop_Mutation': 'Truncating', 'RNA': 'Other', 'Silent': 'Silent', 'Splice_Region': 'Splice', 'Splice_Site': 'Splice', 'Targeted_Region': 'Other', 'Translation_Start_Site': 'Truncating'}
FUNCTIONAL_ORDER = ['Truncating', 'Splice', 'Missense', 'In-frame', 'Silent', 'Other']
FUNCTIONAL_CMAP = {'In-frame': '#ADDBEA', 'Missense': '#7F7F7F', 'Other': '#BBBBCC', 'Silent': '#D9D9D9', 'Splice': '#D0875D', 'Truncating': '#C0392B'}
predefined_cmaps = {'all_mutation': {"3'UTR": '#bbbbcc', "5'UTR": '#bbbbcc', 'False': '#FFFFFF', 'Frame_Shift_Del': '#3E85C0', 'Frame_Shift_Ins': '#FF4500', 'IGR': '#bbbbcc', 'In_Frame_Del': '#ADDBEA', 'In_Frame_Ins': '#E8656E', 'Intron': '#bbbbcc', 'Missense_Mutation': 'gray', 'Multi_Hit': '#222222', 'Nonsense_Mutation': '#98E28F', 'RNA': '#bbbbcc', 'Silent': '#eeeeee', 'Splice_Site': '#D0875D'}, 'cnv': {'AMP': 'salmon', 'AMP&DEL': 'gray', 'DEL': 'steelblue'}, 'functional': {'In-frame': '#ADDBEA', 'Missense': '#7F7F7F', 'Other': '#BBBBCC', 'Silent': '#D9D9D9', 'Splice': '#D0875D', 'Truncating': '#C0392B'}, 'nonsynonymous': {'False': '#FFFFFF', 'Frame_Shift_Del': '#3E85C0', 'Frame_Shift_Ins': '#FF4500', 'In_Frame_Del': '#ADDBEA', 'In_Frame_Ins': '#E8656E', 'Missense_Mutation': 'gray', 'Multi_Hit': '#222222', 'Nonsense_Mutation': '#98E28F', 'Splice_Site': '#D0875D'}, 'titv': {'C>A': '#02BCED', 'C>G': '#1A1A1A', 'C>T': '#E32926', 'T>A': '#999999', 'T>C': '#A1CE63', 'T>G': '#EDBFC2'}}
add_cmap(name, cmap)[source]

Register a custom colormap for later use.

Parameters:
  • name (str) – Name identifier for the colormap.

  • cmap (dict[str, str]) – Dictionary mapping categories to color values.

Return type:

None

get_cmap(name, factor=None, alpha=None)[source]

Retrieve a colormap by name, optionally adjusting brightness and simulated alpha.

Parameters:
  • name (str) – Name of the colormap to retrieve.

  • factor (float, optional) – Brightness factor (>1 = brighter, <1 = darker).

  • alpha (float, optional) – Simulated alpha blending with white background (0–1).

Return type:

dict[str, str]

Returns:

dict[str, str] – Adjusted color mapping.

simulate_alpha_blend(color, alpha, background='#FFFFFF')[source]

Simulate alpha blending of a foreground color over a background color.

Blends the foreground and background colors using the given alpha value and returns the resulting opaque color in hex format.

Parameters:
  • color (str) – Foreground color (any valid matplotlib color string).

  • alpha (float) – Opacity of the foreground color (0 = fully transparent, 1 = fully opaque).

  • background (str, default "#FFFFFF") – Background color to blend against.

Return type:

str

Returns:

str – Blended color in hex format.

generate_categorical_cmap(data, custom_cmap=None, default_palette='Set1')[source]

Generate color mapping for categorical data.

Automatically creates a color mapping for unique categories in the data, with optional custom color overrides.

Parameters:
  • data (pandas.DataFrame or pandas.Series) – Data containing categorical values.

  • custom_cmap (dict[str, str], optional) – Custom color mapping to override defaults.

  • default_palette (str, default "Set1") – Name of seaborn palette for default colors.

Return type:

dict[str, str]

Returns:

dict[str, str] – Mapping from categories to color values.

apply_cmap_to_data(data, cmap, missing_color='#FFFFFF')[source]

Apply color mapping to data values.

Parameters:
  • data (pandas.DataFrame or pandas.Series) – Data to apply color mapping to.

  • cmap (dict[str, str]) – Color mapping dictionary.

  • missing_color (str, default "#FFFFFF") – Color for missing or unmapped values.

Return type:

DataFrame | Series

Returns:

pandas.DataFrame or pandas.Series – Data with values replaced by corresponding colors.

create_matplotlib_cmap(categories, colors, unknown_color='white')[source]

Create matplotlib ListedColormap from categories and colors.

Parameters:
  • categories (list[str]) – List of category names.

  • colors (list[str]) – Corresponding list of color values.

  • unknown_color (str, default "white") – Color for unknown/unmapped categories.

Return type:

ListedColormap

Returns:

matplotlib.colors.ListedColormap – Matplotlib colormap object.

adjust_color_brightness(color, factor)[source]

Adjust the brightness of a color using HLS color space.

Parameters:
  • color (str) – Any valid matplotlib color (hex, name, etc.)

  • factor (float) – Brightness adjustment factor: - 1.0 = no change - <1.0 = darker - >1.0 = brighter

Return type:

str

Returns:

str – Adjusted color in hex format

generate_cmap_from_list(categories, cmap_name='tab20', as_hex=True)[source]

Generate a color mapping dictionary from a list of categories using a matplotlib colormap.

This method automatically creates evenly spaced colors from the specified colormap and maps them to the provided categories. Very useful for creating consistent color mappings for categorical data like case_IDs, sample_types, etc.

Parameters:
  • categories (list) – List of unique categories to create color mapping for

  • cmap_name (str, default "tab20") – Name of matplotlib colormap to use. Popular choices: - “tab20”: 20 distinct colors, good for many categories - “Set1”: 9 bright colors, good for fewer categories - “Set3”: 12 pastel colors - “viridis”, “plasma”: continuous colormaps

  • as_hex (bool, default True) – If True, return colors as hex strings. If False, return as RGBA tuples.

Return type:

dict[str, str]

Returns:

dict – Dictionary mapping categories to color values

Examples

>>> cm = ColorManager()
>>> case_ids = ["LUAD_001", "LUAD_002", "ASC_001", "ASC_002"]
>>> colors = cm.generate_cmap_from_list(case_ids, "tab20")
>>> print(colors)
{"LUAD_001": "#1f77b4", "LUAD_002": "#ff7f0e", ...}
>>> # For many categories, tab20 works well
>>> many_categories = [f"sample_{i}" for i in range(15)]
>>> colors = cm.generate_cmap_from_list(many_categories, "tab20")
>>> # For fewer categories, Set1 gives more distinct colors
>>> few_categories = ["Control", "Treatment", "Placebo"]
>>> colors = cm.generate_cmap_from_list(few_categories, "Set1")

FontManager

class pymaftools.plot.FontManager.FontManager[source]

Bases: object

Manager for registering and configuring fonts in matplotlib.

Provides utilities for registering local font files, scanning directories for fonts, and applying font settings globally to matplotlib’s rcParams.

WEIGHT_MAP = {'black': 900, 'bold': 700, 'book': 400, 'demibold': 600, 'extra bold': 800, 'heavy': 800, 'light': 200, 'medium': 500, 'normal': 400, 'regular': 400, 'semibold': 600, 'ultralight': 100}

Mapping from weight name strings to numeric weight values.

Type:

dict

get_available_fonts()[source]

Return a sorted list of available font family names.

Return type:

list[str]

Returns:

list[str] – Sorted unique font family names registered in matplotlib.

static normalize_weight(weight)[source]

Normalize a font weight to its numeric value.

Parameters:

weight (str or int) – Font weight as a string name (e.g. “bold”) or numeric value.

Return type:

int

Returns:

int – Numeric font weight value.

Raises:

ValueError – If the weight string or value is not recognized.

entry_equal_properties(entry, font_prop)[source]

Check whether a font entry matches the given font properties.

Parameters:
  • entry (matplotlib.font_manager.FontEntry) – A registered font entry to compare.

  • font_prop (matplotlib.font_manager.FontProperties) – Target font properties.

Return type:

bool

Returns:

bool – True if name, weight, and style all match.

register_local_font(font_path)[source]

Register a local .ttf font file.

Skips registration if a font with the same name, weight, and style is already registered.

Parameters:

font_path (str) – Path to a .ttf font file.

Return type:

str

Returns:

str – The registered font family name.

register_fonts_from_directory(directory)[source]

Recursively register all .ttf fonts from a directory.

Parameters:

directory (str) – Path to a directory containing font files.

Raises:

ValueError – If the directory does not exist.

Return type:

None

setup_matplotlib_fonts(font_family='Source Sans Pro', font_weight='normal', base_size=12, fallback_fonts=None)[source]

Configure matplotlib font settings globally.

Parameters:
  • font_family (str, default "Source Sans Pro") – Desired font family name.

  • font_weight (str, default "normal") – Font weight string (e.g. “normal”, “bold”).

  • base_size (int, default 12) – Base font size in points.

  • fallback_fonts (list of str, optional) – Ordered list of fallback font names if font_family is unavailable.

Return type:

str

Returns:

str – The font family name that was actually applied.

Raises:

ValueError – If font_family is not found and no fallback fonts are provided or available.

LegendManager

class pymaftools.plot.LegendManager.LegendManager(ax=None)[source]

Bases: object

Specialized class for legend management.

Responsible for managing and plotting various types of legends, including mutation types, categorical variables, numeric variables, etc. Supports advanced features for PCA plots including shape markers, numeric colorbars, and mixed legends.

set_axis(ax)[source]

Set the axis for legend plotting.

Parameters:

ax (Axes.Axes) – matplotlib axis object.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

add_legend(legend_name, color_dict)[source]

Add legend information.

Parameters:
  • legend_name (str) – Legend name, such as ‘Mutation’, ‘Subtype’, ‘Sex’, etc.

  • color_dict (dict[str, str]) – Color mapping dictionary, such as {'M': 'blue', 'F': 'red'}.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

remove_legend(legend_name)[source]

Remove a specified legend.

Parameters:

legend_name (str) – Name of the legend to remove.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

clear_legends()[source]

Clear all legends.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

get_legend_dict()[source]

Get the current legend dictionary.

Return type:

dict[str, dict[str, str]]

Returns:

dict[str, dict[str, str]] – Complete legend dictionary.

plot_legends(ax=None, fontsize=8, title_fontsize=10, legend_spacing=0.08, item_spacing=0.02, start_y=0.95, rect_width=0.06, rect_height=0.02, text_offset_x=0.14, title_offset_y=0.05, item_offset_y=0.035, legend_gap=0.03, colorbar_width=0.55, colorbar_height=0.022)[source]

Plot all legends.

Parameters:
  • ax (Axes.Axes, optional) – matplotlib axis object, use initialization axis if None.

  • fontsize (int) – Legend item font size.

  • title_fontsize (int) – Legend title font size.

  • legend_spacing (float) – Spacing between different legends.

  • item_spacing (float) – Spacing between items within the same legend.

  • start_y (float) – Starting Y position.

  • rect_width (float) – Color rectangle width.

  • rect_height (float) – Color rectangle height.

  • text_offset_x (float) – Text X offset relative to color rectangle.

  • title_offset_y (float) – Y offset after title.

  • item_offset_y (float) – Y offset between items.

  • legend_gap (float) – Gap between legends.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

plot_horizontal_legend(ax=None, fontsize=8, title_fontsize=10, columns=3, rect_size=(0.03, 0.03), spacing=(0.15, 0.1))[source]

Plot legends in horizontal layout.

Parameters:
  • ax (Axes.Axes, optional) – matplotlib axis object.

  • fontsize (int) – Item font size.

  • title_fontsize (int) – Title font size.

  • columns (int) – Number of items per row.

  • rect_size (Tuple[float, float]) – Color rectangle size (width, height).

  • spacing (Tuple[float, float]) – Item spacing (horizontal spacing, vertical spacing).

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

get_legend_info(legend_name)[source]

Get color mapping for the specified legend.

Parameters:

legend_name (str) – Legend name.

Return type:

dict[str, str] | None

Returns:

dict[str, str] or None – Color mapping dictionary, None if not found.

has_legend(legend_name)[source]

Check if a legend with the specified name exists.

Parameters:

legend_name (str) – Legend name.

Return type:

bool

Returns:

bool – Whether the legend exists.

get_legend_names()[source]

Get all legend names.

Return type:

list[str]

Returns:

list[str] – List of legend names.

count_legends()[source]

Get the number of legends.

Return type:

int

Returns:

int – Number of legends.

update_legend_colors(legend_name, color_updates)[source]

Update colors for the specified legend.

Parameters:
  • legend_name (str) – Legend name.

  • color_updates (dict[str, str]) – Color mapping to update.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

static create_from_dict(legend_dict, ax=None)[source]

Create legend manager from dictionary.

Parameters:
  • legend_dict (dict[str, dict[str, str]]) – Complete legend dictionary.

  • ax (matplotlib.axes.Axes, optional) – Matplotlib axis object.

Return type:

LegendManager

Returns:

LegendManager – New legend manager instance.

add_shape_legend(legend_name, shape_dict)[source]

Add shape legend information.

Parameters:
  • legend_name (str) – Legend name, such as ‘Sex’, ‘Stage’, etc.

  • shape_dict (dict[str, str]) – Shape mapping dictionary, such as {'M': 'o', 'F': 's'}.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

add_numeric_legend(legend_name, colormap, vmin, vmax, label=None)[source]

Add numeric colorbar legend.

Parameters:
  • legend_name (str) – Legend name.

  • colormap (str) – Colormap name (e.g., ‘viridis’, ‘plasma’).

  • vmin (float) – Minimum value for colormap.

  • vmax (float) – Maximum value for colormap.

  • label (str, optional) – Colorbar label (default to legend_name).

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

add_numeric_colorbar(legend_name, scatter_obj, target_ax, label=None, orientation='vertical', fraction=0.08, pad=0.02)[source]

Add numeric colorbar directly to the target axis with custom format.

Parameters:
  • legend_name (str) – Legend name.

  • scatter_obj (Any) – The scatter plot object for colorbar.

  • target_ax (Axes.Axes) – Target axis to add colorbar to.

  • label (str, optional) – Colorbar label (default to legend_name).

  • orientation (str) – Colorbar orientation (‘vertical’ or ‘horizontal’).

  • fraction (float) – Size of colorbar relative to parent axis.

  • pad (float) – Padding between colorbar and parent axis.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.

plot_pca_legends(ax=None, color_legend=None, shape_legend=None, numeric_legend=None, fontsize=12, title_fontsize=12, legend_item_spacing=0.04, legend_group_spacing=0.06)[source]

Plot PCA-style legends with support for color, shape, and numeric legends.

Parameters:
  • ax (Axes.Axes, optional) – matplotlib axis object.

  • color_legend (str, optional) – Name of categorical color legend to display.

  • shape_legend (str, optional) – Name of shape legend to display.

  • numeric_legend (str, optional) – Name of numeric colorbar legend to display.

  • fontsize (int) – Font size for legend items.

  • title_fontsize (int) – Font size for legend titles.

  • legend_item_spacing (float) – Vertical spacing between items within the same legend group.

  • legend_group_spacing (float) – Vertical spacing between different legend groups.

Return type:

LegendManager

Returns:

LegendManager – Support method chaining.