PlotsHelper Module¶
Provides helper functions for creating and managing plots.
- HMB.PlotsHelper.GetRandomCMAPalette(fromAll=False)[source]¶
Get a random color palette from Matplotlib.
- HMB.PlotsHelper.GetCmapColors(cmap, noColors, darkColorsOnly=True, darknessThreshold=0.7)[source]¶
Utility to get a list of unique colors from a matplotlib colormap.
- Parameters:
cmap (str or Colormap) – Name of the colormap or a Colormap object.
noColors (int) – Number of distinct colors to generate.
darkColorsOnly (bool, optional) – Whether to filter out light colors. Default is True.
darknessThreshold (float, optional) – Brightness threshold to classify colors as dark. Default is 0.7.
- Returns:
List of unique RGBA color tuples.
- Return type:
- HMB.PlotsHelper.PlotHeatmap(data, rowLabels, colLabels, title='Heatmap', xlabel='Column', ylabel='Row', cmap='viridis', vmin=None, vmax=None, valueFormat='{:.2f}', annotate=True, fontSize=7, figSize=None, colorbarLabel=None, save=False, savePath=None, fileName=None, dpi=300, display=True, colorbar=True, returnFig=False)[source]¶
Plot a labeled heatmap from a 2D numeric array with flexible display and saving options.
- Parameters:
data (numpy.ndarray) – 2D numeric array to visualize (shape: [n_rows, n_cols]).
rowLabels (list) – Labels for the heatmap rows (y-axis). Length must match data.shape[0].
colLabels (list) – Labels for the heatmap columns (x-axis). Length must match data.shape[1].
title (str) – Plot title. Default is “Heatmap”.
xlabel (str) – Label for x-axis. Default is “Column”.
ylabel (str) – Label for y-axis. Default is “Row”.
cmap (matplotlib.colors.Colormap or str) – Colormap to use for the heatmap. Default is “viridis”.
vmin (float or None) – Minimum data value mapped to the colormap. Default is None.
vmax (float or None) – Maximum data value mapped to the colormap. Default is None.
valueFormat (str) – Format string used to annotate cell values (default: “{:.2f}”).
annotate (bool) – Whether to annotate each cell with its numeric value. Default is True.
fontSize (int) – Font size used for annotations and axis labels. Default is 7.
figSize (tuple) – Figure size in inches. If None a size is inferred from label lengths.
colorbarLabel (str or None) – Label for the colorbar if shown.
save (bool) – Whether to save the plot. Default is False.
savePath (str or pathlib.Path or None) – Path to save the figure. If provided and save is False the function will still save to this path (legacy behavior).
fileName (str or None) – Alternative filename to save the figure when save is True.
dpi (int) – DPI for saving the figure. Default is 300.
display (bool) – Whether to display the plot using plt.show(). Default is True.
colorbar (bool) – Whether to show a colorbar. Default is True.
returnFig (bool) – Whether to return the matplotlib Figure object. Default is False.
- Returns:
The matplotlib figure object if returnFig is True, otherwise None.
- Return type:
matplotlib.figure.Figure or None
Notes
When saving, a PNG sibling file is written alongside the requested format where possible.
The function tolerates NaN/Inf in the data: those cells are not annotated.
Backwards compatibility: if savePath is provided without save, the function will still save to savePath (behavior maintained from prior versions).
Examples
import numpy as np from HMB.PlotsHelper import PlotHeatmap data = np.random.rand(4, 6) PlotHeatmap( data, rowLabels=[f"R{i}" for i in range(4)], colLabels=[f"C{j}" for j in range(6)], title="Example Heatmap", annotate=True, display=True, )
- HMB.PlotsHelper.PlotBarChart(values, labels, title='', ylabel='', save=False, savePath=None, fileName=None, color='tab:blue', colors=None, alpha=0.85, dpi=300, display=True, annotate=False, annotateFormat='{:.4f}', annotateFontSize=None, fontSize=10, figSize=None, rotation=45, returnFig=False)[source]¶
Create a bar chart from values and labels with options to annotate, save, display and return the Figure.
- Parameters:
values (list) – Numeric heights for each bar.
labels (list) – Labels for each bar (x-axis). Must have the same length as values.
title (str) – Plot title. Default is empty.
ylabel (str) – Label for the y-axis.
save (bool) – Whether to save the plot. Default is False.
savePath (str or pathlib.Path or None) – Path to save the figure. Kept for backward compatibility; when provided and save is False the function will still save to this path.
fileName (str or None) – Alternative filename to save the figure when save is True.
color (str or color spec) – Single color for all bars (default: “tab:blue”).
colors (list or None) – Per-bar color list. When provided it overrides color.
alpha (float) – Alpha (opacity) applied to bars. Default is 0.85.
dpi (int) – DPI for saving the figure. Default is 300.
display (bool) – Whether to display the plot using plt.show(). Default is True.
annotate (bool) – Whether to annotate each bar with its numeric value. Default is False.
annotateFormat (str) – Format string used for bar annotations (default: “{:.2f}”).
annotateFontSize (int or None) – Font size for annotations. If None a size is derived from fontSize.
fontSize (int) – Base font size for axis labels and ticks. Default is 10.
figSize (tuple or None) – Figure size in inches. When None a width is inferred from number of bars.
rotation (float) – Rotation applied to x tick labels (degrees). Default is 45.
returnFig (bool) – Whether to return the matplotlib Figure object. Default is False.
- Returns:
The matplotlib figure object if returnFig is True, otherwise None.
- Return type:
matplotlib.figure.Figure or None
Notes
When saving, a PNG sibling file is written alongside other formats where possible.
Backwards compatibility: if savePath is provided without save, the function will still save to savePath (preserving legacy behavior).
Examples
from HMB.PlotsHelper import PlotBarChart PlotBarChart([1.2, 3.4, 2.1], ["A", "B", "C"], title="Counts", annotate=True)
- HMB.PlotsHelper.PlotHorizontalBarChart(values, labels, title='', xlabel='', save=False, savePath=None, fileName=None, color='tab:blue', colors=None, alpha=0.85, dpi=300, display=True, annotate=False, annotateFormat='{:.4f}', annotateFontSize=None, fontSize=10, figSize=None, returnFig=False)[source]¶
Create a horizontal bar chart (bars extend along the x-axis) with labeled y-axis.
This helper creates a horizontal bar chart suitable for categorical counts or scores. It mirrors the options and backwards-compatible saving behavior of PlotBarChart.
- Parameters:
values (list[float]) – Numeric lengths for each horizontal bar.
labels (list[str]) – Labels for each bar shown on the y-axis. Length must match values.
title (str) – Plot title. Default is empty.
xlabel (str) – Label for the x-axis. Default is empty.
save (bool) – Whether to save the plot to disk. Default is False.
savePath (str|Path|None) – Backwards-compatible path to save the figure. When provided and save is False the function still saves to this location (legacy behavior).
fileName (str|None) – Alternative file path used when save is True.
color (Any) – Single color specification for all bars (default “tab:blue”).
colors (list[str]|None) – Per-bar color list that overrides color when provided.
alpha (float) – Opacity applied to bars. Default is 0.85.
dpi (int) – DPI for saved figures. Default is 300.
display (bool) – Whether to call plt.show() after drawing. Default is True.
annotate (bool) – Whether to annotate each bar with its numeric value. Default is False.
annotateFormat (str) – Format string used for annotations. Default is “{:.2f}”.
annotateFontSize (int|None) – Font size for bar annotations. If None a sensible size is derived.
fontSize (int) – Base font size used for axis labels and ticks. Default is 10.
figSize (tuple|None) – Figure size in inches. If None a default is inferred from number of labels.
returnFig (bool) – Whether to return the created matplotlib Figure object. Default is False.
- Returns:
The created Figure when returnFig is True, otherwise None.
- Return type:
matplotlib.figure.Figure or None
Notes
When saving, a PNG sibling file is written alongside other formats when possible.
Backwards compatibility: if savePath is provided without save, the function will still save to savePath (preserving legacy behavior used elsewhere in this module).
Examples
from HMB.PlotsHelper import PlotHorizontalBarChart PlotHorizontalBarChart([10, 5, 7], ["A","B","C"], title="Counts", save=True, fileName="counts.pdf")
- HMB.PlotsHelper.PlotPieChart(values, labels, title='', save=False, savePath=None, fileName=None, autopct='%1.1f%%', explode=None, colors=None, dpi=300, display=True, fontSize=10, figSize=None, returnFig=False)[source]¶
Create a pie chart from categorical values and labels.
This helper draws a pie chart and a right-side legend for readability. The chart accepts options for percentage annotations, slice explosion and custom colors.
- Parameters:
values (list[float]) – Numeric values for pie slices. Length must match labels.
title (str) – Plot title. Default is empty.
save (bool) – Whether to save the plot to disk. Default is False.
savePath (str|Path|None) – Backwards-compatible save path used when provided.
fileName (str|None) – Alternative file path used when save is True.
autopct (str|None) – Format string for slice percentage annotation (e.g. “%1.1f%%”).
explode (list[float]|None) – Per-slice offset fractions for emphasizing slices.
dpi (int) – DPI for saved figures. Default is 300.
display (bool) – Whether to display the figure with plt.show(). Default is True.
fontSize (int) – Font size used in the legend and title. Default is 10.
figSize (tuple|None) – Figure size in inches. Default is a square figure.
returnFig (bool) – Whether to return the created matplotlib Figure object. Default is False.
- Returns:
The created Figure when returnFig is True, otherwise None.
- Return type:
matplotlib.figure.Figure or None
Notes
The function places labels in a legend to the right to keep the pie area uncluttered.
Backwards-compatible saving behavior is preserved (see savePath semantics).
Examples
from HMB.PlotsHelper import PlotPieChart PlotPieChart([30, 70], ["CatA", "CatB"], title="Distribution", save=True, fileName="dist.png")
- HMB.PlotsHelper.PlotLineChart(x, y, title='', xlabel='', ylabel='', save=False, savePath=None, fileName=None, dpi=300, display=True, annotate=False, annotateFormat='{:.2f}', fontSize=10, figSize=None, returnFig=False)[source]¶
Plot a simple line chart connecting (x, y) points.
This helper supports optional annotation of points and standard saving/display options consistent with other plot helpers in this module.
- Parameters:
x (list[float]|None) – X coordinates for points. When None the indices of y are used.
title (str) – Plot title. Default is empty.
xlabel (str) – X-axis label. Default is empty.
ylabel (str) – Y-axis label. Default is empty.
save (bool) – Whether to save the plot to disk. Default is False.
savePath (str|Path|None) – Backwards-compatible save path used when provided.
fileName (str|None) – Alternative file path used when save is True.
dpi (int) – DPI for saved figures. Default is 300.
display (bool) – Whether to display the figure with plt.show(). Default is True.
annotate (bool) – Whether to annotate each point with its value. Default is False.
annotateFormat (str) – Format string used for annotations. Default is “{:.2f}”.
fontSize (int) – Font size used for labels and annotations. Default is 10.
figSize (tuple|None) – Figure size in inches.
returnFig (bool) – Whether to return the created matplotlib Figure object. Default is False.
- Returns:
The created Figure when returnFig is True, otherwise None.
- Return type:
matplotlib.figure.Figure or None
Notes
When x is None the function uses sequential integer indices for the x-axis.
Backwards-compatible saving behavior is preserved.
Examples
from HMB.PlotsHelper import PlotLineChart PlotLineChart(None, [1, 3, 2, 5], title="Signal", annotate=True)
- HMB.PlotsHelper.PlotHistogram(data, bins=20, title='', xlabel='', ylabel='Frequency', save=False, savePath=None, fileName=None, dpi=300, display=True, fontSize=10, figSize=None, returnFig=False)[source]¶
Plot a histogram for 1D numeric data.
This helper draws a histogram with configurable bin count and axis labels. It follows the same saving and display semantics used elsewhere in this module.
- Parameters:
bins (int) – Number of histogram bins. Default is 20.
title (str) – Plot title. Default is empty.
xlabel (str) – X-axis label. Default is empty.
ylabel (str) – Y-axis label. Default is “Frequency”.
save (bool) – Whether to save the plot to disk. Default is False.
savePath (str|Path|None) – Backwards-compatible save path used when provided.
fileName (str|None) – Alternative file path used when save is True.
dpi (int) – DPI for saved figures. Default is 300.
display (bool) – Whether to display the figure with plt.show(). Default is True.
fontSize (int) – Font size used for axis labels. Default is 10.
figSize (tuple|None) – Figure size in inches. Default is a standard wide figure.
returnFig (bool) – Whether to return the created matplotlib Figure object. Default is False.
- Returns:
The created Figure when returnFig is True, otherwise None.
- Return type:
matplotlib.figure.Figure or None
Notes
Backwards-compatible saving behavior is preserved.
Examples
from HMB.PlotsHelper import PlotHistogram PlotHistogram([0.1,0.2,0.2,0.3], bins=10, title="Values")
- HMB.PlotsHelper.GenerateGenericBubblePlot(data, xColumn, yColumn, sizeColumn, colorColumn, outputPath, figureSize=(12, 12), dpiValue=300, title='Bubble Plot', xlabel='X Axis', ylabel='Y Axis', performanceZones=True, concentrationPeak=True)[source]¶
Generate a generic bubble plot from structured data.
- Parameters:
data (pd.DataFrame) – Input data with required columns.
xColumn (str) – Column name for x-axis values.
yColumn (str) – Column name for y-axis categories (will be indexed).
sizeColumn (str) – Column name for bubble size (numeric).
colorColumn (str) – Column name for categorical coloring.
outputPath (str|Path|None) – Path to save the output plot (PNG and PDF).
figureSize (tuple) – Figure dimensions (width, height).
dpiValue (int) – DPI for saved figures.
title (str) – Plot title.
xlabel (str) – X-axis label.
ylabel (str) – Y-axis label.
performanceZones (bool) – Whether to shade low/medium/high performance zones.
concentrationPeak (bool) – Whether to highlight the densest region in x-values.
- Returns:
True if plot was saved successfully, False otherwise.
- Return type:
- HMB.PlotsHelper.PlotApproachesComplexityComparison(approaches, flopsValues, paramsValues, outDir, baseFlops=None, baseParams=None, dpi=300, deviceName='CUDA')[source]¶
Plot a complexity comparison chart for different approaches. This function creates a dual-axis line chart comparing FLOPs and Parameters for various approaches. It annotates each point with values and percentage deltas from a base approach when provided. The plot is saved to the specified output directory with a filename that includes the device type for clarity.
- Parameters:
flopsValues (list[float]) – Corresponding FLOPs values (in GigaFLOPs) for each approach.
paramsValues (list[float]) – Corresponding Parameters values (in Millions) for each approach.
outDir (str|Path) – Directory where the plot will be saved.
baseFlops (float|None) – Optional base FLOPs value for calculating percentage deltas. If None, deltas are not calculated.
baseParams (float|None) – Optional base Parameters value for calculating percentage deltas. If None, deltas are not calculated.
dpi (int) – DPI for the saved plot image.
deviceName (str) – Human-readable name for the device type to include in the title (default is “CUDA”).
- HMB.PlotsHelper.PlotClassDistribution(labelsArray, outPath, title=None, maxVertical=15, exportPng=True, colormap='viridis', fontSize='small', orientation='auto', dpi=300, figureSize=None, paretoThreshold=80.0, save=True, display=False)[source]¶
Plot the distribution of class labels as a bar chart with cumulative percentage overlay.
This function computes the frequency of each unique class label, sorts them in descending order, and visualizes the distribution as a bar chart. It also overlays a line plot showing the cumulative percentage of samples covered by the classes. A marker and annotation indicate where the cumulative percentage crosses a specified Pareto threshold (e.g., 80%), highlighting the number of classes that contribute to that coverage. The plot can be oriented vertically or horizontally based on the number of classes or an explicit override. The resulting figure is saved to the specified path in PDF format, with an optional PNG export for raster use cases.
- Parameters:
labelsArray (array-like) – Sequence of class labels to analyze and plot.
outPath (Path) – Path to save the resulting plot (PDF and optionally PNG).
title (str, optional) – Title for the plot. Default is None (no title).
maxVertical (int, optional) – Maximum number of classes to use vertical bars before switching to horizontal. Default is 15.
exportPng (bool, optional) – Whether to also export a PNG version of the plot. Default is True.
colormap (str, optional) – Matplotlib colormap name to use for the bars and line. Default is “viridis”.
fontSize (str or int, optional) – Font size for tick labels and annotations. Default is “small”.
orientation (str, optional) – “auto”, “vertical”, or “horizontal” to control bar orientation. Default is “auto”.
dpi (int, optional) – Dots-per-inch for raster outputs (PNG) and fallback for PDF. Default is 300.
figureSize (tuple, optional) – Optional figure size override as (width, height) in inches. Default is None (automatic sizing).
paretoThreshold (float, optional) – Percent threshold to mark on cumulative curve (e.g., 80.0). Default is 80.0.
save (bool, optional) – Whether to save the generated figure to outPath. Default is True for backward compatibility.
display (bool, optional) – Whether to display the figure using plt.show(). Default is False to avoid blocking scripts.
- HMB.PlotsHelper.SaveMatplotlibFigure(path, fig=None, dpi=720, show=False, exportPdf=True, exportPng=True, otherExtensions=None)[source]¶
Save a matplotlib figure to disk in both PDF and PNG formats with tight layout.
This helper function attempts to save the provided figure (or the current figure if none is provided) to disk using a base path. It saves in PDF format for vector quality and PNG format for raster use cases, applying tight layout to ensure all elements are visible. The function also ensures that the target directory exists before saving. Optionally, it can display the figure after saving.
- Parameters:
path (str|Path) – The base file path to save the figure. The function will derive PDF and PNG paths from this base.
fig (matplotlib.figure.Figure, optional) – The figure to save. If None, the current active figure will be used. Default is None.
dpi (int, optional) – Dots-per-inch for the saved figures. Default is 720 for high-quality output.
show (bool, optional) – Whether to display the figure after saving. Default is False.
exportPdf (bool, optional) – Whether to save the figure in PDF format. Default is True.
exportPng (bool, optional) – Whether to save the figure in PNG format. Default is True.
otherExtensions (list[str], optional) – Additional file extensions to save (e.g., [“svg”, “eps”]). Default is None.
Notes
- The function will attempt to save in PDF format first, and if that fails (e.g., due to issues with the
figure content), it will still attempt to save a PNG version.
- The target directory will be created if it does not exist, ensuring that the save operation does not
fail due to missing directories.
- Tight layout is applied to the figure before saving to prevent clipping of labels and other elements,
but it will avoid calling tight_layout if the figure was created with constrained_layout to prevent layout warnings.
- HMB.PlotsHelper.GenerateDistributionCountFigure(countDictionary, classList, outputDirectory, splitList=None, dpi=720, fileName='Figure', xLabel='Dataset Split', yLabel='Number of Images', title='Class Distribution Counts')[source]¶
Generate a bar chart figure showing the distribution of class counts across different dataset splits.
- Parameters:
countDictionary (dict) – A dictionary mapping keys of the form “SplitClass” to integer counts, e.g., {“TrainCat”: 100, “TestDog”: 50}.
classList (list) – A list of class names to include in the plot, e.g., [“Cat”, “Dog”, “Bird”].
outputDirectory (str|Path) – The directory where the output figure files will be saved.
splitList (list, optional) – A list of dataset split names to include in the plot, e.g., [“Train”, “Test”, “Val”]. If None, defaults to [“Train”, “Test”, “Val”].
dpi (int, optional) – Dots-per-inch for the saved figure. Default is 720 for high-quality output.
fileName (str, optional) – Base name for the output figure files (without extension). Default is “Figure”.
xLabel (str, optional) – Label for the x-axis. Default is “Dataset Split”.
yLabel (str, optional) – Label for the y-axis. Default is “Number of Images”.
title (str, optional) – Title for the figure. Default is “Class Distribution Counts”.
Notes
The function will create a grouped bar chart where each group corresponds to a dataset split, and each bar within a group corresponds to a class. The height of each bar represents the count of images for that class in that split.
The function saves the figure in both PDF and PNG formats in the specified output directory.