ergodic_insurance.visualization package

Submodules

ergodic_insurance.visualization.annotations module

Annotation and labeling utilities for visualizations.

This module provides utilities for adding professional annotations, labels, and callouts to plots with smart placement and leader line routing.

add_value_labels(ax: Axes, bars, format_func=None, fontsize: int = 9, va: str = 'bottom', ha: str = 'center', offset: float = 0.01, color: str | None = None, bold: bool = False) None[source]

Add value labels to bar chart.

Adds formatted value labels on top of or inside bars in a bar chart.

Parameters:
  • ax (Axes) – Matplotlib axes

  • bars – Bar container from ax.bar()

  • format_func – Optional function to format values

  • fontsize (int) – Font size for labels

  • va (str) – Vertical alignment (‘bottom’, ‘center’, ‘top’)

  • ha (str) – Horizontal alignment (‘left’, ‘center’, ‘right’)

  • offset (float) – Vertical offset as fraction of y-range

  • color (Optional[str]) – Text color (default: gray)

  • bold (bool) – Whether to make text bold

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> bars = ax.bar(range(5), [10, 20, 15, 25, 30])
>>> add_value_labels(ax, bars)
add_trend_annotation(ax: Axes, x_pos: float, y_pos: float, trend: float, period: str = 'YoY', fontsize: int = 10) None[source]

Add trend annotation with arrow.

Adds a trend annotation showing percentage change with an up/down arrow.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x_pos (float) – X position for annotation

  • y_pos (float) – Y position for annotation

  • trend (float) – Trend value (e.g., 0.15 for 15% increase)

  • period (str) – Period description (e.g., “YoY”, “MoM”)

  • fontsize (int) – Font size for annotation

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> add_trend_annotation(ax, 0.8, 0.9, 0.15, "YoY")
add_callout(ax: Axes, text: str, xy: Tuple[float, float], xytext: Tuple[float, float], fontsize: int = 9, color: str | None = None, arrow_color: str | None = None, bbox_props: dict | None = None) None[source]

Add a callout annotation with arrow.

Creates a professional callout annotation with customizable styling.

Parameters:
Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> add_callout(ax, "Peak value", xy=(2, 4), xytext=(2.5, 4.5))
add_benchmark_line(ax: Axes, value: float, label: str, color: str | None = None, linestyle: str = '--', linewidth: float = 1.5, fontsize: int = 9, position: str = 'right') None[source]

Add a horizontal benchmark line with label.

Draws a horizontal reference line with an integrated label.

Parameters:
  • ax (Axes) – Matplotlib axes

  • value (float) – Y-value for benchmark line

  • label (str) – Label for the benchmark

  • color (Optional[str]) – Line color

  • linestyle (str) – Line style

  • linewidth (float) – Line width

  • fontsize (int) – Font size for label

  • position (str) – Label position (‘left’, ‘right’, ‘center’)

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot(range(10), np.random.randn(10))
>>> add_benchmark_line(ax, 0, "Average", color="red")
add_shaded_region(ax: Axes, x_start: float, x_end: float, label: str | None = None, color: str | None = None, alpha: float = 0.2) None[source]

Add a shaded vertical region.

Creates a shaded vertical band to highlight a specific time period or range.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x_start (float) – Start x-coordinate

  • x_end (float) – End x-coordinate

  • label (Optional[str]) – Optional label for the region

  • color (Optional[str]) – Fill color

  • alpha (float) – Transparency

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot(range(10), np.random.randn(10))
>>> add_shaded_region(ax, 3, 6, label="Recession", color="gray")
add_data_source(fig, source: str, x: float = 0.99, y: float = 0.01, fontsize: int = 8, color: str | None = None) None[source]

Add data source attribution.

Adds a data source note to the figure, typically at the bottom right.

Parameters:
  • fig – Matplotlib figure

  • source (str) – Source text (e.g., “Source: Company Reports”)

  • x (float) – X position in figure coordinates

  • y (float) – Y position in figure coordinates

  • fontsize (int) – Font size

  • color (Optional[str]) – Text color

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> add_data_source(fig, "Source: Internal Analysis")
add_footnote(fig, text: str, x: float = 0.5, y: float = 0.02, fontsize: int = 8, color: str | None = None) None[source]

Add footnote to figure.

Adds a footnote or explanatory text to the bottom of the figure.

Parameters:
  • fig – Matplotlib figure

  • text (str) – Footnote text

  • x (float) – X position in figure coordinates

  • y (float) – Y position in figure coordinates

  • fontsize (int) – Font size

  • color (Optional[str]) – Text color

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> add_footnote(fig, "* Preliminary data subject to revision")
class AnnotationBox(text: str, position: Tuple[float, float], width: float = 0.15, height: float = 0.08, priority: int = 50) None[source]

Bases: object

Container for annotation box properties.

text

Annotation text

position

(x, y) position in data coordinates

width

Box width in axes fraction

height

Box height in axes fraction

priority

Priority for placement (higher = more important)

text: str
position: Tuple[float, float]
width: float = 0.15
height: float = 0.08
priority: int = 50
get_bounds() Tuple[float, float, float, float][source]

Get bounding box (x, y, width, height).

Return type:

Tuple[float, float, float, float]

overlaps(other: AnnotationBox, margin: float = 0.01) bool[source]

Check if this box overlaps with another.

Parameters:
  • other (AnnotationBox) – Another annotation box

  • margin (float) – Additional margin to consider

Return type:

bool

Returns:

True if boxes overlap

class SmartAnnotationPlacer(ax: Axes)[source]

Bases: object

Smart placement system for annotations without overlaps.

placed_annotations: List[AnnotationBox]
used_colors: Set[str]
annotation_cache: Dict[str, Tuple[float, float]]
find_best_position(target_point: Tuple[float, float], text: str, priority: int = 50, preferred_quadrant: str | None = None) Tuple[float, float][source]

Find best position for annotation near target point.

Parameters:
  • target_point (Tuple[float, float]) – Point to annotate (data coordinates)

  • text (str) – Annotation text

  • priority (int) – Annotation priority

  • preferred_quadrant (Optional[str]) – Preferred quadrant (‘NE’, ‘NW’, ‘SE’, ‘SW’)

Return type:

Tuple[float, float]

Returns:

Best position in axes fraction coordinates

add_smart_callout(text: str, target_point: Tuple[float, float], fontsize: int = 9, priority: int = 50, preferred_quadrant: str | None = None, color: str | None = None, arrow_color: str | None = None) None[source]

Add callout with smart placement.

Parameters:
  • text (str) – Callout text

  • target_point (Tuple[float, float]) – Point to annotate (data coordinates)

  • fontsize (int) – Font size

  • priority (int) – Annotation priority (higher = more important)

  • preferred_quadrant (Optional[str]) – Preferred quadrant for placement

  • color (Optional[str]) – Text color

  • arrow_color (Optional[str]) – Arrow color

Return type:

None

add_smart_annotations(annotations: List[Dict[str, Any]], fontsize: int = 9) None[source]

Add multiple annotations with smart placement.

Parameters:
  • annotations (List[Dict[str, Any]]) – List of annotation dicts with ‘text’, ‘point’, ‘priority’, ‘color’

  • fontsize (int) – Font size for all annotations

Return type:

None

Examples

>>> placer = SmartAnnotationPlacer(ax)
>>> annotations = [
...     {'text': 'Peak', 'point': (2, 4), 'priority': 80, 'color': 'green'},
...     {'text': 'Valley', 'point': (5, 1), 'priority': 60, 'color': 'red'}
... ]
>>> placer.add_smart_annotations(annotations)
create_leader_line(ax: Axes, start: Tuple[float, float], end: Tuple[float, float], style: str = 'curved', color: str | None = None, linewidth: float = 1.0, alpha: float = 0.7) None[source]

Create a leader line with intelligent routing.

Parameters:
  • ax (Axes) – Matplotlib axes

  • start (Tuple[float, float]) – Start point (data coordinates)

  • end (Tuple[float, float]) – End point (data coordinates)

  • style (str) – Line style (‘straight’, ‘curved’, ‘elbow’)

  • color (Optional[str]) – Line color

  • linewidth (float) – Line width

  • alpha (float) – Line transparency

Return type:

None

auto_annotate_peaks_valleys(ax: Axes, x_data: ndarray, y_data: ndarray, n_peaks: int = 3, n_valleys: int = 2, peak_color: str | None = None, valley_color: str | None = None, fontsize: int = 9, placer: SmartAnnotationPlacer | None = None) SmartAnnotationPlacer[source]

Automatically annotate peaks and valleys in data.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x_data (ndarray) – X coordinates

  • y_data (ndarray) – Y coordinates

  • n_peaks (int) – Number of peaks to annotate

  • n_valleys (int) – Number of valleys to annotate

  • peak_color (Optional[str]) – Color for peak annotations

  • valley_color (Optional[str]) – Color for valley annotations

  • fontsize (int) – Font size

  • placer (Optional[SmartAnnotationPlacer]) – Existing SmartAnnotationPlacer to use (creates new if None)

Return type:

SmartAnnotationPlacer

Returns:

The SmartAnnotationPlacer instance used

ergodic_insurance.visualization.batch_plots module

Batch processing and scenario comparison visualizations.

This module provides visualization functions for batch simulation results, scenario comparisons, and sensitivity analyses.

plot_scenario_comparison(aggregated_results: Any, metrics: List[str] | None = None, figsize: Tuple[float, float] = (14, 8), save_path: str | None = None) Figure[source]

Create comprehensive scenario comparison visualization.

Compares multiple scenarios across different metrics with bar charts highlighting the best performer for each metric.

Parameters:
  • aggregated_results (Any) – AggregatedResults object from batch processing

  • metrics (Optional[List[str]]) – List of metrics to compare (default: key metrics)

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Matplotlib figure with scenario comparisons

Examples

>>> from ergodic_insurance.batch_processor import AggregatedResults
>>> results = AggregatedResults(batch_results)
>>> fig = plot_scenario_comparison(results, metrics=["mean_growth_rate"])
plot_sensitivity_heatmap(aggregated_results: Any, metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (10, 8), save_path: str | None = None) Figure[source]

Create sensitivity analysis heatmap.

Visualizes sensitivity of outcomes to parameter changes using a horizontal bar chart color-coded by impact direction.

Parameters:
  • aggregated_results (Any) – AggregatedResults with sensitivity analysis

  • metric (str) – Metric to visualize

  • figsize (Tuple[float, float]) – Figure size

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Matplotlib figure with sensitivity analysis

plot_parameter_sweep_3d(aggregated_results: Any, param1: str, param2: str, metric: str = 'mean_growth_rate', height: int = 600, save_path: str | None = None) Figure[source]

Create 3D surface plot for parameter sweep results.

Visualizes how a metric varies across two parameter dimensions using an interactive 3D scatter plot.

Parameters:
  • aggregated_results (Any) – AggregatedResults from grid search

  • param1 (str) – First parameter name

  • param2 (str) – Second parameter name

  • metric (str) – Metric to plot on z-axis

  • height (int) – Figure height in pixels

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Plotly figure with 3D parameter sweep

plot_scenario_convergence(batch_results: List[Any], metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (12, 6), save_path: str | None = None) Figure[source]

Plot convergence of metric across scenarios.

Shows how a metric converges as more scenarios are processed, with execution time distribution.

Parameters:
  • batch_results (List[Any]) – List of BatchResult objects

  • metric (str) – Metric to track

  • figsize (Tuple[float, float]) – Figure size

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Matplotlib figure with convergence analysis

plot_parallel_scenarios(batch_results: List[Any], metrics: List[str], figsize: Tuple[float, float] = (12, 8), normalize: bool = True) Figure[source]

Create parallel coordinates plot for scenario comparison.

Visualizes multiple scenarios across multiple metrics using parallel coordinates for comprehensive comparison.

Parameters:
  • batch_results (List[Any]) – List of BatchResult objects

  • metrics (List[str]) – List of metrics to include

  • figsize (Tuple[float, float]) – Figure size

  • normalize (bool) – Whether to normalize metrics to [0, 1]

Return type:

Figure

Returns:

Matplotlib figure with parallel coordinates

ergodic_insurance.visualization.core module

Core visualization utilities and constants.

This module provides the foundational elements for visualization including WSJ-style color palettes, formatters, and base configuration settings.

set_wsj_style()[source]

Set matplotlib to use WSJ-style formatting.

This function applies Wall Street Journal aesthetic styling to matplotlib plots including font choices, spine visibility, grid settings, and colors.

format_currency(value: float, decimals: int = 0, abbreviate: bool = False) str[source]

Format value as currency.

Parameters:
  • value (float) – Numeric value to format

  • decimals (int) – Number of decimal places

  • abbreviate (bool) – If True, use K/M/B notation for large numbers

Return type:

str

Returns:

Formatted string (e.g., “$1,000” or “$1K” if abbreviate=True)

Examples

>>> format_currency(1000)
'$1,000'
>>> format_currency(1500000, abbreviate=True)
'$1.5M'
>>> format_currency(2500.50, decimals=2)
'$2,500.50'
format_percentage(value: float, decimals: int = 1) str[source]

Format value as percentage.

Parameters:
  • value (float) – Numeric value (0.05 = 5%)

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted string (e.g., “5.0%”)

Examples

>>> format_percentage(0.05)
'5.0%'
>>> format_percentage(0.1234, decimals=2)
'12.34%'
class WSJFormatter[source]

Bases: object

Formatter for WSJ-style axis labels.

This class provides static methods for formatting axis values in various styles consistent with Wall Street Journal publication standards.

currency_formatter()[source]

Format axis values as currency

currency()[source]

Format value as currency (shortened method name)

percentage_formatter()[source]

Format axis values as percentage

percentage()[source]

Format value as percentage (shortened method name)

number()[source]

Format large numbers with appropriate suffix

millions_formatter()[source]

Format axis values in millions

static currency_formatter(x, pos)[source]

Format axis values as currency.

Parameters:
  • x – The value to format

  • pos – The position (unused but required by matplotlib)

Returns:

Formatted currency string

static currency(x: float, decimals: int = 1) str[source]

Format value as currency (shortened method name).

Parameters:
  • x (float) – The value to format

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted currency string with appropriate suffix

static percentage_formatter(x, pos)[source]

Format axis values as percentage.

Parameters:
  • x – The value to format

  • pos – The position (unused but required by matplotlib)

Returns:

Formatted percentage string

static percentage(x: float, decimals: int = 1) str[source]

Format value as percentage (shortened method name).

Parameters:
  • x (float) – The value to format (0.05 = 5%)

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted percentage string

static number(x: float, decimals: int = 2) str[source]

Format large numbers with appropriate suffix.

Parameters:
  • x (float) – The value to format

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted number string with K/M/B/T suffix

Examples

>>> WSJFormatter.number(1500000)
'1.50M'
>>> WSJFormatter.number(2500)
'2.50K'
static millions_formatter(x, pos)[source]

Format axis values in millions.

Parameters:
  • x – The value to format

  • pos – The position (unused but required by matplotlib)

Returns:

Value formatted as millions with M suffix

