Plotting Utilities

This module provides comprehensive plotting and visualization tools for TBsim simulation results.

Main Plots Module

tbsim.utils.plots.plot_results(flat_results, keywords=None, exclude=('None',), n_cols=5, dark=True, cmap='tab20', heightfold=2, style='default', savefig=True, outdir=None, metric_filter=None, title='', shared_legend=True, legend_position='upper right')[source]

Visualize simulation outputs from multiple scenarios in a structured grid layout.

Parameters:
  • flat_results (dict) –

    Nested dictionary of the form: {

    ’Scenario A’: {‘metric1’: Result, ‘metric2’: Result, …}, ‘Scenario B’: {‘metric1’: Result, ‘metric2’: Result, …}, …

    } Each Result must have timevec and values attributes representing time series data for a given metric.

  • keywords (list[str], optional) – If provided, only plot metrics containing at least one of these substrings.

  • exclude (tuple[str], optional) – Substrings of metric names to skip. Default is (‘15’,).

  • n_cols (int, optional) – Number of columns in the plot grid. Default is 5.

  • dark (bool, optional) – If True (default), uses a gray-on-dark theme for improved contrast.

  • cmap (str, optional) – Name of a matplotlib colormap (e.g., ‘viridis’, ‘tab10’). Default is ‘tab20’.

  • heightfold (int, optional) – Height multiplier per row of subplots. Default is 3.

  • style (str, optional) – Matplotlib style to apply. Defaults to ‘default’. Falls back to ‘default’ if not found.

  • savefig (bool, optional) – If True (default), saves the figure as a PNG file with a timestamped filename.

  • outdir (str, optional) – Directory to save the figure. If None, saves in the current script’s directory under ‘results’.

  • metric_filter (list[str], optional) – List of metric names to plot. If provided, only these metrics will be plotted.

  • shared_legend (bool, optional) – If True, creates a single shared legend for all subplots. Default is True.

  • legend_position (str, optional) – Position for the shared legend. Options: ‘upper right’, ‘upper left’, ‘lower right’, ‘lower left’, ‘center’, etc. Default is ‘upper right’.

Returns:

The figure is displayed and also saved as a PNG with a timestamped filename.

Return type:

None

Workflow:
  1. Collects all metric names across scenarios.

  2. Filters metrics based on keywords and exclude.

  3. Lays out subplots based on the number of metrics and specified n_cols.

  4. Iterates over each metric and plots it across all scenarios.

  5. Adjusts appearance (background, style, gridlines, labels).

  6. Saves the figure as ‘scenarios_<timestamp>.png’.

Example

>>> results = {
...     'BCG': {
...         'incidence': Result(timevec=[0, 1, 2], values=[0.1, 0.2, 0.3]),
...         'mortality': Result(timevec=[0, 1, 2], values=[0.05, 0.07, 0.1])
...     },
...     'TPT': {
...         'incidence': Result(timevec=[0, 1, 2], values=[0.08, 0.15, 0.25]),
...         'mortality': Result(timevec=[0, 1, 2], values=[0.03, 0.05, 0.08])
...     }
... }
>>> plot_results(results, keywords=['incidence'], n_cols=2, dark=False, cmap='viridis')

NOTE:

This plotting utility assumes results have already been flattened, such that each scenario maps to a dictionary of named time series outputs. This structure enables clean side-by-side comparisons of metrics like incidence or mortality across scenarios in a single visual layout.

FLATTENING RESULTS:

This line:
>>> results['Any_Name'] = sim.results.flatten()       <-- The name will be used for the series name

Converts the simulation’s time series outputs into a flat dictionary or DataFrame. Makes results easier to compare across scenarios (e.g., plotting incidence over time). The results dictionary now maps scenario names to their flattened outputs: {

‘BCG’: <results>, ‘TPT’: <results>, …

}

