Plotting¶
from epydemix.visualization import plot_quantiles, plot_trajectories # and the others below
Simulation results¶
- epydemix.visualization.plotting.plot_quantiles(df_quantiles, columns, data=None, data_date_column='date', ax=None, lower_q=0.05, upper_q=0.95, show_median=True, show_data=False, ci_alpha=0.3, title='', ylabel='', xlabel='', show_legend=True, legend_loc='upper left', palette='Dark2', colors=None, labels=None, y_scale='linear', show_grid=True)[source]¶
Plots quantiles for compartments over time with optional observed data.
- Parameters:
df_quantiles (DataFrame) – DataFrame with columns: ‘date’, ‘quantile’, and data columns
data (DataFrame | None) – Optional DataFrame containing observed data
data_date_column (str) – Column name for date in data
ax (Axes | None) – Matplotlib axes to plot on
lower_q (float) – Lower quantile value (0.05 = 5th percentile)
upper_q (float) – Upper quantile value (0.95 = 95th percentile)
show_median (bool) – Whether to show median line
show_data (bool) – Whether to show observed data points
ci_alpha (float) – Alpha value for confidence interval shading
title (str) – Plot title
ylabel (str) – Y-axis label
xlabel (str) – X-axis label
show_legend (bool) – Whether to show legend
legend_loc (str) – Legend location
palette (str) – Color palette name
y_scale (str) – Scale for y-axis (‘linear’ or ‘log’)
show_grid (bool) – Whether to show grid lines
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- epydemix.visualization.plotting.plot_trajectories(stacked, columns, data=None, ax=None, show_data=False, alpha=0.1, title='', ylabel='', xlabel='', show_legend=True, legend_loc='upper left', palette='Dark2', colors=None, labels=None, y_scale='linear', show_grid=True, dates=None)[source]¶
Plots individual trajectories over time with optional observed data.
- Parameters:
stacked (Dict[str, ndarray]) – Dictionary mapping column names to arrays of shape (n_simulations, timesteps)
data (DataFrame | None) – Optional DataFrame containing observed data
ax (Axes | None) – Matplotlib axes to plot on
show_data (bool) – Whether to show observed data points
alpha (float) – Alpha value for individual trajectories
title (str) – Plot title
ylabel (str) – Y-axis label
xlabel (str) – X-axis label
show_legend (bool) – Whether to show legend
legend_loc (str) – Legend location
palette (str) – Color palette name
y_scale (str) – Scale for y-axis (‘linear’ or ‘log’)
show_grid (bool) – Whether to show grid lines
dates (ndarray | None) – Array of dates for x-axis. If None, uses range(timesteps)
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
Calibration results¶
- epydemix.visualization.plotting.plot_posterior_distribution(posterior, parameter, ax=None, xlabel=None, ylabel=None, kind='hist', color='dodgerblue', xlim=None, prior=None, prior_range=False, title=None, fontsize=10, show_grid=True, show_kde=True, show_rug=False, figsize=(10, 4), stat='density', bins='auto', alpha=0.4, vertical_lines=None, **kwargs)[source]¶
Plots the distribution of a parameter.
- Parameters:
posterior (DataFrame) – DataFrame containing the parameter values
parameter (str) – The parameter to plot
ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None
xlabel (str | None) – X-axis label. If None, uses parameter name
ylabel (str | None) – Y-axis label
kind (str) – Type of plot (‘hist’, ‘kde’, or ‘ecdf’)
color (str) – Color for the plot
xlim (Tuple[float, float] | None) – Tuple of (min, max) for x-axis limits
prior (Any | None) – Prior distribution object with ppf method
prior_range (bool) – Whether to set x-axis limits to prior range
title (str | None) – Plot title. If None, auto-generates
fontsize (int) – Base font size for labels and ticks
show_grid (bool) – Whether to show grid lines
show_kde (bool) – Whether to show KDE curve with histogram (only for kind=’hist’)
show_rug (bool) – Whether to show rug plot
figsize (Tuple[int, int]) – Figure size if creating new figure
stat (str) – Statistic to plot (‘count’, ‘density’, ‘probability’)
alpha (float) – Transparency of the plot
vertical_lines (Dict[str, Dict[str, Any]] | None) – Dict of vertical lines to add, mapping a name to the line’s settings, e.g.
{'name': {'x': value, 'color': 'color', 'linestyle': '--', 'label': 'label'}}**kwargs – Additional arguments passed to plotting functions
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- Raises:
ValueError – If kind is not ‘hist’, ‘kde’, or ‘ecdf’
ValueError – If prior_range is True but no prior is provided
- epydemix.visualization.plotting.plot_posterior_distribution_2d(posterior, parameter_x, parameter_y, ax=None, xlabel=None, ylabel=None, kind='hist', palette='Blues', xlim=None, ylim=None, prior_x=None, prior_y=None, prior_range=False, title=None, fontsize=10, cmap=None, show_grid=True, levels=10, figsize=(6, 6), scatter=False, scatter_alpha=0.5, scatter_size=20, scatter_color='k', **kwargs)[source]¶
Plots the 2D joint distribution of two parameters.
- Parameters:
posterior (DataFrame) – DataFrame containing the parameter values
parameter_x (str) – Parameter to plot on x-axis
parameter_y (str) – Parameter to plot on y-axis
ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None
xlabel (str | None) – X-axis label. If None, uses parameter_x
ylabel (str | None) – Y-axis label. If None, uses parameter_y
kind (str) – Plot type (‘hist’, ‘kde’, or ‘scatter’)
palette (str) – Color palette for histogram/kde
xlim (Tuple[float, float] | None) – Tuple of (min, max) for x-axis limits
ylim (Tuple[float, float] | None) – Tuple of (min, max) for y-axis limits
prior_x (Any | None) – Prior distribution object for x parameter
prior_y (Any | None) – Prior distribution object for y parameter
prior_range (bool) – Whether to set axis limits to prior ranges
title (str | None) – Plot title. If None, auto-generates
fontsize (int) – Base font size for labels and ticks
cmap (str | None) – Colormap for 2D histogram/kde
show_grid (bool) – Whether to show grid lines
levels (int) – Number of contour levels for kde
figsize (Tuple[int, int]) – Figure size if creating new figure
scatter (bool) – Whether to overlay scatter plot on kde
scatter_alpha (float) – Alpha value for scatter points
scatter_size (int) – Size of scatter points
scatter_color (str) – Color for scatter points
**kwargs – Additional arguments passed to sns.histplot/kdeplot
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- Raises:
ValueError – If kind is not ‘hist’, ‘kde’, or ‘scatter’
ValueError – If prior_range is True but priors are not provided
- epydemix.visualization.plotting.plot_distance_distribution(distances, ax=None, kind='hist', color='dodgerblue', xlabel=None, ylabel=None, title=None, fontsize=10, show_grid=True, show_kde=True, show_rug=False, figsize=(10, 4), xlim=None, ylim=None, stat='density', bins='auto', alpha=0.4, vertical_lines=None, **kwargs)[source]¶
Plots the distribution of distances/errors from calibration.
- Parameters:
distances (ndarray | List[float] | Series) – Array-like object containing the distance/error values
ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None
kind (str) – Type of plot (‘hist’, ‘kde’, or ‘ecdf’)
color (str) – Color for the plot
xlabel (str | None) – X-axis label
ylabel (str | None) – Y-axis label
title (str | None) – Plot title
fontsize (int) – Base font size for labels and ticks
show_grid (bool) – Whether to show grid lines
show_kde (bool) – Whether to show KDE curve with histogram (only for kind=’hist’)
show_rug (bool) – Whether to show rug plot
figsize (Tuple[int, int]) – Figure size if creating new figure
xlim (Tuple[float, float] | None) – Tuple of (min, max) for x-axis limits
ylim (Tuple[float, float] | None) – Tuple of (min, max) for y-axis limits
stat (str) – Statistic to plot for histogram (‘count’, ‘density’, ‘probability’)
alpha (float) – Transparency of the plot
vertical_lines (Dict[str, Dict[str, Any]] | None) – Dict of vertical lines to add, mapping a name to the line’s settings, e.g.
{'name': {'x': value, 'color': 'color', 'linestyle': '--', 'label': 'label'}}**kwargs – Additional arguments passed to plotting functions
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- Raises:
ValueError – If kind is not ‘hist’, ‘kde’, or ‘ecdf’
Populations and contacts¶
- epydemix.visualization.plotting.plot_population(population, ax=None, title=None, color='dodgerblue', show_perc=False, fontsize=10, rotation=45, figsize=(10, 6), bar_width=0.8, show_grid=True, ylabel=None, xlabel='Demographic group', show_values=True, fmt=None, value_fontsize=None)[source]¶
Plot the population distribution across demographic groups.
- Parameters:
population (Any) – Population object containing demographic data
ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None
title (str | None) – Plot title. If None, uses default title
color (str) – Color for the bars
show_perc (bool) – Whether to show population as percentages
fontsize (int) – Base font size for labels and ticks
rotation (int) – Rotation angle for x-axis labels
figsize (Tuple[int, int]) – Figure size if creating new figure
bar_width (float) – Width of the bars (between 0 and 1)
show_grid (bool) – Whether to show grid lines
ylabel (str | None) – Y-axis label. If None, uses default based on show_perc
xlabel (str) – X-axis label
show_values (bool) – Whether to show values above bars
fmt (str | None) – Format string for values. If None, uses “.1f%” for percentages and human-readable suffixes (K/M/B) for absolute numbers.
value_fontsize (int | None) – Font size for bar values. If None, uses fontsize
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- epydemix.visualization.plotting.plot_contact_matrix(population, layer, ax=None, cmap='YlOrRd', show_values=False, title=None, show_colorbar=True, fmt='.1f', fontsize=8, rotation=45, figsize=(10, 8), vmin=None, vmax=None, origin='lower')[source]¶
Plot a contact matrix heatmap.
- Parameters:
population (Any) – Population object containing contact matrices
layer (str) – Name of the contact layer to plot
ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None
cmap (str) – Colormap for the heatmap
show_values (bool) – Whether to show numerical values in cells
title (str | None) – Plot title. If None, uses layer name
colorbar – Whether to show the colorbar
fmt (str) – Format string for cell values
fontsize (int) – Font size for labels and values
rotation (int) – Rotation angle for x-axis labels
figsize (Tuple[int, int]) – Figure size if creating new figure
vmin (float | None) – Minimum value for colormap scaling
vmax (float | None) – Maximum value for colormap scaling
origin (str) – Whether to plot the matrix with the origin at the bottom left (default) or top left
show_colorbar (bool)
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- Raises:
KeyError – If specified layer doesn’t exist
- epydemix.visualization.plotting.plot_spectral_radius(epimodel, ax=None, title=None, color='k', show_perc=False, layer='overall', show_interventions=True, interventions_palette='Dark2', interventions_colors=None, fontsize=10, date_format='%Y-%m-%d', ylabel=None, xlabel='Date', show_grid=True, alpha=0.2, legend_loc='upper left')[source]¶
Plots the spectral radius of the contact matrices over time.
- Parameters:
epimodel (Any) – The EpiModel object containing contact matrices and interventions
ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None
title (str | None) – Plot title. If None, uses default title
color (str) – Color of the spectral radius line
show_perc (bool) – Whether to show as percentage change with respect to the initial value
layer (str) – Contact matrix layer to analyze
show_interventions (bool) – Whether to show intervention periods
interventions_palette (str) – Color palette for interventions
interventions_colors (List[str] | None) – Custom colors for interventions
fontsize (int) – Base font size for labels and ticks
date_format (str) – Format string for date labels
ylabel (str | None) – Y-axis label. If None, auto-generated based on normalize/show_perc
xlabel (str) – X-axis label
show_grid (bool) – Whether to show grid lines
alpha (float) – Transparency for intervention highlights
legend_loc (str) – Location of the legend
- Returns:
The matplotlib axes object
- Return type:
plt.Axes
- Raises:
ValueError – If no contact matrices are defined or layer doesn’t exist