ergodic_insurance.visualization.executive_plots module

Executive-level visualization functions.

This module provides high-level visualization functions for executive reporting including loss distributions, return period curves, and insurance layer diagrams.

safe_tight_layout()[source]

Apply tight_layout with warning suppression.

plot_loss_distribution(losses: ndarray | DataFrame, title: str = 'Loss Distribution', bins: int = 50, show_metrics: bool = True, var_levels: List[float] | None = None, figsize: Tuple[int, int] = (12, 6), show_stats: bool = False, log_scale: bool = False, use_factory: bool = False, theme: Any | None = None) Figure[source]

Create WSJ-style loss distribution plot.

Creates a two-panel visualization showing loss distribution histogram and Q-Q plot for normality assessment.

Parameters:
  • losses (Union[ndarray, DataFrame]) – Array of loss values or DataFrame with ‘amount’ column

  • title (str) – Plot title

  • bins (int) – Number of histogram bins

  • show_metrics (bool) – Whether to show VaR/TVaR lines

  • var_levels (Optional[List[float]]) – VaR confidence levels to show (default: [0.95, 0.99])

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_stats (bool) – Whether to show statistics

  • log_scale (bool) – Whether to use log scale

  • use_factory (bool) – Whether to use new visualization factory if available

  • theme (Optional[Any]) – Optional theme to use with factory

Return type:

Figure

Returns:

Matplotlib figure with distribution plots

Examples

>>> losses = np.random.lognormal(10, 2, 1000)
>>> fig = plot_loss_distribution(losses, title="Annual Loss Distribution")
plot_return_period_curve(losses: ndarray | DataFrame, return_periods: ndarray | None = None, scenarios: Dict[str, ndarray] | None = None, title: str = 'Return Period Curves', figsize: Tuple[int, int] = (10, 6), confidence_level: float = 0.95, show_grid: bool = True) Figure[source]

Create WSJ-style return period curve.

Visualizes the relationship between return periods and loss magnitudes, commonly used in catastrophe modeling and risk assessment.

Parameters:
  • losses (Union[ndarray, DataFrame]) – Loss amounts (array or DataFrame)

  • return_periods (Optional[ndarray]) – Array of return periods (years), optional

  • scenarios (Optional[Dict[str, ndarray]]) – Optional dict of scenario names to loss arrays

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • confidence_level (float) – Confidence level for bands

  • show_grid (bool) – Whether to show grid

Return type:

Figure

Returns:

Matplotlib figure with return period curve

Examples

>>> losses = np.random.lognormal(10, 2, 1000)
>>> fig = plot_return_period_curve(losses)
plot_insurance_layers(layers: List[Dict[str, float]] | DataFrame, total_limit: float | None = None, title: str = 'Insurance Program Structure', figsize: Tuple[int, int] = (10, 6), losses: ndarray | DataFrame | None = None, loss_data: ndarray | DataFrame | None = None, show_expected_loss: bool = False) Figure[source]

Create WSJ-style insurance layer visualization.

Visualizes insurance program structure with layer attachments, limits, and premium distribution in a two-panel display.

Parameters:
  • layers (Union[List[Dict[str, float]], DataFrame]) – List of layer dictionaries or DataFrame with ‘attachment’, ‘limit’ columns

  • total_limit (Optional[float]) – Total program limit (calculated from layers if not provided)

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • losses (Union[ndarray, DataFrame, None]) – Optional loss data for overlay

  • loss_data (Union[ndarray, DataFrame, None]) – Alias for losses parameter

  • show_expected_loss (bool) – Whether to show expected loss line

Return type:

Figure

Returns:

Matplotlib figure with layer structure and premium distribution

Examples

>>> layers = [
...     {"attachment": 0, "limit": 5e6, "premium": 0.015},
...     {"attachment": 5e6, "limit": 10e6, "premium": 0.008},
... ]
>>> fig = plot_insurance_layers(layers)
plot_roe_ruin_frontier(results: Dict[float, DataFrame] | DataFrame, company_sizes: List[float] | None = None, title: str = 'ROE-Ruin Efficient Frontier', figsize: Tuple[int, int] = (12, 8), highlight_sweet_spots: bool = True, show_optimal_zones: bool = True, export_dpi: int | None = None, log_scale_y: bool = True, grid: bool = True, annotations: bool = True, color_scheme: List[str] | None = None) Figure[source]

Create ROE-Ruin efficient frontier visualization.

Visualizes the Pareto frontier showing trade-offs between Return on Equity (ROE) and Ruin Probability for different company sizes. This helps executives understand optimal insurance purchasing decisions.

Parameters:
  • results (Union[Dict[float, DataFrame], DataFrame]) – Either a dict of company_size (float) -> optimization results DataFrame, or a single DataFrame with ‘company_size’ column

  • company_sizes (Optional[List[float]]) – List of company sizes to plot (e.g., [1e6, 1e7, 1e8]) If None, will use all available sizes in results

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • highlight_sweet_spots (bool) – Whether to highlight knee points on curves

  • show_optimal_zones (bool) – Whether to show shaded optimal zones

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print, None for screen)

  • log_scale_y (bool) – Whether to use log scale for ruin probability axis

  • grid (bool) – Whether to show grid lines

  • annotations (bool) – Whether to show annotations for key points

  • color_scheme (Optional[List[str]]) – List of colors for different company sizes

Return type:

Figure

Returns:

Matplotlib figure with ROE-Ruin efficient frontier plots

Raises:

ValueError – If results format is invalid or no data available

Examples

>>> # With dictionary of results
>>> results = {
...     1e6: pd.DataFrame({'roe': [0.1, 0.15, 0.2],
...                       'ruin_prob': [0.05, 0.02, 0.01]}),
...     1e7: pd.DataFrame({'roe': [0.08, 0.12, 0.18],
...                       'ruin_prob': [0.03, 0.015, 0.008]})
... }
>>> fig = plot_roe_ruin_frontier(results)
>>> # With single DataFrame
>>> df = pd.DataFrame({
...     'company_size': [1e6, 1e6, 1e7, 1e7],
...     'roe': [0.1, 0.15, 0.08, 0.12],
...     'ruin_prob': [0.05, 0.02, 0.03, 0.015]
... })
>>> fig = plot_roe_ruin_frontier(df)
plot_ruin_cliff(retention_range: Tuple[float, float] | None = None, n_points: int = 50, company_size: float = 10000000, simulation_data: Dict[str, Any] | None = None, title: str = 'The Ruin Cliff: Retention vs Failure Risk', figsize: Tuple[int, int] = (14, 8), show_inset: bool = True, show_warnings: bool = True, show_3d_effect: bool = True, export_dpi: int | None = None) Figure[source]

Create dramatic ruin cliff visualization with 3D effects.

Visualizes the relationship between insurance retention (deductible) levels and ruin probability, highlighting the “cliff edge” where risk dramatically increases. Features 3D-style gradient effects and warning zones.

Parameters:
  • retention_range (Optional[Tuple[float, float]]) – Tuple of (min, max) retention values in dollars. Default: (10_000, 10_000_000)

  • n_points (int) – Number of points to calculate along retention axis

  • company_size (float) – Company asset size for scaling retention levels

  • simulation_data (Optional[Dict[str, Any]]) – Optional pre-computed simulation results with keys: ‘retentions’, ‘ruin_probs’, ‘confidence_intervals’

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_inset (bool) – Whether to show zoomed inset of critical region

  • show_warnings (bool) – Whether to show warning callouts and annotations

  • show_3d_effect (bool) – Whether to add 3D gradient background effects

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with ruin cliff visualization

Examples

>>> # Basic usage with synthetic data
>>> fig = plot_ruin_cliff()
>>> # With custom retention range
>>> fig = plot_ruin_cliff(retention_range=(5000, 5_000_000))
>>> # With pre-computed simulation data
>>> data = {
...     'retentions': np.logspace(4, 7, 50),
...     'ruin_probs': np.array([...]),
... }
>>> fig = plot_ruin_cliff(simulation_data=data)

Notes

The visualization uses a log scale for retention values to show the full range from small to large deductibles. The cliff edge is detected using derivative analysis to find the steepest point of increase in ruin probability.

plot_simulation_architecture(title: str = 'Simulation Architecture Flow', figsize: Tuple[int, int] = (14, 8), export_dpi: int | None = None, show_icons: bool = True) Figure[source]

Create simulation architecture flow diagram.

Visualizes the data flow from parameters through simulation to insights using a clean flowchart style with boxes and arrows.

Parameters:
  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

  • show_icons (bool) – Whether to show icons in boxes

Return type:

Figure

Returns:

Matplotlib figure with architecture diagram

Examples

>>> fig = plot_simulation_architecture()
>>> fig.savefig("architecture.png", dpi=150)
plot_sample_paths(simulation_data: Dict[str, Any] | None = None, n_paths: int = 5, short_horizon: int = 10, long_horizon: int = 100, company_size: float = 10000000, title: str = 'Sample Path Visualization', figsize: Tuple[int, int] = (14, 8), show_failures: bool = True, export_dpi: int | None = None) Figure[source]

Create sample path visualization showing trajectory evolution.

Displays representative paths over short and long time horizons, highlighting survivors vs failed companies with transparency effects.

Parameters:
  • simulation_data (Optional[Dict[str, Any]]) – Optional pre-computed simulation results with paths

  • n_paths (int) – Number of paths to display (default 5)

  • short_horizon (int) – Years for short-term view (default 10)

  • long_horizon (int) – Years for long-term view (default 100)

  • company_size (float) – Starting company size

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_failures (bool) – Whether to highlight failed paths

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with dual-panel path visualization

Examples

>>> fig = plot_sample_paths(n_paths=5)
>>> fig.savefig("sample_paths.png", dpi=150)
plot_optimal_coverage_heatmap(optimization_results: Dict[str, Any] | None = None, company_sizes: List[float] | None = None, title: str = 'Optimal Coverage Heatmap', figsize: Tuple[int, int] = (16, 6), show_contours: bool = True, export_dpi: int | None = None) Figure[source]

Create optimal insurance coverage heatmap for different company sizes.

Visualizes the relationship between retention, limit, and growth rate using color intensity to show optimal configurations.

Parameters:
  • optimization_results (Optional[Dict[str, Any]]) – Optional pre-computed optimization data

  • company_sizes (Optional[List[float]]) – List of company sizes (default: [1e6, 1e7, 1e8])

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_contours (bool) – Whether to show contour lines

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with 3-panel heatmap

Examples

>>> fig = plot_optimal_coverage_heatmap(
...     company_sizes=[1e6, 1e7, 1e8]
... )
>>> fig.savefig("coverage_heatmap.png", dpi=150)
plot_sensitivity_tornado(sensitivity_data: Dict[str, float] | None = None, baseline_value: float | None = None, title: str = 'Sensitivity Analysis - Tornado Chart', figsize: Tuple[int, int] = (10, 8), show_percentages: bool = True, export_dpi: int | None = None) Figure[source]

Create tornado chart showing parameter sensitivity analysis.

Visualizes the impact of parameter variations on key metrics using horizontal bars sorted by influence magnitude.

Parameters:
  • sensitivity_data (Optional[Dict[str, float]]) – Dict of parameter names to impact values

  • baseline_value (Optional[float]) – Baseline metric value for reference

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_percentages (bool) – Whether to show percentage labels

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with tornado chart

Examples

>>> sensitivity = {
...     "Premium Rate": 0.15,
...     "Loss Frequency": -0.12,
...     "Loss Severity": -0.08,
... }
>>> fig = plot_sensitivity_tornado(sensitivity)
plot_robustness_heatmap(robustness_data: ndarray | None = None, frequency_range: Tuple[float, float] | None = None, severity_range: Tuple[float, float] | None = None, title: str = 'Insurance Program Robustness Analysis', figsize: Tuple[int, int] = (10, 8), show_reference: bool = True, export_dpi: int | None = None) Figure[source]

Create robustness heatmap showing stability across parameter variations.

Visualizes how optimal coverage changes with variations in loss frequency and severity parameters.

Parameters:
  • robustness_data (Optional[ndarray]) – 2D array of stability metrics

  • frequency_range (Optional[Tuple[float, float]]) – Tuple of (min, max) frequency variation (default 0.7-1.3)

  • severity_range (Optional[Tuple[float, float]]) – Tuple of (min, max) severity variation (default 0.7-1.3)

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_reference (bool) – Whether to show reference point at 100%/100%

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with robustness heatmap

Examples

>>> fig = plot_robustness_heatmap()
>>> fig.savefig("robustness.png", dpi=150)
plot_premium_multiplier(optimization_results: Dict[float, Dict[str, Any]] | None = None, company_sizes: List[float] | None = None, title: str = 'Premium Multiplier Analysis', figsize: Tuple[int, int] = (12, 8), show_confidence: bool = True, show_reference_lines: bool = True, show_annotations: bool = True, export_dpi: int | None = None) Figure[source]

Create premium multiplier analysis visualization.

Visualizes the optimal premium as a multiple of expected loss for different company sizes, demonstrating why premiums 2-5× expected losses are optimal from an ergodic perspective.

Parameters:
  • optimization_results (Optional[Dict[float, Dict[str, Any]]]) – Dict of company_size -> optimization data containing ‘expected_loss’, ‘optimal_premium’, and optionally ‘confidence_bounds’ for each company size

  • company_sizes (Optional[List[float]]) – List of company sizes to analyze (default: [1e6, 1e7, 1e8])

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_confidence (bool) – Whether to show confidence intervals

  • show_reference_lines (bool) – Whether to show horizontal reference lines

  • show_annotations (bool) – Whether to add explanatory annotations

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with premium multiplier analysis

Examples

>>> results = {
...     1e6: {'expected_loss': 50000, 'optimal_premium': 150000},
...     1e7: {'expected_loss': 200000, 'optimal_premium': 600000}
... }
>>> fig = plot_premium_multiplier(results)
plot_breakeven_timeline(simulation_results: Dict[float, Dict[str, Any]] | None = None, company_sizes: List[float] | None = None, time_horizon: int = 30, title: str = 'Insurance Break-even Timeline Analysis', figsize: Tuple[int, int] = (14, 8), show_percentiles: bool = True, show_breakeven_markers: bool = True, export_dpi: int | None = None) Figure[source]

Create break-even timeline visualization.

Shows when the cumulative benefits of optimal insurance exceed the cumulative excess premiums paid (premiums above expected losses), demonstrating the long-term value proposition.

Parameters:
  • simulation_results (Optional[Dict[float, Dict[str, Any]]]) – Dict of company_size -> simulation data containing ‘cumulative_benefit’, ‘cumulative_excess_premium’, and optionally percentile data

  • company_sizes (Optional[List[float]]) – List of company sizes to analyze (default: [1e6, 1e7, 1e8])

  • time_horizon (int) – Years to simulate (default: 30)

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_percentiles (bool) – Whether to show 25th/75th percentile bands

  • show_breakeven_markers (bool) – Whether to mark break-even points

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with break-even timeline analysis

Examples