tbsim.utils.plots.plot_combined(flat_results, keywords=None, exclude=('None',), n_cols=7, dark=True, cmap='plasma', heightfold=2, style='default', savefig=True, outdir=None, plot_type='line', marker_styles=None, alpha=0.85, grid_alpha=0.4, title_fontsize=10, legend_fontsize=7, line_width=0.3, marker_size=2, markeredgewidth=0.2, grid_linewidth=0.5, spine_linewidth=0.5, label_fontsize=6, tick_fontsize=6, filter=None, title='', shared_legend=True, legend_position='upper left')[source]

Visualize simulation outputs from multiple scenarios in a structured grid layout.

Parameters:
  • flat_results (dict) –

    Nested dictionary of the form: {

    ’Scenario A’: {‘metric1’: Result, ‘metric2’: Result, …}, ‘Scenario B’: {‘metric1’: Result, ‘metric2’: Result, …}, …

    } Each Result must have timevec and values attributes representing time series data for a given metric.

  • keywords (list[str], optional) – If provided, only plot metrics containing at least one of these substrings.

  • exclude (tuple[str], optional) – Substrings of metric names to skip. Default is (‘15’,).

  • n_cols (int, optional) – Number of columns in the plot grid. Default is 5.

  • dark (bool, optional) – If True (default), uses a gray-on-dark theme for improved contrast.

  • cmap (str, optional) – Name of a matplotlib colormap (e.g., ‘viridis’, ‘tab10’, ‘plasma’). Default is ‘plasma’.

  • heightfold (int, optional) – Height multiplier per row of subplots. Default is 3.

  • style (str, optional) – Matplotlib style to apply. Defaults to ‘default’. Falls back to ‘default’ if not found.

  • savefig (bool, optional) – If True (default), saves the figure as a PNG file with a timestamped filename.

  • outdir (str, optional) – Directory to save the figure. If None, saves in the current script’s directory under ‘results’.

  • plot_type (str, optional) – Type of plot to use for each metric (‘line’ or ‘scatter’). Default is ‘line’.

  • marker_styles (list[str], optional) – List of marker styles for scatter plots. Defaults to a preset list.

  • alpha (float, optional) – Transparency for lines/markers. Default is 0.85.

  • grid_alpha (float, optional) – Transparency for grid lines. Default is 0.4.

  • title_fontsize (int, optional) – Font size for subplot titles. Default is 10.

  • legend_fontsize (int, optional) – Font size for legends. Default is 6.

  • line_width (float, optional) – Line width for line plots. Default is 0.2.

  • marker_size (int, optional) – Marker size for scatter and line plots. Default is 3.

  • markeredgewidth (float, optional) – Marker edge width. Default is 0.5.

  • grid_linewidth (float, optional) – Grid line width. Default is 0.5.

  • spine_linewidth (float, optional) – Axis spine line width. Default is 0.5.

  • label_fontsize (int, optional) – Font size for axis labels. Default is 9.

  • tick_fontsize (int, optional) – Font size for axis tick labels. Default is 5.

  • shared_legend (bool, optional) – If True, creates a single shared legend for all subplots. Default is True.

  • legend_position (str, optional) – Position for the shared legend. Options: ‘upper right’, ‘upper left’, ‘lower right’, ‘lower left’, ‘center’, etc. Default is ‘upper right’.

Returns:

The figure is displayed and also saved as a PNG with a timestamped filename.

Return type:

None

Workflow:
  1. Collects all metric names across scenarios.

  2. Filters metrics based on keywords and exclude.

  3. Lays out subplots based on the number of metrics and specified n_cols.

  4. Iterates over each metric and plots it across all scenarios.

  5. Adjusts appearance (background, style, gridlines, labels).

  6. Saves the figure as ‘scenarios_<timestamp>.png’.

Example

