Plot Modules
OncoPlot
- class pymaftools.plot.OncoPlot.OncoPlot(pivot_table, **kwargs)[source]
Bases:
BasePlotOncoPlot 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 byrender()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 byrender().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:
- 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 nextrender()). The columns come fromnumeric_columnsconfigured inset_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:
- 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"); prefermain()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:
- 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 categoricalMainMatrixTrack;"cnv"(alias"numeric") registers a continuousNumericMatrixTrackfor 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,yticklabelsfor mutation;cmap,symmetricfor cnv).
- Return type:
- Returns:
self (OncoPlot) – Returns self for method chaining.
- add_track(track)[source]
Register an arbitrary pre-built
Trackforrender().The escape hatch behind the curated
add_*helpers: anyTracksubclass (e.g. aBarTrackplaced on any side) can be attached here. Position and order follow(side, registration order)— the track’ssideplaces 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:
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:
- 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_metadatacolumns to draw, one strip each (e.g.["LUAD_freq", "LUSC_freq"]). Populate group-specific columns withPivotTable.add_freq()(groups=orgroup_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:
Notes
For a signed per-feature numeric column (e.g.
delta_freq) useadd_feature_annotation()with a diverging cmap instead;add_freqis 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_metadatacolumns 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:
See also
add_feature_annotationsame, 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_driverfrom 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_metadatacolumns 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
cmapinkwargs; 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:
Notes
Use this (not
add_freq()) for signed/continuous feature columns:add_freqis for 0–1 frequency proportions on a shared 0–1 scale, whileadd_feature_annotationinfers the scale per column (and goes symmetric forcoolwarm).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_metadatacolumn.render()draws each group as its own section with a whitespacegap(in matrix-cell units) between them and, ifshow_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:
- 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_metadatacolumn.render()draws each group as its own section with a whitespacegap(in matrix-cell units) between them and, ifshow_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:
Per-section frequency
With
freq=Trueeach section gets its own frequency strip immediately to its right, readingfeature_metadata[f"{label}{freq_suffix}"](e.g. theLUAD_freq/LUSC_freqcolumns produced byPivotTable.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
sideand 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; passfigto 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]fromset_config.main_height (float, optional) – Relative size of the main matrix column / row. Default to
width_ratios[0]/height_ratios[-1]fromset_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:
- 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(); preferadd_bar()in new code.- Parameters:
- Return type:
- 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(); preferadd_freq()in new code.- Parameters:
- Return type:
- 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:
- 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()(passsample_labels=to override them, orshow_sample_labels=to force on/off). This shim is kept for backward compatibility: it re-appliesrotation/fontsizeto the already-drawn gutter labels. Call it afterrender().- Return type:
- 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"); prefermain(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:
- 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:
- 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
MainMatrixTrackand (from Stage 2) the annotation tracks. Moved verbatim fromOncoPlot.categorical_heatmap, which now delegates here so external callers keep working.
- class pymaftools.plot.Track.Track[source]
Bases:
ABCAbstract 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:
- 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:
TrackMain mutation heatmap (categorical variant matrix).
Owns every drawing parameter that
OncoPlot.mutation_heatmapused 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:
- legend_entries()[source]
Return
{legend_name: {category: color}}contributed to the shared legend, orNoneif this track has no legend.
- 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:
TrackContinuous 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_entriesis None.renderdraws a compact inset colorbar (the declarative path); the legacy freq-column colorbar lives indraw_colorbar()for the eagernumeric_heatmap.- side: str = 'main'
"main"for the central matrix;"top"/"bottom"align to samples (columns);"left"/"right"align to features (rows).- Type:
- draw_colorbar(cax)[source]
Legacy freq-column colorbar (used by the eager
numeric_heatmapso its output stays byte-identical). Must be called afterrender().
- 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:
TrackBar strip aligned to one matrix axis; single-series or stacked.
sidein("top", "bottom")is sample-aligned and draws vertical bars (ax.bar);("left", "right")is feature-aligned and draws horizontal bars (ax.barh).growcontrols direction:"out"(default) grows away from the matrix,"in"toward it.datais normalized to an internalframewhose 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
colorwith 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:
- 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:
TrackPer-feature frequency annotation column drawn right of the matrix.
- 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:
TrackSingle categorical annotation strip.
Bound to either axis of the main matrix via
side(S3 — feature and sample annotations are the same kind of track):sidein("top", "bottom")→ sample-aligned, horizontal strip;datais 1xN (the metadata field as a row), its name labels the y-axis.sidein("left", "right")→ feature-aligned, vertical strip;datais 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:
- legend_entries()[source]
Return
{legend_name: {category: color}}contributed to the shared legend, orNoneif this track has no legend.
- 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:
TrackSingle 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:
- 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.
LollipopPlot
- class pymaftools.plot.LollipopPlot.LollipopPlot(protein_name, protein_length, domains, mutations, config=None, domain_label_map=None, mutation_label_map=None)[source]
Bases:
BasePlotLollipopPlot 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.
- 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:
BasePlotStatistical / 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
OncoPlotfor this table.Unifies the entry point so the composite oncoplot is reachable from the same
table.plotaccessor as the statistical plots, e.g.:table.plot.oncoplot(figsize=(15, 10)).main().add_freq().render()
**kwargsare forwarded toOncoPlot(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:
- 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:
PivotStatsPlotPlotting 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_metadataused 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:
PivotStatsPlotPlotting interface for CopyNumberVariationTable objects.
Inherits the shared plotters from
PivotStatsPlot(oncoplot,plot_pca_samples,plot_boxplot_with_annot) and adds CNV-specific visualisations.
SignatureTablePlot
SignatureTablePlot Module
Plotting functionality specific to SignatureTable objects.
Reachable via signature_table.plot.
- class pymaftools.plot.SignatureTablePlot.SignatureTablePlot(pivot_table)[source]
Bases:
PivotStatsPlotPlotting 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
SignatureTableis 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
axis 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:
PivotStatsPlotPlotting 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:
BasePlotPlotting 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
Noneto 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:
- 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:
- 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:
- 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:
- Returns:
ModelPlot – Self, for method chaining.
MethodsPlot
- class pymaftools.plot.MethodsPlot.MethodsPlot[source]
Bases:
BasePlotPlotting 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:
BasePlot
Base plotting class that provides legend management functionality.
- class pymaftools.plot.BasePlot.BasePlot[source]
Bases:
objectBase class for all plotting classes.
Provides common functionality for legend management and color management.
- 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_legendif 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:
- Returns:
BasePlot – Self, to support method chaining.
- get_legend_manager()[source]
Get the legend manager instance.
- Return type:
- Returns:
LegendManager – The legend manager instance.
- clear_legends()[source]
Clear all legends.
- Return type:
- Returns:
BasePlot – Self, to support method chaining.
- get_color_manager()[source]
Get the color manager instance.
- Return type:
- 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:
ColorManager
- class pymaftools.plot.ColorManager.ColorManager[source]
Bases:
objectUnified 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'}}
- get_cmap(name, factor=None, alpha=None)[source]
Retrieve a colormap by name, optionally adjusting brightness and simulated alpha.
- 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:
- Return type:
- 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:
- 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.
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.
- adjust_color_brightness(color, factor)[source]
Adjust the brightness of a color using HLS color space.
- 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:
- 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:
objectManager 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:
- 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:
- 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:
- Returns:
bool – True if name, weight, and style all match.
- register_local_font(font_path)[source]
Register a local
.ttffont file.Skips registration if a font with the same name, weight, and style is already registered.
- register_fonts_from_directory(directory)[source]
Recursively register all
.ttffonts from a directory.- Parameters:
directory (str) – Path to a directory containing font files.
- Raises:
ValueError – If the directory does not exist.
- Return type:
- 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:
- 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:
objectSpecialized 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:
- Returns:
LegendManager – Support method chaining.
- add_legend(legend_name, color_dict)[source]
Add legend information.
- Parameters:
- Return type:
- 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:
- Returns:
LegendManager – Support method chaining.
- clear_legends()[source]
Clear all legends.
- Return type:
- Returns:
LegendManager – Support method chaining.
- 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:
- 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:
- Returns:
LegendManager – Support method chaining.
- update_legend_colors(legend_name, color_updates)[source]
Update colors for the specified legend.
- Parameters:
- Return type:
- Returns:
LegendManager – Support method chaining.
- add_shape_legend(legend_name, shape_dict)[source]
Add shape legend information.
- Parameters:
- Return type:
- Returns:
LegendManager – Support method chaining.
- add_numeric_legend(legend_name, colormap, vmin, vmax, label=None)[source]
Add numeric colorbar legend.
- Parameters:
- Return type:
- 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:
- 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:
- Returns:
LegendManager – Support method chaining.