>>> results = {
...     1e6: {
...         'cumulative_benefit': np.array([...]),
...         'cumulative_excess_premium': np.array([...])
...     }
... }
>>> fig = plot_breakeven_timeline(results)

ergodic_insurance.visualization.export module

Export utilities for saving visualizations in various formats.

This module provides functions to export visualizations to different formats including high-resolution images, PDFs, and web-ready formats.

save_figure(fig: Figure | Figure, filename: str, dpi: int = 300, bbox_inches: str = 'tight', transparent: bool = False, formats: List[str] | None = None, metadata: Dict[str, Any] | None = None) List[str][source]

Save figure in multiple formats.

Saves a matplotlib or plotly figure to disk in one or more formats with professional quality settings.

Parameters:
  • fig (Union[Figure, Figure]) – Matplotlib Figure or Plotly Figure to save

  • filename (str) – Base filename (without extension)

  • dpi (int) – Resolution for raster formats

  • bbox_inches (str) – How to handle figure bounds

  • transparent (bool) – Whether to use transparent background

  • formats (Optional[List[str]]) – List of formats to save (default: [‘png’])

  • metadata (Optional[Dict[str, Any]]) – Optional metadata to embed in files

Return type:

List[str]

Returns:

List of saved file paths

Raises:

ValueError – If unsupported format is requested

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> save_figure(fig, "my_plot", formats=["png", "pdf"])
['my_plot.png', 'my_plot.pdf']
save_for_publication(fig: Figure, filename: str, width: float = 7, height: float = 5, dpi: int = 600) str[source]

Save figure with publication-quality settings.

Exports a figure with settings optimized for academic publication or professional reports.

Parameters:
  • fig (Figure) – Matplotlib figure

  • filename (str) – Output filename (without extension)

  • width (float) – Figure width in inches

  • height (float) – Figure height in inches

  • dpi (int) – Resolution (600 for print quality)

Return type:

str

Returns:

Path to saved PDF file

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> save_for_publication(fig, "figure_1")
'figure_1.pdf'
save_for_presentation(fig: Figure | Figure, filename: str, width: int = 1920, height: int = 1080) str[source]

Save figure optimized for presentations.

Exports a figure with settings optimized for PowerPoint or other presentation software.

Parameters:
  • fig (Union[Figure, Figure]) – Matplotlib or Plotly figure

  • filename (str) – Output filename (without extension)

  • width (int) – Width in pixels

  • height (int) – Height in pixels

Return type:

str

Returns:

Path to saved file

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> save_for_presentation(fig, "slide_1")
'slide_1.png'
save_for_web(fig: Figure | Figure, filename: str, optimize: bool = True) Dict[str, str][source]

Save figure optimized for web display.

Creates web-optimized versions of the figure including responsive formats and multiple resolutions.

Parameters:
  • fig (Union[Figure, Figure]) – Matplotlib or Plotly figure

  • filename (str) – Base filename (without extension)

  • optimize (bool) – Whether to optimize file sizes

Return type:

Dict[str, str]

Returns:

Dictionary of format to file path mappings

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> files = save_for_web(fig, "chart")
>>> print(files)
{'thumbnail': 'chart_thumb.png', 'full': 'chart.png', 'svg': 'chart.svg'}
batch_export(figures: Dict[str, Figure | Figure], output_dir: str, formats: List[str] | None = None, dpi: int = 300) Dict[str, List[str]][source]

Export multiple figures in batch.

Saves multiple figures to a directory with consistent settings.

Parameters:
  • figures (Dict[str, Union[Figure, Figure]]) – Dictionary mapping names to figures

  • output_dir (str) – Output directory path

  • formats (Optional[List[str]]) – List of formats to save each figure

  • dpi (int) – Resolution for raster formats

Return type:

Dict[str, List[str]]

Returns:

Dictionary mapping figure names to lists of saved files

Examples

>>> fig1, ax1 = plt.subplots()
>>> fig2, ax2 = plt.subplots()
>>> figures = {"chart1": fig1, "chart2": fig2}
>>> batch_export(figures, "output/", formats=["png"])

ergodic_insurance.visualization.figure_factory module

Figure factory for creating standardized plots with consistent styling.

This module provides a factory class for creating various types of plots with automatic styling, spacing, and formatting applied consistently.

class FigureFactory(style_manager: StyleManager | None = None, theme: Theme = Theme.DEFAULT, auto_apply: bool = True)[source]

Bases: object

Factory for creating standardized figures with consistent styling.

This class provides methods to create various types of plots with automatic application of themes, consistent formatting, and proper spacing.

Example

>>> factory = FigureFactory(theme=Theme.PRESENTATION)
>>> fig, ax = factory.create_line_plot(
...     x_data=[1, 2, 3, 4],
...     y_data=[10, 20, 15, 25],
...     title="Revenue Growth",
...     x_label="Quarter",
...     y_label="Revenue ($M)"
... )
>>> # Create multiple subplots
>>> fig, axes = factory.create_subplots(
...     rows=2, cols=2,
...     size_type="large",
...     subplot_titles=["Q1", "Q2", "Q3", "Q4"]
... )
create_figure(size_type: str = 'medium', orientation: str = 'landscape', dpi_type: str = 'screen', title: str | None = None) Tuple[Figure, Axes][source]

Create a basic figure with styling applied.

Parameters:
  • size_type (str) – Size preset (small, medium, large, blog, technical, presentation)

  • orientation (str) – Figure orientation (landscape or portrait)

  • dpi_type (str) – DPI type (screen, web, print)

  • title (Optional[str]) – Optional figure title

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_subplots(rows: int = 1, cols: int = 1, size_type: str = 'large', dpi_type: str = 'screen', title: str | None = None, subplot_titles: List[str] | None = None, **kwargs) Tuple[Figure, Axes | ndarray][source]

Create subplots with consistent styling.

Parameters:
  • rows (int) – Number of subplot rows

  • cols (int) – Number of subplot columns

  • size_type (str) – Size preset

  • dpi_type (str) – DPI type

  • title (Optional[str]) – Main figure title

  • subplot_titles (Optional[List[str]]) – Titles for each subplot

  • **kwargs – Additional arguments for plt.subplots

Return type:

Tuple[Figure, Union[Axes, ndarray]]

Returns:

Tuple of (figure, axes array)