>>> results = {
...     'BCG': {
...         'incidence': Result(timevec=[0, 1, 2], values=[0.1, 0.2, 0.3]),
...         'mortality': Result(timevec=[0, 1, 2], values=[0.05, 0.07, 0.1])
...     },
...     'TPT': {
...         'incidence': Result(timevec=[0, 1, 2], values=[0.08, 0.15, 0.25]),
...         'mortality': Result(timevec=[0, 1, 2], values=[0.03, 0.05, 0.08])
...     }
... }
>>> plot_results(results, keywords=['incidence'], n_cols=2, dark=False, cmap='viridis', plot_type='scatter')

NOTE:

This plotting utility assumes results have already been flattened, such that each scenario maps to a dictionary of named time series outputs. This structure enables clean side-by-side comparisons of metrics like incidence or mortality across scenarios in a single visual layout.

FLATTENING RESULTS:

This line:
>>> results['Any_Name'] = sim.results.flatten()       <-- The name will be used for the series name

Converts the simulation’s time series outputs into a flat dictionary or DataFrame. Makes results easier to compare across scenarios (e.g., plotting incidence over time). The results dictionary now maps scenario names to their flattened outputs: {

‘BCG’: <results>, ‘TPT’: <results>, …

}

cmap:

‘Accent’, ‘Accent_r’, ‘Blues’, ‘Blues_r’, ‘BrBG’, ‘BrBG_r’, ‘BuGn’, ‘BuGn_r’, ‘BuPu’, ‘BuPu_r’, ‘CMRmap’, ‘CMRmap_r’, ‘Dark2’, ‘Dark2_r’, ‘GnBu’, ‘GnBu_r’, ‘Grays’, ‘Grays_r’, ‘Greens’, ‘Greens_r’, ‘Greys’, ‘Greys_r’, ‘OrRd’, ‘OrRd_r’, ‘Oranges’, ‘Oranges_r’, ‘PRGn’, ‘PRGn_r’, ‘Paired’, ‘Paired_r’, ‘Pastel1’, ‘Pastel1_r’, ‘Pastel2’, ‘Pastel2_r’, ‘PiYG’, ‘PiYG_r’, ‘PuBu’, ‘PuBuGn’, ‘PuBuGn_r’, ‘PuBu_r’, ‘PuOr’, ‘PuOr_r’, ‘PuRd’, ‘PuRd_r’, ‘Purples’, ‘Purples_r’, ‘RdBu’, ‘RdBu_r’, ‘RdGy’, ‘RdGy_r’, ‘RdPu’, ‘RdPu_r’, ‘RdYlBu’, ‘RdYlBu_r’, ‘RdYlGn’, ‘RdYlGn_r’, ‘Reds’, ‘Reds_r’, ‘Set1’, ‘Set1_r’, ‘Set2’, ‘Set2_r’, ‘Set3’, ‘Set3_r’, ‘Spectral’, ‘Spectral_r’, ‘Wistia’, ‘Wistia_r’, ‘YlGn’, ‘YlGnBu’, ‘YlGnBu_r’, ‘YlGn_r’, ‘YlOrBr’, ‘YlOrBr_r’, ‘YlOrRd’, ‘YlOrRd_r’, ‘afmhot’, ‘afmhot_r’, ‘alpine’, ‘autumn’, ‘autumn_r’, ‘banded’, ‘berlin’, ‘berlin_r’, ‘bi’, ‘binary’, ‘binary_r’, ‘bone’, ‘bone_r’, ‘brg’, ‘brg_r’, ‘bwr’, ‘bwr_r’, ‘cividis’, ‘cividis_r’, ‘cool’, ‘cool_r’, ‘coolwarm’, ‘coolwarm_r’, ‘copper’, ‘copper_r’, ‘crest’, ‘crest_r’, ‘cubehelix’, ‘cubehelix_r’, ‘flag’, ‘flag_r’, ‘flare’, ‘flare_r’, ‘gist_earth’, ‘gist_earth_r’, ‘gist_gray’, ‘gist_gray_r’, ‘gist_grey’, ‘gist_grey_r’, ‘gist_heat’, ‘gist_heat_r’, ‘gist_ncar’, ‘gist_ncar_r’, ‘gist_rainbow’, ‘gist_rainbow_r’, ‘gist_stern’, ‘gist_stern_r’, ‘gist_yarg’, ‘gist_yarg_r’, ‘gist_yerg’, ‘gist_yerg_r’, ‘gnuplot’, ‘gnuplot2’, ‘gnuplot2_r’, ‘gnuplot_r’, ‘gray’, ‘gray_r’, ‘grey’, ‘grey_r’, ‘hot’, ‘hot_r’, ‘hsv’, ‘hsv_r’, ‘icefire’, ‘icefire_r’, ‘inferno’, ‘inferno_r’, ‘jet’, ‘jet_r’, ‘magma’, ‘magma_r’, ‘mako’, ‘mako_r’, ‘managua’, ‘managua_r’, ‘nipy_spectral’, ‘nipy_spectral_r’, ‘ocean’, ‘ocean_r’, ‘orangeblue’, ‘parula’, ‘pink’, ‘pink_r’, ‘plasma’, ‘plasma_r’, ‘prism’, ‘prism_r’, ‘rainbow’, ‘rainbow_r’, ‘rocket’, ‘rocket_r’, ‘sciris-alpine’, ‘sciris-banded’, ‘sciris-bi’, ‘sciris-orangeblue’, ‘sciris-parula’, ‘sciris-turbo’, ‘seismic’, ‘seismic_r’, ‘spring’, ‘spring_r’, ‘summer’, ‘summer_r’, ‘tab10’, ‘tab10_r’, ‘tab20’, ‘tab20_r’, ‘tab20b’, ‘tab20b_r’, ‘tab20c’, ‘tab20c_r’, ‘terrain’, ‘terrain_r’, ‘turbo’, ‘turbo_r’, ‘twilight’, ‘twilight_r’, ‘twilight_shifted’, ‘twilight_shifted_r’, ‘vanimo’, ‘vanimo_r’, ‘viridis’, ‘viridis_r’, ‘vlag’, ‘vlag_r’, ‘winter’, ‘winter_r’

