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=[25, 1, 1, 2], height_ratios=[1, 20], wspace=0.015, hspace=0.02, categorical_columns=[], numeric_columns=[], 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]) – Width ratios for subplot columns
height_ratios (list, default [1, 20]) – Height ratios for subplot rows
wspace (float, default 0.015) – Width spacing between subplots
hspace (float, default 0.02) – Height spacing between subplots
categorical_columns (list, default []) – List of categorical metadata columns to display
numeric_columns (list, default []) – List of numeric metadata columns to display
ytick_fontsize (int, default 10) – Font size for y-axis tick labels
- Return type:
- Returns:
self (OncoPlot) – Returns self for method chaining
- update_layout()[source]
Update the subplot layout based on configured metadata columns.
Creates a GridSpec layout with appropriate dimensions for the main heatmap, TMB bar plot, frequency plot, legend area, and metadata annotations.
- Return type:
- plot_numeric_metadata(annotate=False, annotation_font_size=10, fmt='.2f', cmap='Blues', cmap_dict=None, alpha=1, linewidths=1)[source]
Plot numeric metadata as heatmaps below the main mutation heatmap.
- 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
- Return type:
- Returns:
self (OncoPlot) – Returns self for method chaining
- heatmap_rectangle(show_frame=False, n=3, cmap=None, table=None, width=1, height=1, line_color='white')[source]
Plot mutation heatmap using colored rectangles for each mutation type.
- Parameters:
show_frame (bool, default False) – Whether to show frames around groups of columns
n (int, default 3) – Number of columns per frame group
cmap (dict, optional) – Color mapping for mutation types
table (DataFrame, optional) – Mutation table to plot (defaults to self.pivot_table)
width (float, default 1) – Width of rectangles (0-1)
height (float, default 1) – Height of rectangles (0-1)
line_color (str, default "white") – Color of lines between rectangles
- 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]
- mutation_heatmap(cmap_dict=None, linecolor='white', linewidths=1, show_frame=False, n=3, yticklabels=True, ytick_fontsize=None, show_ylabel=False)[source]
Plot the main mutation heatmap using categorical color coding.
- 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
- 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.
- Parameters:
- Return type:
- Returns:
self (OncoPlot) – Returns self for method chaining
- plot_freq(freq_columns=['freq'], annot_fontsize=9, linewidths=1, xtick_fontsize=9)[source]
Plot frequency heatmap showing mutation frequencies for each gene.
- 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 color mappings Example: {
- ”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
- static plot_color_heatmap(ax, color_matrix, linecolor='white', linewidths=1, xticklabels=False, yticklabels=True, alpha=1.0, width=1.0, height=1.0, ytick_fontsize=10)[source]
Plot a heatmap using colored rectangles based on a color matrix.
- Parameters:
ax (matplotlib.axes.Axes) – The axes to plot on
color_matrix (pd.DataFrame) – DataFrame containing hex color codes for each cell
linecolor (str, default 'white') – Color of lines between cells
linewidths (int, default 1) – Width of lines between cells
xticklabels (bool, default False) – Whether to show x-axis labels
yticklabels (bool, default True) – Whether to show y-axis labels
alpha (float, default 1.0) – Transparency level (0-1)
width (float, default 1.0) – Width of rectangles (0-1)
height (float, default 1.0) – Height of rectangles (0-1)
ytick_fontsize (int, default 10) – Font size for y-axis tick labels
- Returns:
ax (matplotlib.axes.Axes) – The modified axes
- add_xticklabel()[source]
Add x-axis tick labels to the bottom-most subplot.
Finds the subplot in the bottom row and first column, then adds sample names as x-axis tick labels with 90-degree rotation.
- 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.
- 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), width_ratios=[20, 1, 2])[source]
Create a default oncoplot with standard configuration.
This is a convenience method that creates an OncoPlot with commonly used settings and plots the main components (mutation heatmap, frequency plot, TMB bar plot, and legends).
- Parameters:
pivot_table (PivotTable) – The PivotTable instance containing mutation data
figsize (tuple, default (30, 15)) – Figure size (width, height)
width_ratios (list, default [20, 1, 2]) – Width ratios for subplot columns
- Return type:
- Returns:
oncoplot (OncoPlot) – Configured and plotted OncoPlot instance
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=[9, 1], 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)
PivotTablePlot
PivotTablePlot Module
Dedicated plotting functionality for PivotTable objects. Provides a clean interface for various visualization methods while keeping plotting logic separate from the core PivotTable class.
- class pymaftools.plot.PivotTablePlot.PivotTablePlot(pivot_table)[source]
Bases:
BasePlotPlotting functionality for PivotTable objects.
This class provides a clean interface for various visualization methods while keeping plotting logic separate from the core PivotTable class. Inherits from BasePlot to provide legend management and figure saving capabilities.
- 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")
>>> # Direct instantiation (not recommended) >>> plotter = PivotTablePlot(pivot_table) >>> plotter.plot_pca_samples(color_col="subtype")
- 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"} ... )
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:
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'}
- 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'}, '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'}}
- 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}
- 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.04, rect_height=0.03, text_offset_x=0.12, title_offset_y=0.05, item_offset_y=0.035, legend_gap=0.03)[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.