create_line_plot(x_data: List | ndarray | Series, y_data: List | ndarray | Series | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', show_legend: bool = True, show_grid: bool = True, markers: bool = False, **kwargs) Tuple[Figure, Axes][source]

Create a line plot with automatic formatting.

Parameters:
  • x_data (Union[List, ndarray, Series]) – X-axis data

  • y_data (Union[List, ndarray, Series, Dict[str, Union[List, ndarray]]]) – Y-axis data (can be multiple series as dict)

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • labels (Optional[List[str]]) – Series labels for legend

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • show_legend (bool) – Whether to show legend

  • show_grid (bool) – Whether to show grid

  • markers (bool) – Whether to add markers to lines

  • **kwargs – Additional arguments for plot

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_bar_plot(categories: List | ndarray, values: List | ndarray | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_values: bool = False, value_format: str = '.1f', **kwargs) Tuple[Figure, Axes][source]

Create a bar plot with automatic formatting.

Parameters:
  • categories (Union[List, ndarray]) – Category labels

  • values (Union[List, ndarray, Dict[str, Union[List, ndarray]]]) – Values to plot (can be multiple series as dict)

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • labels (Optional[List[str]]) – Series labels for legend

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • orientation (str) – Bar orientation (vertical or horizontal)

  • show_values (bool) – Whether to show value labels on bars

  • value_format (str) – Format string for value labels

  • **kwargs – Additional arguments for bar plot

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_scatter_plot(x_data: List | ndarray, y_data: List | ndarray, title: str | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', colors: List | ndarray | None = None, sizes: List | ndarray | None = None, labels: List[str] | None = None, show_colorbar: bool = False, **kwargs) Tuple[Figure, Axes][source]

Create a scatter plot with automatic formatting.

Parameters:
  • x_data (Union[List, ndarray]) – X-axis data

  • y_data (Union[List, ndarray]) – Y-axis data

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • colors (Union[List, ndarray, None]) – Optional colors for points (for continuous coloring)

  • sizes (Union[List, ndarray, None]) – Optional sizes for points

  • labels (Optional[List[str]]) – Optional labels for points

  • show_colorbar (bool) – Whether to show colorbar when colors provided

  • **kwargs – Additional arguments for scatter

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_histogram(data: List | ndarray | Series, title: str | None = None, x_label: str | None = None, y_label: str = 'Frequency', bins: int | str = 'auto', size_type: str = 'medium', dpi_type: str = 'screen', show_statistics: bool = False, show_kde: bool = False, **kwargs) Tuple[Figure, Axes][source]

Create a histogram with automatic formatting.

Parameters:
  • data (Union[List, ndarray, Series]) – Data to plot

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (str) – Y-axis label

  • bins (Union[int, str]) – Number of bins or method

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • show_statistics (bool) – Whether to show mean/median lines

  • show_kde (bool) – Whether to overlay KDE

  • **kwargs – Additional arguments for hist

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_heatmap(data: ndarray | DataFrame, title: str | None = None, x_labels: List[str] | None = None, y_labels: List[str] | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', cmap: str = 'RdBu_r', show_values: bool = True, value_format: str = '.2f', **kwargs) Tuple[Figure, Axes][source]

Create a heatmap with automatic formatting.

Parameters:
  • data (Union[ndarray, DataFrame]) – 2D data array or DataFrame

  • title (Optional[str]) – Plot title

  • x_labels (Optional[List[str]]) – Labels for x-axis

  • y_labels (Optional[List[str]]) – Labels for y-axis

  • x_label (Optional[str]) – X-axis title

  • y_label (Optional[str]) – Y-axis title

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • cmap (str) – Colormap name

  • show_values (bool) – Whether to show values in cells

  • value_format (str) – Format string for cell values

  • **kwargs – Additional arguments for imshow

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_box_plot(data: List[List] | Dict[str, List] | DataFrame, title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_means: bool = True, **kwargs) Tuple[Figure, Axes][source]

Create a box plot with automatic formatting.

Parameters:
  • data (Union[List[List], Dict[str, List], DataFrame]) – Data for box plot (list of lists, dict, or DataFrame)

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • labels (Optional[List[str]]) – Labels for each box

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • orientation (str) – Plot orientation (vertical or horizontal)

  • show_means (bool) – Whether to show mean markers

  • **kwargs – Additional arguments for boxplot

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

format_axis_currency(ax: Axes, axis: str = 'y', abbreviate: bool = True, decimals: int = 0) None[source]

Format axis labels as currency.

Parameters:
  • ax (Axes) – Matplotlib axes

  • axis (str) – Which axis to format (x or y)

  • abbreviate (bool) – Whether to abbreviate large numbers

  • decimals (int) – Number of decimal places

Return type:

None

format_axis_percentage(ax: Axes, axis: str = 'y', decimals: int = 0) None[source]

Format axis labels as percentages.

Parameters:
  • ax (Axes) – Matplotlib axes

  • axis (str) – Which axis to format (x or y)

  • decimals (int) – Number of decimal places

Return type:

None

add_annotations(ax: Axes, x: float, y: float, text: str, arrow: bool = True, offset: Tuple[float, float] = (10, 10), **kwargs) None[source]

Add styled annotation to plot.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x (float) – X coordinate

  • y (float) – Y coordinate

  • text (str) – Annotation text

  • arrow (bool) – Whether to show arrow

  • offset (Tuple[float, float]) – Text offset from point

  • **kwargs – Additional arguments for annotate

Return type:

None

save_figure(fig: Figure, filename: str, output_type: str = 'web', **kwargs) None[source]

Save figure with appropriate DPI settings.

Parameters:
  • fig (Figure) – Figure to save

  • filename (str) – Output filename

  • output_type (str) – Output type (screen, web, print)

  • **kwargs – Additional arguments for savefig

Return type:

None

ergodic_insurance.visualization.improved_tower_plot module

Improved insurance tower visualization with stacked bar chart and smart annotations.

plot_insurance_tower(layers: List[Dict[str, float]] | DataFrame, title: str = 'Insurance Tower Structure', figsize: Tuple[int, int] = (10, 12), min_height_for_text: float = 0.02, color_scheme: str = 'viridis', show_summary: bool = True, log_scale: bool = True) Figure[source]

Create an improved insurance tower visualization with stacked bars and smart annotations.

Parameters:
  • layers (Union[List[Dict[str, float]], DataFrame]) – List of layer dictionaries or DataFrame with columns: - attachment: Layer attachment point - limit: Layer limit - premium: Premium amount or rate - expected_loss (optional): Expected loss for the layer - rate_on_line (optional): Rate on line for the layer

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • min_height_for_text (float) – Minimum relative height (as fraction of total) to display text inside bar

  • color_scheme (str) – Matplotlib colormap name

  • show_summary (bool) – Whether to show summary statistics

  • log_scale (bool) – Use logarithmic scale for y-axis to better show layers of different sizes

Return type:

Figure

Returns:

Matplotlib figure with improved tower visualization

ergodic_insurance.visualization.interactive_plots module

Interactive visualization functions using Plotly.

This module provides functions for creating interactive dashboards and visualizations for Monte Carlo simulations and analysis results.

create_interactive_dashboard(results: Dict[str, Any] | DataFrame, title: str = 'Monte Carlo Simulation Dashboard', height: int = 600, show_distributions: bool = False) Figure[source]

Create interactive Plotly dashboard with WSJ styling.

Creates a comprehensive interactive dashboard with multiple panels showing simulation results, convergence, and risk metrics.

Parameters:
  • results (Union[Dict[str, Any], DataFrame]) – Dictionary with simulation results or DataFrame

  • title (str) – Dashboard title

  • height (int) – Dashboard height in pixels

  • show_distributions (bool) – Whether to show distribution plots

Return type:

Figure

Returns:

Plotly figure with interactive dashboard

Examples

>>> results = {
...     "growth_rates": np.random.normal(0.05, 0.02, 1000),
...     "losses": np.random.lognormal(10, 2, 1000),
...     "metrics": {"var_95": 100000, "var_99": 150000}
... }
>>> fig = create_interactive_dashboard(results)
create_time_series_dashboard(data: DataFrame, value_col: str, time_col: str = 'date', title: str = 'Time Series Analysis', height: int = 600, show_forecast: bool = False) Figure[source]

Create interactive time series visualization.

Creates an interactive time series plot with optional forecast bands and statistical overlays.

Parameters:
  • data (DataFrame) – DataFrame with time series data

  • value_col (str) – Name of value column

  • time_col (str) – Name of time column

  • title (str) – Plot title

  • height (int) – Plot height in pixels

  • show_forecast (bool) – Whether to show forecast bands

Return type:

Figure

Returns:

Plotly figure with time series visualization

create_correlation_heatmap(data: DataFrame, title: str = 'Correlation Matrix', height: int = 600, show_values: bool = True) Figure[source]

Create interactive correlation heatmap.

Creates an interactive heatmap showing correlations between variables with customizable color scheme and annotations.

Parameters:
  • data (DataFrame) – DataFrame with variables to correlate

  • title (str) – Plot title

  • height (int) – Plot height in pixels

  • show_values (bool) – Whether to show correlation values

Return type:

Figure

Returns:

Plotly figure with correlation heatmap

create_risk_dashboard(risk_metrics: Dict[str, Any], title: str = 'Risk Analytics Dashboard', height: int = 800) Figure[source]

Create comprehensive risk analytics dashboard.

Creates a multi-panel dashboard showing various risk metrics and distributions for comprehensive risk assessment.

Parameters:
  • risk_metrics (Dict[str, Any]) – Dictionary containing risk metrics and data

  • title (str) – Dashboard title

  • height (int) – Dashboard height in pixels

Return type:

Figure

Returns:

Plotly figure with risk dashboard

ergodic_insurance.visualization.style_manager module

Style management for consistent visualization across all reports.

This module provides centralized style configuration for all visualizations, including color palettes, fonts, figure sizes, and DPI settings.

class Theme(*values)[source]

Bases: Enum

Available visualization themes.

DEFAULT = 'default'
COLORBLIND = 'colorblind'
PRESENTATION = 'presentation'
MINIMAL = 'minimal'
PRINT = 'print'
class ColorPalette(primary: str = '#0080C7', secondary: str = '#003F5C', accent: str = '#FF9800', warning: str = '#D32F2F', success: str = '#4CAF50', neutral: str = '#666666', background: str = '#FFFFFF', text: str = '#000000', grid: str = '#E0E0E0', series: List[str] = <factory>) None[source]

Bases: object

Color palette configuration for a theme.

primary

Main color for primary elements

secondary

Secondary color for supporting elements

accent

Accent color for highlights

warning

Color for warnings or negative values

success

Color for positive values or success states

neutral

Neutral gray tones

background

Background color

text

Text color

grid

Grid line color

series

List of colors for multiple data series

primary: str = '#0080C7'
secondary: str = '#003F5C'
accent: str = '#FF9800'
warning: str = '#D32F2F'
success: str = '#4CAF50'
neutral: str = '#666666'
background: str = '#FFFFFF'
text: str = '#000000'
grid: str = '#E0E0E0'
series: List[str]
class FontConfig(family: str = 'Arial', size_base: int = 11, size_title: int = 14, size_label: int = 12, size_tick: int = 10, size_legend: int = 10, weight_normal: str = 'normal', weight_bold: str = 'bold') None[source]

Bases: object

Font configuration for a theme.

family

Font family name

size_base

Base font size

size_title

Title font size

size_label

Label font size

size_tick

Tick label font size

size_legend

Legend font size

weight_normal

Normal font weight

weight_bold

Bold font weight

family: str = 'Arial'
size_base: int = 11
size_title: int = 14
size_label: int = 12
size_tick: int = 10
size_legend: int = 10
weight_normal: str = 'normal'
weight_bold: str = 'bold'
class FigureConfig(size_small: Tuple[float, float] = (6, 4), size_medium: Tuple[float, float] = (8, 6), size_large: Tuple[float, float] = (12, 8), size_blog: Tuple[float, float] = (8, 6), size_technical: Tuple[float, float] = (10, 8), size_presentation: Tuple[float, float] = (10, 7.5), dpi_screen: int = 100, dpi_web: int = 150, dpi_print: int = 300) None[source]

Bases: object

Figure size and DPI configuration.

size_small

Small figure size (width, height) in inches

size_medium

Medium figure size

size_large

Large figure size

size_blog

Blog-optimized size (8x6)

size_technical

Technical appendix size (10x8)

size_presentation

Presentation slide size

dpi_screen

DPI for screen display

dpi_web

DPI for web publishing (150)

dpi_print

DPI for print quality (300)

size_small: Tuple[float, float] = (6, 4)
size_medium: Tuple[float, float] = (8, 6)
size_large: Tuple[float, float] = (12, 8)
size_blog: Tuple[float, float] = (8, 6)
size_technical: Tuple[float, float] = (10, 8)
size_presentation: Tuple[float, float] = (10, 7.5)
dpi_screen: int = 100
dpi_web: int = 150
dpi_print: int = 300
class GridConfig(show_grid: bool = True, grid_alpha: float = 0.3, grid_linewidth: float = 0.5, spine_top: bool = False, spine_right: bool = False, spine_bottom: bool = True, spine_left: bool = True, spine_linewidth: float = 0.8, tick_major_width: float = 0.8, tick_minor_width: float = 0.4) None[source]

Bases: object

Grid and axis configuration.

show_grid

Whether to show grid lines

grid_alpha

Grid transparency

grid_linewidth

Grid line width

spine_top

Show top spine

spine_right

Show right spine

spine_bottom

Show bottom spine

spine_left

Show left spine

spine_linewidth

Spine line width

tick_major_width

Major tick width

tick_minor_width

Minor tick width

show_grid: bool = True
grid_alpha: float = 0.3
grid_linewidth: float = 0.5
spine_top: bool = False
spine_right: bool = False
spine_bottom: bool = True
spine_left: bool = True
spine_linewidth: float = 0.8
tick_major_width: float = 0.8
tick_minor_width: float = 0.4
class StyleManager(theme: Theme = Theme.DEFAULT, config_path: str | Path | None = None, custom_colors: Dict[str, str] | None = None, custom_fonts: Dict[str, Any] | None = None)[source]

Bases: object

Manages visualization styles and themes.

This class provides centralized style management for all visualizations, supporting multiple themes, custom configurations, and style inheritance.

Example

>>> style_mgr = StyleManager()
>>> style_mgr.set_theme(Theme.PRESENTATION)
>>> style_mgr.apply_style()
>>> # Create plots with consistent styling
>>> # Or with custom configuration
>>> style_mgr = StyleManager(config_path="custom_style.yaml")
>>> style_mgr.apply_style()
themes: Dict[Theme, Dict[str, Any]]
set_theme(theme: Theme) None[source]

Set the current theme.

Parameters:

theme (Theme) – Theme to activate

Return type:

None

get_theme_config(theme: Theme | None = None) Dict[str, Any][source]

Get configuration for a theme.

Parameters:

theme (Optional[Theme]) – Theme to get config for (defaults to current)

Return type:

Dict[str, Any]

Returns:

Theme configuration dictionary

get_colors() ColorPalette[source]

Get current color palette.

Return type:

ColorPalette

Returns:

Current theme’s color palette

get_fonts() FontConfig[source]

Get current font configuration.

Return type:

FontConfig

Returns:

Current theme’s font configuration

get_figure_config() FigureConfig[source]

Get current figure configuration.

Return type:

FigureConfig

Returns:

Current theme’s figure configuration

get_grid_config() GridConfig[source]

Get current grid configuration.

Return type:

GridConfig

Returns:

Current theme’s grid configuration

update_colors(updates: Dict[str, str]) None[source]

Update colors in current theme.

Parameters:

updates (Dict[str, str]) – Dictionary of color updates

Return type:

None

update_fonts(updates: Dict[str, Any]) None[source]

Update fonts in current theme.

Parameters:

updates (Dict[str, Any]) – Dictionary of font updates

Return type:

None

apply_style() None[source]

Apply current theme to matplotlib.

This updates matplotlib’s rcParams to match the current theme settings.

Return type:

None

get_figure_size(size_type: str = 'medium', orientation: str = 'landscape') Tuple[float, float][source]

Get figure size for a given type.

Parameters:
  • size_type (str) – Size type (small, medium, large, blog, technical, presentation)

  • orientation (str) – Figure orientation (landscape or portrait)

Return type:

Tuple[float, float]

Returns:

Tuple of (width, height) in inches

get_dpi(output_type: str = 'screen') int[source]

Get DPI for output type.

Parameters:

output_type (str) – Output type (screen, web, print)

Return type:

int

Returns:

DPI value

load_config(config_path: str | Path) None[source]

Load configuration from YAML file.

Parameters:

config_path (Union[str, Path]) – Path to YAML configuration file

Return type:

None

save_config(config_path: str | Path) None[source]

Save current configuration to YAML file.

Parameters:

config_path (Union[str, Path]) – Path to save YAML configuration

Return type:

None

create_style_sheet() Dict[str, Any][source]

Create matplotlib style sheet dictionary.

Return type:

Dict[str, Any]

Returns:

Style sheet dictionary compatible with matplotlib

inherit_from(parent_theme: Theme, modifications: Dict[str, Any]) Theme[source]

Create a new theme inheriting from a parent with modifications.

Parameters:
  • parent_theme (Theme) – Theme to inherit from

  • modifications (Dict[str, Any]) – Dictionary of modifications

Return type:

Theme

Returns:

New theme enum value

ergodic_insurance.visualization.technical_plots module

Technical appendix visualization functions.

This module provides detailed technical visualization functions for convergence diagnostics, Pareto frontier analysis, loss distribution validation, and Monte Carlo convergence analysis.

plot_convergence_diagnostics(convergence_stats: Dict[str, Any], title: str = 'Convergence Diagnostics', figsize: Tuple[int, int] = (12, 8), r_hat_threshold: float = 1.1, show_threshold: bool = False) Figure[source]

Create comprehensive convergence diagnostics plot.

Visualizes convergence metrics including R-hat statistics, effective sample size, autocorrelation, and Monte Carlo standard errors.

Parameters:
  • convergence_stats (Dict[str, Any]) – Dictionary with convergence statistics

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • r_hat_threshold (float) – R-hat convergence threshold

  • show_threshold (bool) – Whether to show threshold lines

Return type:

Figure

Returns:

Matplotlib figure with convergence diagnostics

Examples

>>> stats = {
...     "r_hat_history": [1.5, 1.3, 1.15, 1.05],
...     "iterations": [100, 200, 300, 400],
...     "ess_history": [500, 800, 1200, 1500]
... }
>>> fig = plot_convergence_diagnostics(stats)
plot_pareto_frontier_2d(frontier_points: List[Any], x_objective: str, y_objective: str, x_label: str | None = None, y_label: str | None = None, title: str = 'Pareto Frontier', highlight_knees: bool = True, show_trade_offs: bool = False, figsize: Tuple[float, float] = (10, 6)) Figure[source]

Plot 2D Pareto frontier with WSJ styling.

Visualizes the trade-off between two objectives with optional knee point highlighting and dominated region shading.

Parameters:
  • frontier_points (List[Any]) – List of ParetoPoint objects

  • x_objective (str) – Name of objective for x-axis

  • y_objective (str) – Name of objective for y-axis

  • x_label (Optional[str]) – Optional custom label for x-axis

  • y_label (Optional[str]) – Optional custom label for y-axis

  • title (str) – Plot title

  • highlight_knees (bool) – Whether to highlight knee points

  • show_trade_offs (bool) – Whether to show trade-off annotations

  • figsize (Tuple[float, float]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with 2D Pareto frontier

Examples

>>> points = [ParetoPoint(objectives={"cost": 100, "quality": 0.8})]
>>> fig = plot_pareto_frontier_2d(points, "cost", "quality")
plot_pareto_frontier_3d(frontier_points: List[Any], x_objective: str, y_objective: str, z_objective: str, x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, title: str = '3D Pareto Frontier', figsize: Tuple[float, float] = (12, 8)) Figure[source]

Plot 3D Pareto frontier surface.

Creates a 3D visualization of the Pareto frontier with optional surface interpolation when sufficient points are available.

Parameters:
  • frontier_points (List[Any]) – List of ParetoPoint objects

  • x_objective (str) – Name of objective for x-axis

  • y_objective (str) – Name of objective for y-axis

  • z_objective (str) – Name of objective for z-axis

  • x_label (Optional[str]) – Optional custom label for x-axis

  • y_label (Optional[str]) – Optional custom label for y-axis

  • z_label (Optional[str]) – Optional custom label for z-axis

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with 3D Pareto frontier

create_interactive_pareto_frontier(frontier_points: List[Any], objectives: List[str], title: str = 'Interactive Pareto Frontier', height: int = 600, show_dominated: bool = True) Figure[source]

Create interactive Plotly Pareto frontier visualization.

Creates an interactive visualization that automatically adapts to the number of objectives (2D scatter, 3D scatter, or parallel coordinates).

Parameters:
  • frontier_points (List[Any]) – List of ParetoPoint objects

  • objectives (List[str]) – List of objective names to display

  • title (str) – Plot title

  • height (int) – Plot height in pixels

  • show_dominated (bool) – Whether to show dominated region (2D only)

Return type:

Figure

Returns:

Plotly figure with interactive Pareto frontier

plot_trace_plots(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Trace Plots', figsize: Tuple[int, int] = (12, 8)) Figure[source]

Create trace plots for MCMC chains with burn-in indicators.

Parameters:
  • chains (ndarray) – Array of shape (n_chains, n_iterations, n_parameters)

  • parameter_names (Optional[List[str]]) – Names of parameters (optional)

  • burn_in (Optional[int]) – Number of burn-in iterations to mark

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with trace plots

Examples

>>> chains = np.random.randn(4, 1000, 3)  # 4 chains, 1000 iterations, 3 parameters
>>> fig = plot_trace_plots(chains, ["param1", "param2", "param3"], burn_in=200)
plot_loss_distribution_validation(attritional_losses: ndarray, large_losses: ndarray, attritional_dist: Dict[str, Any] | None = None, large_dist: Dict[str, Any] | None = None, title: str = 'Loss Distribution Validation', figsize: Tuple[int, int] = (12, 10)) Figure[source]

Create comprehensive loss distribution validation plots (Figure B1).

Generates Q-Q plots and CDF comparisons for attritional and large losses, with K-S test statistics and goodness-of-fit metrics.

Parameters:
  • attritional_losses (ndarray) – Empirical attritional loss data

  • large_losses (ndarray) – Empirical large loss data

  • attritional_dist (Optional[Dict[str, Any]]) – Theoretical distribution parameters for attritional losses

  • large_dist (Optional[Dict[str, Any]]) – Theoretical distribution parameters for large losses

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with validation plots

Examples

>>> attritional = np.random.lognormal(10, 1, 1000)
>>> large = np.random.lognormal(15, 2, 100)
>>> fig = plot_loss_distribution_validation(attritional, large)
plot_monte_carlo_convergence(metrics_history: Dict[str, List[float]], iterations: ndarray | None = None, convergence_thresholds: Dict[str, float] | None = None, title: str = 'Monte Carlo Convergence Analysis', figsize: Tuple[int, int] = (14, 10), log_scale: bool = True) Figure[source]

Create Monte Carlo convergence analysis plots (Figure C3).

Visualizes convergence of key metrics (ROE, ruin probability, etc.) as a function of Monte Carlo iterations, with running statistics and thresholds.

Parameters:
  • metrics_history (Dict[str, List[float]]) – Dictionary of metric names to lists of values over iterations

  • iterations (Optional[ndarray]) – Array of iteration counts (optional, will be inferred)

  • convergence_thresholds (Optional[Dict[str, float]]) – Dictionary of metric names to convergence thresholds

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • log_scale (bool) – Whether to use log scale for x-axis

Return type:

Figure

Returns:

Matplotlib figure with convergence analysis

Examples

>>> history = {
...     "ROE": [0.08, 0.082, 0.081, 0.0805],
...     "Ruin Probability": [0.05, 0.048, 0.049, 0.0495]
... }
>>> fig = plot_monte_carlo_convergence(history)
plot_enhanced_convergence_diagnostics(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Enhanced Convergence Diagnostics', figsize: Tuple[int, int] = (14, 10)) Figure[source]

Create comprehensive convergence diagnostics with trace plots and statistics.

Enhanced version of plot_convergence_diagnostics that includes trace plots, R-hat evolution, ESS calculations, and autocorrelation analysis.

Parameters:
  • chains (ndarray) – Array of shape (n_chains, n_iterations, n_parameters)

  • parameter_names (Optional[List[str]]) – Names of parameters

  • burn_in (Optional[int]) – Number of burn-in iterations

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with enhanced diagnostics

Examples

>>> chains = np.random.randn(4, 1000, 2)
>>> fig = plot_enhanced_convergence_diagnostics(
...     chains,
...     parameter_names=["mu", "sigma"],
...     burn_in=200
... )
plot_ergodic_divergence(time_horizons: ndarray, time_averages: ndarray, ensemble_averages: ndarray, standard_errors: ndarray | None = None, parameter_scenarios: Dict[str, Dict[str, Any]] | None = None, title: str = 'Ergodic vs Ensemble Average Divergence', figsize: Tuple[float, float] = (14, 8), add_formulas: bool = True) Figure[source]

Create ergodic vs ensemble divergence visualization (Figure C1).

Demonstrates the fundamental difference between time-average (ergodic) and ensemble-average growth rates as time horizon increases, showing why insurance decisions must consider individual path dynamics rather than expected values.

Parameters:
  • time_horizons (ndarray) – Array of time horizons (e.g., 1 to 1000 years)

  • time_averages (ndarray) – Time-average growth rates for each horizon

  • ensemble_averages (ndarray) – Ensemble-average growth rates for each horizon

  • standard_errors (Optional[ndarray]) – Optional standard errors for confidence bands

  • parameter_scenarios (Optional[Dict[str, Dict[str, Any]]]) – Optional dict of scenario name to parameter values

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • add_formulas (bool) – Whether to add LaTeX formula annotations

Return type:

Figure

Returns:

Matplotlib figure showing divergence visualization

Examples

>>> horizons = np.logspace(0, 3, 50)  # 1 to 1000 years
>>> time_avg = np.array([0.05 * (1 - 0.1 * np.log10(t)) for t in horizons])
>>> ensemble_avg = np.array([0.08] * len(horizons))
>>> fig = plot_ergodic_divergence(horizons, time_avg, ensemble_avg)
plot_path_dependent_wealth(trajectories: ndarray, time_points: ndarray | None = None, ruin_threshold: float = 0.0, percentiles: List[int] | None = None, highlight_ruined: bool = True, add_survivor_bias_inset: bool = True, title: str = 'Path-Dependent Wealth Evolution', figsize: Tuple[float, float] = (14, 8), log_scale: bool = True) Figure[source]

Create path-dependent wealth evolution visualization (Figure C2).

Shows multiple wealth trajectories over time with percentile bands, highlighting paths that hit ruin and demonstrating survivor bias effects. This visualization makes clear why ensemble averages mislead decision-making.

Parameters:
  • trajectories (ndarray) – Array of shape (n_paths, n_time_points) with wealth values

  • time_points (Optional[ndarray]) – Optional array of time points (defaults to years)

  • ruin_threshold (float) – Wealth level considered as ruin (default 0)

  • percentiles (Optional[List[int]]) – List of percentiles to show (default [5, 25, 50, 75, 95])

  • highlight_ruined (bool) – Whether to highlight paths that hit ruin

  • add_survivor_bias_inset (bool) – Whether to add survivor bias analysis inset

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • log_scale (bool) – Whether to use log scale for wealth axis

Return type:

Figure

Returns:

Matplotlib figure showing path evolution

Examples

>>> n_paths, n_years = 1000, 100
>>> trajectories = np.random.lognormal(0, 0.2, (n_paths, n_years)).cumprod(axis=1)
>>> fig = plot_path_dependent_wealth(trajectories)
plot_correlation_structure(data: Dict[str, ndarray], correlation_type: str = 'pearson', risk_types: List[str] | None = None, title: str = 'Risk Correlation Structure', figsize: Tuple[float, float] = (14, 10), show_copula: bool = True) Figure[source]

Create correlation structure visualization with copula analysis (Figure B2).

Visualizes correlation matrices, copula density plots, and scatter plots with fitted copulas to show dependencies between different risk types.

Parameters:
  • data (Dict[str, ndarray]) – Dictionary mapping risk type names to data arrays (n_samples, n_variables)

  • correlation_type (str) – Type of correlation (‘pearson’, ‘spearman’, ‘kendall’)

  • risk_types (Optional[List[str]]) – List of risk types to analyze (defaults to all in data)

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • show_copula (bool) – Whether to show copula density plots

Return type:

Figure

Returns:

Matplotlib figure with correlation structure visualization

Examples

>>> data = {
...     "operational": np.random.randn(1000, 3),
...     "financial": np.random.randn(1000, 3)
... }
>>> fig = plot_correlation_structure(data)
plot_premium_decomposition(premium_components: Dict[str, Dict[str, Dict[str, float]]], company_sizes: List[str] | None = None, layers: List[str] | None = None, title: str = 'Premium Loading Decomposition', figsize: Tuple[float, float] = (14, 8), show_percentages: bool = True, color_scheme: Dict[str, str] | None = None) Figure[source]

Create premium loading decomposition visualization (Figure C4).

Shows stacked bar charts breaking down insurance premium into components: expected loss (base), volatility load, tail load, expense load, and profit margin.

Parameters:
  • premium_components (Dict[str, Dict[str, Dict[str, float]]]) – Nested dict with structure: {company_size: {layer: {component: value}}} Components: ‘expected_loss’, ‘volatility_load’, ‘tail_load’, ‘expense_load’, ‘profit_margin’

  • company_sizes (Optional[List[str]]) – List of company sizes to show (defaults to all)

  • layers (Optional[List[str]]) – List of insurance layers to show (defaults to all)

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • show_percentages (bool) – Whether to show percentage labels on segments

  • color_scheme (Optional[Dict[str, str]]) – Dict mapping component names to colors

Return type:

Figure

Returns:

Matplotlib figure with premium decomposition

Examples

>>> components = {
...     "Small": {
...         "Primary": {"expected_loss": 100, "volatility_load": 20,
...                    "tail_load": 15, "expense_load": 10, "profit_margin": 5}
...     }
... }
>>> fig = plot_premium_decomposition(components)
plot_capital_efficiency_frontier_3d(efficiency_data: Dict[str, Dict[str, ndarray]], company_sizes: List[str] | None = None, optimal_paths: Dict[str, ndarray] | None = None, title: str = 'Capital Efficiency Frontier', figsize: Tuple[float, float] = (14, 10), view_angles: Tuple[float, float] | None = None, export_views: bool = False) Figure | List[Figure][source]

Create 3D capital efficiency frontier visualization (Figure C5).

Shows 3D surface plot with ROE, Ruin Probability, and Insurance Spend axes, with separate surfaces for each company size and highlighted optimal paths.

Parameters:
  • efficiency_data (Dict[str, Dict[str, ndarray]]) – Nested dict with structure: {company_size: {'roe': 2D array (n_ruin x n_spend), 'ruin_prob': 1D array (n_ruin), 'insurance_spend': 1D array (n_spend)}}

  • company_sizes (Optional[List[str]]) – List of company sizes to show (defaults to all)

  • optimal_paths (Optional[Dict[str, ndarray]]) – Dict mapping company size to optimal path coordinates: {company_size: array of shape (n_points, 3) with [roe, ruin, spend]}

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • view_angles (Optional[Tuple[float, float]]) – Tuple of (elevation, azimuth) angles for 3D view

  • export_views (bool) – Whether to return multiple figures with different view angles

Return type:

Union[Figure, List[Figure]]

Returns:

Single figure or list of figures with different viewing angles if export_views=True

Examples

>>> data = {
...     "Small": {
...         "roe": np.random.rand(20, 30),
...         "ruin_prob": np.linspace(0, 0.1, 20),
...         "insurance_spend": np.linspace(0, 1e6, 30)
...     }
... }
>>> fig = plot_capital_efficiency_frontier_3d(data)

Module contents

Unified visualization infrastructure for ergodic insurance analysis.

This package provides a comprehensive visualization toolkit with: - Professional Wall Street Journal styling - Executive-level and technical visualizations - Interactive dashboards - Export utilities for various formats

set_wsj_style()[source]

Set matplotlib to use WSJ-style formatting.

This function applies Wall Street Journal aesthetic styling to matplotlib plots including font choices, spine visibility, grid settings, and colors.

format_currency(value: float, decimals: int = 0, abbreviate: bool = False) str[source]

Format value as currency.

Parameters:
  • value (float) – Numeric value to format

  • decimals (int) – Number of decimal places

  • abbreviate (bool) – If True, use K/M/B notation for large numbers

Return type:

str

Returns:

Formatted string (e.g., “$1,000” or “$1K” if abbreviate=True)

Examples

>>> format_currency(1000)
'$1,000'
>>> format_currency(1500000, abbreviate=True)
'$1.5M'
>>> format_currency(2500.50, decimals=2)
'$2,500.50'
format_percentage(value: float, decimals: int = 1) str[source]

Format value as percentage.

Parameters:
  • value (float) – Numeric value (0.05 = 5%)

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted string (e.g., “5.0%”)

Examples

>>> format_percentage(0.05)
'5.0%'
>>> format_percentage(0.1234, decimals=2)
'12.34%'
class WSJFormatter[source]

Bases: object

Formatter for WSJ-style axis labels.

This class provides static methods for formatting axis values in various styles consistent with Wall Street Journal publication standards.

currency_formatter()[source]

Format axis values as currency

currency()[source]

Format value as currency (shortened method name)

percentage_formatter()[source]

Format axis values as percentage

percentage()[source]

Format value as percentage (shortened method name)

number()[source]

Format large numbers with appropriate suffix

millions_formatter()[source]

Format axis values in millions

static currency_formatter(x, pos)[source]

Format axis values as currency.

Parameters:
  • x – The value to format

  • pos – The position (unused but required by matplotlib)

Returns:

Formatted currency string

static currency(x: float, decimals: int = 1) str[source]

Format value as currency (shortened method name).

Parameters:
  • x (float) – The value to format

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted currency string with appropriate suffix

static percentage_formatter(x, pos)[source]

Format axis values as percentage.

Parameters:
  • x – The value to format

  • pos – The position (unused but required by matplotlib)

Returns:

Formatted percentage string

static percentage(x: float, decimals: int = 1) str[source]

Format value as percentage (shortened method name).

Parameters:
  • x (float) – The value to format (0.05 = 5%)

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted percentage string

static number(x: float, decimals: int = 2) str[source]

Format large numbers with appropriate suffix.

Parameters:
  • x (float) – The value to format

  • decimals (int) – Number of decimal places

Return type:

str

Returns:

Formatted number string with K/M/B/T suffix

Examples

>>> WSJFormatter.number(1500000)
'1.50M'
>>> WSJFormatter.number(2500)
'2.50K'
static millions_formatter(x, pos)[source]

Format axis values in millions.

Parameters:
  • x – The value to format

  • pos – The position (unused but required by matplotlib)

Returns:

Value formatted as millions with M suffix

plot_loss_distribution(losses: ndarray | DataFrame, title: str = 'Loss Distribution', bins: int = 50, show_metrics: bool = True, var_levels: List[float] | None = None, figsize: Tuple[int, int] = (12, 6), show_stats: bool = False, log_scale: bool = False, use_factory: bool = False, theme: Any | None = None) Figure[source]

Create WSJ-style loss distribution plot.

Creates a two-panel visualization showing loss distribution histogram and Q-Q plot for normality assessment.

Parameters:
  • losses (Union[ndarray, DataFrame]) – Array of loss values or DataFrame with ‘amount’ column

  • title (str) – Plot title

  • bins (int) – Number of histogram bins

  • show_metrics (bool) – Whether to show VaR/TVaR lines

  • var_levels (Optional[List[float]]) – VaR confidence levels to show (default: [0.95, 0.99])

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_stats (bool) – Whether to show statistics

  • log_scale (bool) – Whether to use log scale

  • use_factory (bool) – Whether to use new visualization factory if available

  • theme (Optional[Any]) – Optional theme to use with factory

Return type:

Figure

Returns:

Matplotlib figure with distribution plots

Examples

>>> losses = np.random.lognormal(10, 2, 1000)
>>> fig = plot_loss_distribution(losses, title="Annual Loss Distribution")
plot_return_period_curve(losses: ndarray | DataFrame, return_periods: ndarray | None = None, scenarios: Dict[str, ndarray] | None = None, title: str = 'Return Period Curves', figsize: Tuple[int, int] = (10, 6), confidence_level: float = 0.95, show_grid: bool = True) Figure[source]

Create WSJ-style return period curve.

Visualizes the relationship between return periods and loss magnitudes, commonly used in catastrophe modeling and risk assessment.

Parameters:
  • losses (Union[ndarray, DataFrame]) – Loss amounts (array or DataFrame)

  • return_periods (Optional[ndarray]) – Array of return periods (years), optional

  • scenarios (Optional[Dict[str, ndarray]]) – Optional dict of scenario names to loss arrays

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • confidence_level (float) – Confidence level for bands

  • show_grid (bool) – Whether to show grid

Return type:

Figure

Returns:

Matplotlib figure with return period curve

Examples

>>> losses = np.random.lognormal(10, 2, 1000)
>>> fig = plot_return_period_curve(losses)
plot_insurance_layers(layers: List[Dict[str, float]] | DataFrame, total_limit: float | None = None, title: str = 'Insurance Program Structure', figsize: Tuple[int, int] = (10, 6), losses: ndarray | DataFrame | None = None, loss_data: ndarray | DataFrame | None = None, show_expected_loss: bool = False) Figure[source]

Create WSJ-style insurance layer visualization.

Visualizes insurance program structure with layer attachments, limits, and premium distribution in a two-panel display.

Parameters:
  • layers (Union[List[Dict[str, float]], DataFrame]) – List of layer dictionaries or DataFrame with ‘attachment’, ‘limit’ columns

  • total_limit (Optional[float]) – Total program limit (calculated from layers if not provided)

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • losses (Union[ndarray, DataFrame, None]) – Optional loss data for overlay

  • loss_data (Union[ndarray, DataFrame, None]) – Alias for losses parameter

  • show_expected_loss (bool) – Whether to show expected loss line

Return type:

Figure

Returns:

Matplotlib figure with layer structure and premium distribution

Examples

>>> layers = [
...     {"attachment": 0, "limit": 5e6, "premium": 0.015},
...     {"attachment": 5e6, "limit": 10e6, "premium": 0.008},
... ]
>>> fig = plot_insurance_layers(layers)
plot_roe_ruin_frontier(results: Dict[float, DataFrame] | DataFrame, company_sizes: List[float] | None = None, title: str = 'ROE-Ruin Efficient Frontier', figsize: Tuple[int, int] = (12, 8), highlight_sweet_spots: bool = True, show_optimal_zones: bool = True, export_dpi: int | None = None, log_scale_y: bool = True, grid: bool = True, annotations: bool = True, color_scheme: List[str] | None = None) Figure[source]

Create ROE-Ruin efficient frontier visualization.

Visualizes the Pareto frontier showing trade-offs between Return on Equity (ROE) and Ruin Probability for different company sizes. This helps executives understand optimal insurance purchasing decisions.

Parameters:
  • results (Union[Dict[float, DataFrame], DataFrame]) – Either a dict of company_size (float) -> optimization results DataFrame, or a single DataFrame with ‘company_size’ column

  • company_sizes (Optional[List[float]]) – List of company sizes to plot (e.g., [1e6, 1e7, 1e8]) If None, will use all available sizes in results

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • highlight_sweet_spots (bool) – Whether to highlight knee points on curves

  • show_optimal_zones (bool) – Whether to show shaded optimal zones

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print, None for screen)

  • log_scale_y (bool) – Whether to use log scale for ruin probability axis

  • grid (bool) – Whether to show grid lines

  • annotations (bool) – Whether to show annotations for key points

  • color_scheme (Optional[List[str]]) – List of colors for different company sizes

Return type:

Figure

Returns:

Matplotlib figure with ROE-Ruin efficient frontier plots

Raises:

ValueError – If results format is invalid or no data available

Examples

>>> # With dictionary of results
>>> results = {
...     1e6: pd.DataFrame({'roe': [0.1, 0.15, 0.2],
...                       'ruin_prob': [0.05, 0.02, 0.01]}),
...     1e7: pd.DataFrame({'roe': [0.08, 0.12, 0.18],
...                       'ruin_prob': [0.03, 0.015, 0.008]})
... }
>>> fig = plot_roe_ruin_frontier(results)
>>> # With single DataFrame
>>> df = pd.DataFrame({
...     'company_size': [1e6, 1e6, 1e7, 1e7],
...     'roe': [0.1, 0.15, 0.08, 0.12],
...     'ruin_prob': [0.05, 0.02, 0.03, 0.015]
... })
>>> fig = plot_roe_ruin_frontier(df)
plot_ruin_cliff(retention_range: Tuple[float, float] | None = None, n_points: int = 50, company_size: float = 10000000, simulation_data: Dict[str, Any] | None = None, title: str = 'The Ruin Cliff: Retention vs Failure Risk', figsize: Tuple[int, int] = (14, 8), show_inset: bool = True, show_warnings: bool = True, show_3d_effect: bool = True, export_dpi: int | None = None) Figure[source]

Create dramatic ruin cliff visualization with 3D effects.

Visualizes the relationship between insurance retention (deductible) levels and ruin probability, highlighting the “cliff edge” where risk dramatically increases. Features 3D-style gradient effects and warning zones.

Parameters:
  • retention_range (Optional[Tuple[float, float]]) – Tuple of (min, max) retention values in dollars. Default: (10_000, 10_000_000)

  • n_points (int) – Number of points to calculate along retention axis

  • company_size (float) – Company asset size for scaling retention levels

  • simulation_data (Optional[Dict[str, Any]]) – Optional pre-computed simulation results with keys: ‘retentions’, ‘ruin_probs’, ‘confidence_intervals’

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • show_inset (bool) – Whether to show zoomed inset of critical region

  • show_warnings (bool) – Whether to show warning callouts and annotations

  • show_3d_effect (bool) – Whether to add 3D gradient background effects

  • export_dpi (Optional[int]) – DPI for export (150 for web, 300 for print)

Return type:

Figure

Returns:

Matplotlib figure with ruin cliff visualization

Examples

>>> # Basic usage with synthetic data
>>> fig = plot_ruin_cliff()
>>> # With custom retention range
>>> fig = plot_ruin_cliff(retention_range=(5000, 5_000_000))
>>> # With pre-computed simulation data
>>> data = {
...     'retentions': np.logspace(4, 7, 50),
...     'ruin_probs': np.array([...]),
... }
>>> fig = plot_ruin_cliff(simulation_data=data)

Notes

The visualization uses a log scale for retention values to show the full range from small to large deductibles. The cliff edge is detected using derivative analysis to find the steepest point of increase in ruin probability.

plot_convergence_diagnostics(convergence_stats: Dict[str, Any], title: str = 'Convergence Diagnostics', figsize: Tuple[int, int] = (12, 8), r_hat_threshold: float = 1.1, show_threshold: bool = False) Figure[source]

Create comprehensive convergence diagnostics plot.

Visualizes convergence metrics including R-hat statistics, effective sample size, autocorrelation, and Monte Carlo standard errors.

Parameters:
  • convergence_stats (Dict[str, Any]) – Dictionary with convergence statistics

  • title (str) – Plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • r_hat_threshold (float) – R-hat convergence threshold

  • show_threshold (bool) – Whether to show threshold lines

Return type:

Figure

Returns:

Matplotlib figure with convergence diagnostics

Examples

>>> stats = {
...     "r_hat_history": [1.5, 1.3, 1.15, 1.05],
...     "iterations": [100, 200, 300, 400],
...     "ess_history": [500, 800, 1200, 1500]
... }
>>> fig = plot_convergence_diagnostics(stats)
plot_enhanced_convergence_diagnostics(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Enhanced Convergence Diagnostics', figsize: Tuple[int, int] = (14, 10)) Figure[source]

Create comprehensive convergence diagnostics with trace plots and statistics.

Enhanced version of plot_convergence_diagnostics that includes trace plots, R-hat evolution, ESS calculations, and autocorrelation analysis.

Parameters:
  • chains (ndarray) – Array of shape (n_chains, n_iterations, n_parameters)

  • parameter_names (Optional[List[str]]) – Names of parameters

  • burn_in (Optional[int]) – Number of burn-in iterations

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with enhanced diagnostics

Examples

>>> chains = np.random.randn(4, 1000, 2)
>>> fig = plot_enhanced_convergence_diagnostics(
...     chains,
...     parameter_names=["mu", "sigma"],
...     burn_in=200
... )
plot_ergodic_divergence(time_horizons: ndarray, time_averages: ndarray, ensemble_averages: ndarray, standard_errors: ndarray | None = None, parameter_scenarios: Dict[str, Dict[str, Any]] | None = None, title: str = 'Ergodic vs Ensemble Average Divergence', figsize: Tuple[float, float] = (14, 8), add_formulas: bool = True) Figure[source]

Create ergodic vs ensemble divergence visualization (Figure C1).

Demonstrates the fundamental difference between time-average (ergodic) and ensemble-average growth rates as time horizon increases, showing why insurance decisions must consider individual path dynamics rather than expected values.

Parameters:
  • time_horizons (ndarray) – Array of time horizons (e.g., 1 to 1000 years)

  • time_averages (ndarray) – Time-average growth rates for each horizon

  • ensemble_averages (ndarray) – Ensemble-average growth rates for each horizon

  • standard_errors (Optional[ndarray]) – Optional standard errors for confidence bands

  • parameter_scenarios (Optional[Dict[str, Dict[str, Any]]]) – Optional dict of scenario name to parameter values

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • add_formulas (bool) – Whether to add LaTeX formula annotations

Return type:

Figure

Returns:

Matplotlib figure showing divergence visualization

Examples

>>> horizons = np.logspace(0, 3, 50)  # 1 to 1000 years
>>> time_avg = np.array([0.05 * (1 - 0.1 * np.log10(t)) for t in horizons])
>>> ensemble_avg = np.array([0.08] * len(horizons))
>>> fig = plot_ergodic_divergence(horizons, time_avg, ensemble_avg)
plot_trace_plots(chains: ndarray, parameter_names: List[str] | None = None, burn_in: int | None = None, title: str = 'Trace Plots', figsize: Tuple[int, int] = (12, 8)) Figure[source]

Create trace plots for MCMC chains with burn-in indicators.

Parameters:
  • chains (ndarray) – Array of shape (n_chains, n_iterations, n_parameters)

  • parameter_names (Optional[List[str]]) – Names of parameters (optional)

  • burn_in (Optional[int]) – Number of burn-in iterations to mark

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with trace plots

Examples

>>> chains = np.random.randn(4, 1000, 3)  # 4 chains, 1000 iterations, 3 parameters
>>> fig = plot_trace_plots(chains, ["param1", "param2", "param3"], burn_in=200)
plot_loss_distribution_validation(attritional_losses: ndarray, large_losses: ndarray, attritional_dist: Dict[str, Any] | None = None, large_dist: Dict[str, Any] | None = None, title: str = 'Loss Distribution Validation', figsize: Tuple[int, int] = (12, 10)) Figure[source]

Create comprehensive loss distribution validation plots (Figure B1).

Generates Q-Q plots and CDF comparisons for attritional and large losses, with K-S test statistics and goodness-of-fit metrics.

Parameters:
  • attritional_losses (ndarray) – Empirical attritional loss data

  • large_losses (ndarray) – Empirical large loss data

  • attritional_dist (Optional[Dict[str, Any]]) – Theoretical distribution parameters for attritional losses

  • large_dist (Optional[Dict[str, Any]]) – Theoretical distribution parameters for large losses

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with validation plots

Examples

>>> attritional = np.random.lognormal(10, 1, 1000)
>>> large = np.random.lognormal(15, 2, 100)
>>> fig = plot_loss_distribution_validation(attritional, large)
plot_monte_carlo_convergence(metrics_history: Dict[str, List[float]], iterations: ndarray | None = None, convergence_thresholds: Dict[str, float] | None = None, title: str = 'Monte Carlo Convergence Analysis', figsize: Tuple[int, int] = (14, 10), log_scale: bool = True) Figure[source]

Create Monte Carlo convergence analysis plots (Figure C3).

Visualizes convergence of key metrics (ROE, ruin probability, etc.) as a function of Monte Carlo iterations, with running statistics and thresholds.

Parameters:
  • metrics_history (Dict[str, List[float]]) – Dictionary of metric names to lists of values over iterations

  • iterations (Optional[ndarray]) – Array of iteration counts (optional, will be inferred)

  • convergence_thresholds (Optional[Dict[str, float]]) – Dictionary of metric names to convergence thresholds

  • title (str) – Overall plot title

  • figsize (Tuple[int, int]) – Figure size (width, height)

  • log_scale (bool) – Whether to use log scale for x-axis

Return type:

Figure

Returns:

Matplotlib figure with convergence analysis

Examples

>>> history = {
...     "ROE": [0.08, 0.082, 0.081, 0.0805],
...     "Ruin Probability": [0.05, 0.048, 0.049, 0.0495]
... }
>>> fig = plot_monte_carlo_convergence(history)
plot_pareto_frontier_2d(frontier_points: List[Any], x_objective: str, y_objective: str, x_label: str | None = None, y_label: str | None = None, title: str = 'Pareto Frontier', highlight_knees: bool = True, show_trade_offs: bool = False, figsize: Tuple[float, float] = (10, 6)) Figure[source]

Plot 2D Pareto frontier with WSJ styling.

Visualizes the trade-off between two objectives with optional knee point highlighting and dominated region shading.

Parameters:
  • frontier_points (List[Any]) – List of ParetoPoint objects

  • x_objective (str) – Name of objective for x-axis

  • y_objective (str) – Name of objective for y-axis

  • x_label (Optional[str]) – Optional custom label for x-axis

  • y_label (Optional[str]) – Optional custom label for y-axis

  • title (str) – Plot title

  • highlight_knees (bool) – Whether to highlight knee points

  • show_trade_offs (bool) – Whether to show trade-off annotations

  • figsize (Tuple[float, float]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with 2D Pareto frontier

Examples

>>> points = [ParetoPoint(objectives={"cost": 100, "quality": 0.8})]
>>> fig = plot_pareto_frontier_2d(points, "cost", "quality")
plot_pareto_frontier_3d(frontier_points: List[Any], x_objective: str, y_objective: str, z_objective: str, x_label: str | None = None, y_label: str | None = None, z_label: str | None = None, title: str = '3D Pareto Frontier', figsize: Tuple[float, float] = (12, 8)) Figure[source]

Plot 3D Pareto frontier surface.

Creates a 3D visualization of the Pareto frontier with optional surface interpolation when sufficient points are available.

Parameters:
  • frontier_points (List[Any]) – List of ParetoPoint objects

  • x_objective (str) – Name of objective for x-axis

  • y_objective (str) – Name of objective for y-axis

  • z_objective (str) – Name of objective for z-axis

  • x_label (Optional[str]) – Optional custom label for x-axis

  • y_label (Optional[str]) – Optional custom label for y-axis

  • z_label (Optional[str]) – Optional custom label for z-axis

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

Return type:

Figure

Returns:

Matplotlib figure with 3D Pareto frontier

plot_path_dependent_wealth(trajectories: ndarray, time_points: ndarray | None = None, ruin_threshold: float = 0.0, percentiles: List[int] | None = None, highlight_ruined: bool = True, add_survivor_bias_inset: bool = True, title: str = 'Path-Dependent Wealth Evolution', figsize: Tuple[float, float] = (14, 8), log_scale: bool = True) Figure[source]

Create path-dependent wealth evolution visualization (Figure C2).

Shows multiple wealth trajectories over time with percentile bands, highlighting paths that hit ruin and demonstrating survivor bias effects. This visualization makes clear why ensemble averages mislead decision-making.

Parameters:
  • trajectories (ndarray) – Array of shape (n_paths, n_time_points) with wealth values

  • time_points (Optional[ndarray]) – Optional array of time points (defaults to years)

  • ruin_threshold (float) – Wealth level considered as ruin (default 0)

  • percentiles (Optional[List[int]]) – List of percentiles to show (default [5, 25, 50, 75, 95])

  • highlight_ruined (bool) – Whether to highlight paths that hit ruin

  • add_survivor_bias_inset (bool) – Whether to add survivor bias analysis inset

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • log_scale (bool) – Whether to use log scale for wealth axis

Return type:

Figure

Returns:

Matplotlib figure showing path evolution

Examples

>>> n_paths, n_years = 1000, 100
>>> trajectories = np.random.lognormal(0, 0.2, (n_paths, n_years)).cumprod(axis=1)
>>> fig = plot_path_dependent_wealth(trajectories)
create_interactive_pareto_frontier(frontier_points: List[Any], objectives: List[str], title: str = 'Interactive Pareto Frontier', height: int = 600, show_dominated: bool = True) Figure[source]

Create interactive Plotly Pareto frontier visualization.

Creates an interactive visualization that automatically adapts to the number of objectives (2D scatter, 3D scatter, or parallel coordinates).

Parameters:
  • frontier_points (List[Any]) – List of ParetoPoint objects

  • objectives (List[str]) – List of objective names to display

  • title (str) – Plot title

  • height (int) – Plot height in pixels

  • show_dominated (bool) – Whether to show dominated region (2D only)

Return type:

Figure

Returns:

Plotly figure with interactive Pareto frontier

plot_correlation_structure(data: Dict[str, ndarray], correlation_type: str = 'pearson', risk_types: List[str] | None = None, title: str = 'Risk Correlation Structure', figsize: Tuple[float, float] = (14, 10), show_copula: bool = True) Figure[source]

Create correlation structure visualization with copula analysis (Figure B2).

Visualizes correlation matrices, copula density plots, and scatter plots with fitted copulas to show dependencies between different risk types.

Parameters:
  • data (Dict[str, ndarray]) – Dictionary mapping risk type names to data arrays (n_samples, n_variables)

  • correlation_type (str) – Type of correlation (‘pearson’, ‘spearman’, ‘kendall’)

  • risk_types (Optional[List[str]]) – List of risk types to analyze (defaults to all in data)

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • show_copula (bool) – Whether to show copula density plots

Return type:

Figure

Returns:

Matplotlib figure with correlation structure visualization

Examples

>>> data = {
...     "operational": np.random.randn(1000, 3),
...     "financial": np.random.randn(1000, 3)
... }
>>> fig = plot_correlation_structure(data)
plot_premium_decomposition(premium_components: Dict[str, Dict[str, Dict[str, float]]], company_sizes: List[str] | None = None, layers: List[str] | None = None, title: str = 'Premium Loading Decomposition', figsize: Tuple[float, float] = (14, 8), show_percentages: bool = True, color_scheme: Dict[str, str] | None = None) Figure[source]

Create premium loading decomposition visualization (Figure C4).

Shows stacked bar charts breaking down insurance premium into components: expected loss (base), volatility load, tail load, expense load, and profit margin.

Parameters:
  • premium_components (Dict[str, Dict[str, Dict[str, float]]]) – Nested dict with structure: {company_size: {layer: {component: value}}} Components: ‘expected_loss’, ‘volatility_load’, ‘tail_load’, ‘expense_load’, ‘profit_margin’

  • company_sizes (Optional[List[str]]) – List of company sizes to show (defaults to all)

  • layers (Optional[List[str]]) – List of insurance layers to show (defaults to all)

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • show_percentages (bool) – Whether to show percentage labels on segments

  • color_scheme (Optional[Dict[str, str]]) – Dict mapping component names to colors

Return type:

Figure

Returns:

Matplotlib figure with premium decomposition

Examples

>>> components = {
...     "Small": {
...         "Primary": {"expected_loss": 100, "volatility_load": 20,
...                    "tail_load": 15, "expense_load": 10, "profit_margin": 5}
...     }
... }
>>> fig = plot_premium_decomposition(components)
plot_capital_efficiency_frontier_3d(efficiency_data: Dict[str, Dict[str, ndarray]], company_sizes: List[str] | None = None, optimal_paths: Dict[str, ndarray] | None = None, title: str = 'Capital Efficiency Frontier', figsize: Tuple[float, float] = (14, 10), view_angles: Tuple[float, float] | None = None, export_views: bool = False) Figure | List[Figure][source]

Create 3D capital efficiency frontier visualization (Figure C5).

Shows 3D surface plot with ROE, Ruin Probability, and Insurance Spend axes, with separate surfaces for each company size and highlighted optimal paths.

Parameters:
  • efficiency_data (Dict[str, Dict[str, ndarray]]) – Nested dict with structure: {company_size: {'roe': 2D array (n_ruin x n_spend), 'ruin_prob': 1D array (n_ruin), 'insurance_spend': 1D array (n_spend)}}

  • company_sizes (Optional[List[str]]) – List of company sizes to show (defaults to all)

  • optimal_paths (Optional[Dict[str, ndarray]]) – Dict mapping company size to optimal path coordinates: {company_size: array of shape (n_points, 3) with [roe, ruin, spend]}

  • title (str) – Plot title

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • view_angles (Optional[Tuple[float, float]]) – Tuple of (elevation, azimuth) angles for 3D view

  • export_views (bool) – Whether to return multiple figures with different view angles

Return type:

Union[Figure, List[Figure]]

Returns:

Single figure or list of figures with different viewing angles if export_views=True

Examples

>>> data = {
...     "Small": {
...         "roe": np.random.rand(20, 30),
...         "ruin_prob": np.linspace(0, 0.1, 20),
...         "insurance_spend": np.linspace(0, 1e6, 30)
...     }
... }
>>> fig = plot_capital_efficiency_frontier_3d(data)
create_interactive_dashboard(results: Dict[str, Any] | DataFrame, title: str = 'Monte Carlo Simulation Dashboard', height: int = 600, show_distributions: bool = False) Figure[source]

Create interactive Plotly dashboard with WSJ styling.

Creates a comprehensive interactive dashboard with multiple panels showing simulation results, convergence, and risk metrics.

Parameters:
  • results (Union[Dict[str, Any], DataFrame]) – Dictionary with simulation results or DataFrame

  • title (str) – Dashboard title

  • height (int) – Dashboard height in pixels

  • show_distributions (bool) – Whether to show distribution plots

Return type:

Figure

Returns:

Plotly figure with interactive dashboard

Examples

>>> results = {
...     "growth_rates": np.random.normal(0.05, 0.02, 1000),
...     "losses": np.random.lognormal(10, 2, 1000),
...     "metrics": {"var_95": 100000, "var_99": 150000}
... }
>>> fig = create_interactive_dashboard(results)
create_time_series_dashboard(data: DataFrame, value_col: str, time_col: str = 'date', title: str = 'Time Series Analysis', height: int = 600, show_forecast: bool = False) Figure[source]

Create interactive time series visualization.

Creates an interactive time series plot with optional forecast bands and statistical overlays.

Parameters:
  • data (DataFrame) – DataFrame with time series data

  • value_col (str) – Name of value column

  • time_col (str) – Name of time column

  • title (str) – Plot title

  • height (int) – Plot height in pixels

  • show_forecast (bool) – Whether to show forecast bands

Return type:

Figure

Returns:

Plotly figure with time series visualization

create_correlation_heatmap(data: DataFrame, title: str = 'Correlation Matrix', height: int = 600, show_values: bool = True) Figure[source]

Create interactive correlation heatmap.

Creates an interactive heatmap showing correlations between variables with customizable color scheme and annotations.

Parameters:
  • data (DataFrame) – DataFrame with variables to correlate

  • title (str) – Plot title

  • height (int) – Plot height in pixels

  • show_values (bool) – Whether to show correlation values

Return type:

Figure

Returns:

Plotly figure with correlation heatmap

create_risk_dashboard(risk_metrics: Dict[str, Any], title: str = 'Risk Analytics Dashboard', height: int = 800) Figure[source]

Create comprehensive risk analytics dashboard.

Creates a multi-panel dashboard showing various risk metrics and distributions for comprehensive risk assessment.

Parameters:
  • risk_metrics (Dict[str, Any]) – Dictionary containing risk metrics and data

  • title (str) – Dashboard title

  • height (int) – Dashboard height in pixels

Return type:

Figure

Returns:

Plotly figure with risk dashboard

plot_scenario_comparison(aggregated_results: Any, metrics: List[str] | None = None, figsize: Tuple[float, float] = (14, 8), save_path: str | None = None) Figure[source]

Create comprehensive scenario comparison visualization.

Compares multiple scenarios across different metrics with bar charts highlighting the best performer for each metric.

Parameters:
  • aggregated_results (Any) – AggregatedResults object from batch processing

  • metrics (Optional[List[str]]) – List of metrics to compare (default: key metrics)

  • figsize (Tuple[float, float]) – Figure size (width, height)

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Matplotlib figure with scenario comparisons

Examples

>>> from ergodic_insurance.batch_processor import AggregatedResults
>>> results = AggregatedResults(batch_results)
>>> fig = plot_scenario_comparison(results, metrics=["mean_growth_rate"])
plot_sensitivity_heatmap(aggregated_results: Any, metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (10, 8), save_path: str | None = None) Figure[source]

Create sensitivity analysis heatmap.

Visualizes sensitivity of outcomes to parameter changes using a horizontal bar chart color-coded by impact direction.

Parameters:
  • aggregated_results (Any) – AggregatedResults with sensitivity analysis

  • metric (str) – Metric to visualize

  • figsize (Tuple[float, float]) – Figure size

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Matplotlib figure with sensitivity analysis

plot_parameter_sweep_3d(aggregated_results: Any, param1: str, param2: str, metric: str = 'mean_growth_rate', height: int = 600, save_path: str | None = None) Figure[source]

Create 3D surface plot for parameter sweep results.

Visualizes how a metric varies across two parameter dimensions using an interactive 3D scatter plot.

Parameters:
  • aggregated_results (Any) – AggregatedResults from grid search

  • param1 (str) – First parameter name

  • param2 (str) – Second parameter name

  • metric (str) – Metric to plot on z-axis

  • height (int) – Figure height in pixels

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Plotly figure with 3D parameter sweep

plot_scenario_convergence(batch_results: List[Any], metric: str = 'mean_growth_rate', figsize: Tuple[float, float] = (12, 6), save_path: str | None = None) Figure[source]

Plot convergence of metric across scenarios.

Shows how a metric converges as more scenarios are processed, with execution time distribution.

Parameters:
  • batch_results (List[Any]) – List of BatchResult objects

  • metric (str) – Metric to track

  • figsize (Tuple[float, float]) – Figure size

  • save_path (Optional[str]) – Path to save figure

Return type:

Figure

Returns:

Matplotlib figure with convergence analysis

plot_parallel_scenarios(batch_results: List[Any], metrics: List[str], figsize: Tuple[float, float] = (12, 8), normalize: bool = True) Figure[source]

Create parallel coordinates plot for scenario comparison.

Visualizes multiple scenarios across multiple metrics using parallel coordinates for comprehensive comparison.

Parameters:
  • batch_results (List[Any]) – List of BatchResult objects

  • metrics (List[str]) – List of metrics to include

  • figsize (Tuple[float, float]) – Figure size

  • normalize (bool) – Whether to normalize metrics to [0, 1]

Return type:

Figure

Returns:

Matplotlib figure with parallel coordinates

add_value_labels(ax: Axes, bars, format_func=None, fontsize: int = 9, va: str = 'bottom', ha: str = 'center', offset: float = 0.01, color: str | None = None, bold: bool = False) None[source]

Add value labels to bar chart.

Adds formatted value labels on top of or inside bars in a bar chart.

Parameters:
  • ax (Axes) – Matplotlib axes

  • bars – Bar container from ax.bar()

  • format_func – Optional function to format values

  • fontsize (int) – Font size for labels

  • va (str) – Vertical alignment (‘bottom’, ‘center’, ‘top’)

  • ha (str) – Horizontal alignment (‘left’, ‘center’, ‘right’)

  • offset (float) – Vertical offset as fraction of y-range

  • color (Optional[str]) – Text color (default: gray)

  • bold (bool) – Whether to make text bold

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> bars = ax.bar(range(5), [10, 20, 15, 25, 30])
>>> add_value_labels(ax, bars)
add_trend_annotation(ax: Axes, x_pos: float, y_pos: float, trend: float, period: str = 'YoY', fontsize: int = 10) None[source]

Add trend annotation with arrow.

Adds a trend annotation showing percentage change with an up/down arrow.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x_pos (float) – X position for annotation

  • y_pos (float) – Y position for annotation

  • trend (float) – Trend value (e.g., 0.15 for 15% increase)

  • period (str) – Period description (e.g., “YoY”, “MoM”)

  • fontsize (int) – Font size for annotation

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> add_trend_annotation(ax, 0.8, 0.9, 0.15, "YoY")
add_callout(ax: Axes, text: str, xy: Tuple[float, float], xytext: Tuple[float, float], fontsize: int = 9, color: str | None = None, arrow_color: str | None = None, bbox_props: dict | None = None) None[source]

Add a callout annotation with arrow.

Creates a professional callout annotation with customizable styling.

Parameters:
Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> add_callout(ax, "Peak value", xy=(2, 4), xytext=(2.5, 4.5))
add_benchmark_line(ax: Axes, value: float, label: str, color: str | None = None, linestyle: str = '--', linewidth: float = 1.5, fontsize: int = 9, position: str = 'right') None[source]

Add a horizontal benchmark line with label.

Draws a horizontal reference line with an integrated label.

Parameters:
  • ax (Axes) – Matplotlib axes

  • value (float) – Y-value for benchmark line

  • label (str) – Label for the benchmark

  • color (Optional[str]) – Line color

  • linestyle (str) – Line style

  • linewidth (float) – Line width

  • fontsize (int) – Font size for label

  • position (str) – Label position (‘left’, ‘right’, ‘center’)

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot(range(10), np.random.randn(10))
>>> add_benchmark_line(ax, 0, "Average", color="red")
add_shaded_region(ax: Axes, x_start: float, x_end: float, label: str | None = None, color: str | None = None, alpha: float = 0.2) None[source]

Add a shaded vertical region.

Creates a shaded vertical band to highlight a specific time period or range.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x_start (float) – Start x-coordinate

  • x_end (float) – End x-coordinate

  • label (Optional[str]) – Optional label for the region

  • color (Optional[str]) – Fill color

  • alpha (float) – Transparency

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot(range(10), np.random.randn(10))
>>> add_shaded_region(ax, 3, 6, label="Recession", color="gray")
add_data_source(fig, source: str, x: float = 0.99, y: float = 0.01, fontsize: int = 8, color: str | None = None) None[source]

Add data source attribution.

Adds a data source note to the figure, typically at the bottom right.

Parameters:
  • fig – Matplotlib figure

  • source (str) – Source text (e.g., “Source: Company Reports”)

  • x (float) – X position in figure coordinates

  • y (float) – Y position in figure coordinates

  • fontsize (int) – Font size

  • color (Optional[str]) – Text color

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> add_data_source(fig, "Source: Internal Analysis")
add_footnote(fig, text: str, x: float = 0.5, y: float = 0.02, fontsize: int = 8, color: str | None = None) None[source]

Add footnote to figure.

Adds a footnote or explanatory text to the bottom of the figure.

Parameters:
  • fig – Matplotlib figure

  • text (str) – Footnote text

  • x (float) – X position in figure coordinates

  • y (float) – Y position in figure coordinates

  • fontsize (int) – Font size

  • color (Optional[str]) – Text color

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> add_footnote(fig, "* Preliminary data subject to revision")
save_figure(fig: Figure | Figure, filename: str, dpi: int = 300, bbox_inches: str = 'tight', transparent: bool = False, formats: List[str] | None = None, metadata: Dict[str, Any] | None = None) List[str][source]

Save figure in multiple formats.

Saves a matplotlib or plotly figure to disk in one or more formats with professional quality settings.

Parameters:
  • fig (Union[Figure, Figure]) – Matplotlib Figure or Plotly Figure to save

  • filename (str) – Base filename (without extension)

  • dpi (int) – Resolution for raster formats

  • bbox_inches (str) – How to handle figure bounds

  • transparent (bool) – Whether to use transparent background

  • formats (Optional[List[str]]) – List of formats to save (default: [‘png’])

  • metadata (Optional[Dict[str, Any]]) – Optional metadata to embed in files

Return type:

List[str]

Returns:

List of saved file paths

Raises:

ValueError – If unsupported format is requested

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> save_figure(fig, "my_plot", formats=["png", "pdf"])
['my_plot.png', 'my_plot.pdf']
save_for_publication(fig: Figure, filename: str, width: float = 7, height: float = 5, dpi: int = 600) str[source]

Save figure with publication-quality settings.

Exports a figure with settings optimized for academic publication or professional reports.

Parameters:
  • fig (Figure) – Matplotlib figure

  • filename (str) – Output filename (without extension)

  • width (float) – Figure width in inches

  • height (float) – Figure height in inches

  • dpi (int) – Resolution (600 for print quality)

Return type:

str

Returns:

Path to saved PDF file

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> save_for_publication(fig, "figure_1")
'figure_1.pdf'
save_for_presentation(fig: Figure | Figure, filename: str, width: int = 1920, height: int = 1080) str[source]

Save figure optimized for presentations.

Exports a figure with settings optimized for PowerPoint or other presentation software.

Parameters:
  • fig (Union[Figure, Figure]) – Matplotlib or Plotly figure

  • filename (str) – Output filename (without extension)

  • width (int) – Width in pixels

  • height (int) – Height in pixels

Return type:

str

Returns:

Path to saved file

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> save_for_presentation(fig, "slide_1")
'slide_1.png'
save_for_web(fig: Figure | Figure, filename: str, optimize: bool = True) Dict[str, str][source]

Save figure optimized for web display.

Creates web-optimized versions of the figure including responsive formats and multiple resolutions.

Parameters:
  • fig (Union[Figure, Figure]) – Matplotlib or Plotly figure

  • filename (str) – Base filename (without extension)

  • optimize (bool) – Whether to optimize file sizes

Return type:

Dict[str, str]

Returns:

Dictionary of format to file path mappings

Examples

>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 2])
>>> files = save_for_web(fig, "chart")
>>> print(files)
{'thumbnail': 'chart_thumb.png', 'full': 'chart.png', 'svg': 'chart.svg'}
batch_export(figures: Dict[str, Figure | Figure], output_dir: str, formats: List[str] | None = None, dpi: int = 300) Dict[str, List[str]][source]

Export multiple figures in batch.

Saves multiple figures to a directory with consistent settings.

Parameters:
  • figures (Dict[str, Union[Figure, Figure]]) – Dictionary mapping names to figures

  • output_dir (str) – Output directory path

  • formats (Optional[List[str]]) – List of formats to save each figure

  • dpi (int) – Resolution for raster formats

Return type:

Dict[str, List[str]]

Returns:

Dictionary mapping figure names to lists of saved files

Examples

>>> fig1, ax1 = plt.subplots()
>>> fig2, ax2 = plt.subplots()
>>> figures = {"chart1": fig1, "chart2": fig2}
>>> batch_export(figures, "output/", formats=["png"])
class FigureFactory(style_manager: StyleManager | None = None, theme: Theme = Theme.DEFAULT, auto_apply: bool = True)[source]

Bases: object

Factory for creating standardized figures with consistent styling.

This class provides methods to create various types of plots with automatic application of themes, consistent formatting, and proper spacing.

Example

>>> factory = FigureFactory(theme=Theme.PRESENTATION)
>>> fig, ax = factory.create_line_plot(
...     x_data=[1, 2, 3, 4],
...     y_data=[10, 20, 15, 25],
...     title="Revenue Growth",
...     x_label="Quarter",
...     y_label="Revenue ($M)"
... )
>>> # Create multiple subplots
>>> fig, axes = factory.create_subplots(
...     rows=2, cols=2,
...     size_type="large",
...     subplot_titles=["Q1", "Q2", "Q3", "Q4"]
... )
create_figure(size_type: str = 'medium', orientation: str = 'landscape', dpi_type: str = 'screen', title: str | None = None) Tuple[Figure, Axes][source]

Create a basic figure with styling applied.

Parameters:
  • size_type (str) – Size preset (small, medium, large, blog, technical, presentation)

  • orientation (str) – Figure orientation (landscape or portrait)

  • dpi_type (str) – DPI type (screen, web, print)

  • title (Optional[str]) – Optional figure title

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_subplots(rows: int = 1, cols: int = 1, size_type: str = 'large', dpi_type: str = 'screen', title: str | None = None, subplot_titles: List[str] | None = None, **kwargs) Tuple[Figure, Axes | ndarray][source]

Create subplots with consistent styling.

Parameters:
  • rows (int) – Number of subplot rows

  • cols (int) – Number of subplot columns

  • size_type (str) – Size preset

  • dpi_type (str) – DPI type

  • title (Optional[str]) – Main figure title

  • subplot_titles (Optional[List[str]]) – Titles for each subplot

  • **kwargs – Additional arguments for plt.subplots

Return type:

Tuple[Figure, Union[Axes, ndarray]]

Returns:

Tuple of (figure, axes array)

create_line_plot(x_data: List | ndarray | Series, y_data: List | ndarray | Series | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', show_legend: bool = True, show_grid: bool = True, markers: bool = False, **kwargs) Tuple[Figure, Axes][source]

Create a line plot with automatic formatting.

Parameters:
  • x_data (Union[List, ndarray, Series]) – X-axis data

  • y_data (Union[List, ndarray, Series, Dict[str, Union[List, ndarray]]]) – Y-axis data (can be multiple series as dict)

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • labels (Optional[List[str]]) – Series labels for legend

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • show_legend (bool) – Whether to show legend

  • show_grid (bool) – Whether to show grid

  • markers (bool) – Whether to add markers to lines

  • **kwargs – Additional arguments for plot

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_bar_plot(categories: List | ndarray, values: List | ndarray | Dict[str, List | ndarray], title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_values: bool = False, value_format: str = '.1f', **kwargs) Tuple[Figure, Axes][source]

Create a bar plot with automatic formatting.

Parameters:
  • categories (Union[List, ndarray]) – Category labels

  • values (Union[List, ndarray, Dict[str, Union[List, ndarray]]]) – Values to plot (can be multiple series as dict)

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • labels (Optional[List[str]]) – Series labels for legend

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • orientation (str) – Bar orientation (vertical or horizontal)

  • show_values (bool) – Whether to show value labels on bars

  • value_format (str) – Format string for value labels

  • **kwargs – Additional arguments for bar plot

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_scatter_plot(x_data: List | ndarray, y_data: List | ndarray, title: str | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', colors: List | ndarray | None = None, sizes: List | ndarray | None = None, labels: List[str] | None = None, show_colorbar: bool = False, **kwargs) Tuple[Figure, Axes][source]

Create a scatter plot with automatic formatting.

Parameters:
  • x_data (Union[List, ndarray]) – X-axis data

  • y_data (Union[List, ndarray]) – Y-axis data

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • colors (Union[List, ndarray, None]) – Optional colors for points (for continuous coloring)

  • sizes (Union[List, ndarray, None]) – Optional sizes for points

  • labels (Optional[List[str]]) – Optional labels for points

  • show_colorbar (bool) – Whether to show colorbar when colors provided

  • **kwargs – Additional arguments for scatter

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_histogram(data: List | ndarray | Series, title: str | None = None, x_label: str | None = None, y_label: str = 'Frequency', bins: int | str = 'auto', size_type: str = 'medium', dpi_type: str = 'screen', show_statistics: bool = False, show_kde: bool = False, **kwargs) Tuple[Figure, Axes][source]

Create a histogram with automatic formatting.

Parameters:
  • data (Union[List, ndarray, Series]) – Data to plot

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (str) – Y-axis label

  • bins (Union[int, str]) – Number of bins or method

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • show_statistics (bool) – Whether to show mean/median lines

  • show_kde (bool) – Whether to overlay KDE

  • **kwargs – Additional arguments for hist

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_heatmap(data: ndarray | DataFrame, title: str | None = None, x_labels: List[str] | None = None, y_labels: List[str] | None = None, x_label: str | None = None, y_label: str | None = None, size_type: str = 'medium', dpi_type: str = 'screen', cmap: str = 'RdBu_r', show_values: bool = True, value_format: str = '.2f', **kwargs) Tuple[Figure, Axes][source]

Create a heatmap with automatic formatting.

Parameters:
  • data (Union[ndarray, DataFrame]) – 2D data array or DataFrame

  • title (Optional[str]) – Plot title

  • x_labels (Optional[List[str]]) – Labels for x-axis

  • y_labels (Optional[List[str]]) – Labels for y-axis

  • x_label (Optional[str]) – X-axis title

  • y_label (Optional[str]) – Y-axis title

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • cmap (str) – Colormap name

  • show_values (bool) – Whether to show values in cells

  • value_format (str) – Format string for cell values

  • **kwargs – Additional arguments for imshow

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

create_box_plot(data: List[List] | Dict[str, List] | DataFrame, title: str | None = None, x_label: str | None = None, y_label: str | None = None, labels: List[str] | None = None, size_type: str = 'medium', dpi_type: str = 'screen', orientation: str = 'vertical', show_means: bool = True, **kwargs) Tuple[Figure, Axes][source]

Create a box plot with automatic formatting.

Parameters:
  • data (Union[List[List], Dict[str, List], DataFrame]) – Data for box plot (list of lists, dict, or DataFrame)

  • title (Optional[str]) – Plot title

  • x_label (Optional[str]) – X-axis label

  • y_label (Optional[str]) – Y-axis label

  • labels (Optional[List[str]]) – Labels for each box

  • size_type (str) – Figure size preset

  • dpi_type (str) – DPI type

  • orientation (str) – Plot orientation (vertical or horizontal)

  • show_means (bool) – Whether to show mean markers

  • **kwargs – Additional arguments for boxplot

Return type:

Tuple[Figure, Axes]

Returns:

Tuple of (figure, axes)

format_axis_currency(ax: Axes, axis: str = 'y', abbreviate: bool = True, decimals: int = 0) None[source]

Format axis labels as currency.

Parameters:
  • ax (Axes) – Matplotlib axes

  • axis (str) – Which axis to format (x or y)

  • abbreviate (bool) – Whether to abbreviate large numbers

  • decimals (int) – Number of decimal places

Return type:

None

format_axis_percentage(ax: Axes, axis: str = 'y', decimals: int = 0) None[source]

Format axis labels as percentages.

Parameters:
  • ax (Axes) – Matplotlib axes

  • axis (str) – Which axis to format (x or y)

  • decimals (int) – Number of decimal places

Return type:

None

add_annotations(ax: Axes, x: float, y: float, text: str, arrow: bool = True, offset: Tuple[float, float] = (10, 10), **kwargs) None[source]

Add styled annotation to plot.

Parameters:
  • ax (Axes) – Matplotlib axes

  • x (float) – X coordinate

  • y (float) – Y coordinate

  • text (str) – Annotation text

  • arrow (bool) – Whether to show arrow

  • offset (Tuple[float, float]) – Text offset from point

  • **kwargs – Additional arguments for annotate

Return type:

None

save_figure(fig: Figure, filename: str, output_type: str = 'web', **kwargs) None[source]

Save figure with appropriate DPI settings.

Parameters:
  • fig (Figure) – Figure to save

  • filename (str) – Output filename

  • output_type (str) – Output type (screen, web, print)

  • **kwargs – Additional arguments for savefig

Return type:

None

class StyleManager(theme: Theme = Theme.DEFAULT, config_path: str | Path | None = None, custom_colors: Dict[str, str] | None = None, custom_fonts: Dict[str, Any] | None = None)[source]

Bases: object

Manages visualization styles and themes.

This class provides centralized style management for all visualizations, supporting multiple themes, custom configurations, and style inheritance.

Example

>>> style_mgr = StyleManager()
>>> style_mgr.set_theme(Theme.PRESENTATION)
>>> style_mgr.apply_style()
>>> # Create plots with consistent styling
>>> # Or with custom configuration
>>> style_mgr = StyleManager(config_path="custom_style.yaml")
>>> style_mgr.apply_style()
themes: Dict[Theme, Dict[str, Any]]
set_theme(theme: Theme) None[source]

Set the current theme.

Parameters:

theme (Theme) – Theme to activate

Return type:

None

get_theme_config(theme: Theme | None = None) Dict[str, Any][source]

Get configuration for a theme.

Parameters:

theme (Optional[Theme]) – Theme to get config for (defaults to current)

Return type:

Dict[str, Any]

Returns:

Theme configuration dictionary

get_colors() ColorPalette[source]

Get current color palette.

Return type:

ColorPalette

Returns:

Current theme’s color palette

get_fonts() FontConfig[source]

Get current font configuration.

Return type:

FontConfig

Returns:

Current theme’s font configuration

get_figure_config() FigureConfig[source]

Get current figure configuration.

Return type:

FigureConfig

Returns:

Current theme’s figure configuration

get_grid_config() GridConfig[source]

Get current grid configuration.

Return type:

GridConfig

Returns:

Current theme’s grid configuration

update_colors(updates: Dict[str, str]) None[source]

Update colors in current theme.

Parameters:

updates (Dict[str, str]) – Dictionary of color updates

Return type:

None

update_fonts(updates: Dict[str, Any]) None[source]

Update fonts in current theme.

Parameters:

updates (Dict[str, Any]) – Dictionary of font updates

Return type:

None

apply_style() None[source]

Apply current theme to matplotlib.

This updates matplotlib’s rcParams to match the current theme settings.

Return type:

None

get_figure_size(size_type: str = 'medium', orientation: str = 'landscape') Tuple[float, float][source]

Get figure size for a given type.

Parameters:
  • size_type (str) – Size type (small, medium, large, blog, technical, presentation)

  • orientation (str) – Figure orientation (landscape or portrait)

Return type:

Tuple[float, float]

Returns:

Tuple of (width, height) in inches

get_dpi(output_type: str = 'screen') int[source]

Get DPI for output type.

Parameters:

output_type (str) – Output type (screen, web, print)

Return type:

int

Returns:

DPI value

load_config(config_path: str | Path) None[source]

Load configuration from YAML file.

Parameters:

config_path (Union[str, Path]) – Path to YAML configuration file

Return type:

None

save_config(config_path: str | Path) None[source]

Save current configuration to YAML file.

Parameters:

config_path (Union[str, Path]) – Path to save YAML configuration

Return type:

None

create_style_sheet() Dict[str, Any][source]

Create matplotlib style sheet dictionary.

Return type:

Dict[str, Any]

Returns:

Style sheet dictionary compatible with matplotlib

inherit_from(parent_theme: Theme, modifications: Dict[str, Any]) Theme[source]

Create a new theme inheriting from a parent with modifications.

Parameters:
  • parent_theme (Theme) – Theme to inherit from

  • modifications (Dict[str, Any]) – Dictionary of modifications

Return type:

Theme

Returns:

New theme enum value

class Theme(*values)[source]

Bases: Enum

Available visualization themes.

DEFAULT = 'default'
COLORBLIND = 'colorblind'
PRESENTATION = 'presentation'
MINIMAL = 'minimal'
PRINT = 'print'