tbsim.utils.plots.out_to(outdir)[source]
class tbsim.utils.plots.FILTERS[source]

Bases: object

important_metrics = ['tb_prevalence_active', 'tb_prevalence', 'cum_deaths']

Key Features

  • Result Visualization: Plot simulation outputs and trends

  • Comparative Analysis: Compare multiple simulation scenarios

  • Custom Plotting: Flexible plotting with customizable parameters

  • Export Capabilities: Save plots in various formats

  • Interactive Plots: Dynamic visualizations for exploration

Usage Examples

Basic result plotting:

from tbsim.utils.plots import plot_results

# Plot basic simulation results
plot_results(sim_results)

# Plot with custom parameters
plot_results(
    sim_results,
    title='TB Simulation Results',
    save_path='results.png'
)

Combined result plotting:

from tbsim.utils.plots import plot_combined

# Plot multiple simulation results
plot_combined(
    [results1, results2, results3],
    labels=['Baseline', 'Intervention A', 'Intervention B']
)

Custom plotting:

from tbsim.utils.plots import create_custom_plot

# Create custom visualization
fig = create_custom_plot(
    data=sim_results,
    plot_type='incidence_trends',
    style='seaborn'
)

Available Plot Types

Time Series Plots
  • Incidence trends over time

  • Prevalence changes

  • Treatment outcomes

Comparative Plots
  • Multiple scenario comparison

  • Intervention effectiveness

  • Parameter sensitivity

Distribution Plots
  • Age distribution of cases

  • Geographic distribution

  • Risk factor distributions

Export Options
  • PNG, PDF, SVG formats

  • High-resolution outputs

  • Publication-ready figures

For advanced plotting and analysis, see the TBsim Analyzers module.