Plotting

Standalone plotting functions. Each one is also exposed as a Dataset method of the same name, which additionally handles column-name resolution (sim_name_col/replica_col) and optional sim_name/replica filtering before delegating to the function below.

Scatter plots

plot_scatter draws a single scatter plot of two features, with optional coloring by system/replica, a KDE density overlay, and an annotated correlation coefficient / regression line.

RepLikCompare.plotting.plot_scatter.plot_scatter(df, x, y, sim_name_col=None, replica_col=None, max_data=50000, quant=None, s=20, linewidth=0, alpha=1, palette='tab10', ax=None, context='talk', xlabel=None, ylabel=None, xlim=None, ylim=None, title=None, output_file_name='', figsize=None, legend_loc='lower center', legend_bbox_to_anchor=None, legend_ncol=None, edgecolors='black', global_density=False, density_alpha=0.25, density_color='black', density_kwargs=None, corr_method='pearson', show_corr=False, show_regression=False, reg_color='red', reg_linestyle='--', reg_linewidth=1.5, reg_alpha=0.8)[source]

Scatter plot of two numeric columns, optionally colored by system/replica and annotated with a correlation coefficient and/or a regression line.

Parameters:
  • df (pandas.DataFrame) – Long-format dataframe containing at least the x and y columns.

  • x (str) – Column names to plot on the x- and y-axes.

  • y (str) – Column names to plot on the x- and y-axes.

  • sim_name_col (str, optional) – Column names used to color points by system/replica. If both are given, each (system, replica) pair gets its own shade within the system’s base color. Default None (no color grouping).

  • replica_col (str, optional) – Column names used to color points by system/replica. If both are given, each (system, replica) pair gets its own shade within the system’s base color. Default None (no color grouping).

  • max_data (int, optional) – Maximum number of points drawn; the dataframe is subsampled with a fixed step if larger. Default 50000.

  • quant (float, optional) – If given, x/y limits are clipped to this quantile (and 1 - quant) of each axis instead of the full data range. Default None.

  • s (optional) – Standard matplotlib/seaborn marker styling passed to seaborn.scatterplot().

  • linewidth (optional) – Standard matplotlib/seaborn marker styling passed to seaborn.scatterplot().

  • alpha (optional) – Standard matplotlib/seaborn marker styling passed to seaborn.scatterplot().

  • edgecolors (optional) – Standard matplotlib/seaborn marker styling passed to seaborn.scatterplot().

  • palette (str or dict, optional) – Seaborn/matplotlib palette name (or explicit color mapping) used for the system/replica coloring. Default “tab10”.

  • ax (matplotlib.axes.Axes, optional) – Axes to draw on. A new figure/axes is created if None.

  • context (str, optional) – Seaborn plotting context (e.g. “talk”, “notebook”). Default “talk”.

  • xlabel (optional) – Axis labels/limits/title. Labels default to x/y; limits default to the data range (or quant-based bounds).

  • ylabel (optional) – Axis labels/limits/title. Labels default to x/y; limits default to the data range (or quant-based bounds).

  • xlim (optional) – Axis labels/limits/title. Labels default to x/y; limits default to the data range (or quant-based bounds).

  • ylim (optional) – Axis labels/limits/title. Labels default to x/y; limits default to the data range (or quant-based bounds).

  • title (optional) – Axis labels/limits/title. Labels default to x/y; limits default to the data range (or quant-based bounds).

  • output_file_name (str, optional) – If given, the figure is saved to this path.

  • figsize (tuple, optional) – Figure size, used only when ax is None.

  • legend_loc (optional) – Legend placement, forwarded to seaborn.move_legend().

  • legend_bbox_to_anchor (optional) – Legend placement, forwarded to seaborn.move_legend().

  • legend_ncol (optional) – Legend placement, forwarded to seaborn.move_legend().

  • global_density (bool, optional) – Overlay a 2D KDE density contour of the (x, y) distribution. Default False.

  • density_alpha (optional) – Styling for the density overlay.

  • density_color (optional) – Styling for the density overlay.

  • density_kwargs (optional) – Styling for the density overlay.

  • corr_method ({"pearson", "spearman"}, optional) – Correlation coefficient reported when show_corr/show_regression is True. Default “pearson”.

  • show_corr (bool, optional) – Annotate the plot title with the correlation coefficient (R or rho) and its square. Default False.

  • show_regression (bool, optional) – Draw a linear trendline (least-squares fit) over the points, with the correlation in its legend label. Default False.

  • reg_color (optional) – Styling for the regression line.

  • reg_linestyle (optional) – Styling for the regression line.

  • reg_linewidth (optional) – Styling for the regression line.

  • reg_alpha (optional) – Styling for the regression line.

Returns:

ax (matplotlib.axes.Axes) – The axes containing the plot.

plot_scatter_facet is the faceted version: one scatter sub-panel per system (or any other grouping column) instead of a single global plot, with optional local (per-facet) and/or global regression lines so groups can be compared directly.

RepLikCompare.plotting.plot_scatter.plot_scatter_facet(df, x, y, sim_name_col=None, replica_col=None, facet_col=None, facet_order=None, ncols=3, max_data=50000, quant=None, s=20, linewidth=0, alpha=1, palette='tab10', context='talk', xlabel=None, ylabel=None, xlim=None, ylim=None, shared_axlim=True, figsize_per_facet=(8, 8), title=None, output_file_name='', save_fig=True, shared_legend=True, legend_loc='center left', legend_bbox_to_anchor=(1, 0.5), legend_ncol=None, edgecolors='black', global_density=True, density_alpha=0.25, density_color='black', density_kwargs=None, corr_method='pearson', show_corr=False, show_local_reg=False, show_global_reg=False, local_reg_color='red', global_reg_color='blue', local_reg_linestyle='--', global_reg_linestyle='-.', reg_linewidth=1.5)[source]

Faceted version of plot_scatter(): draws one scatter sub-panel per value of facet_col (e.g. one panel per system) instead of a single global plot, optionally with local (per-facet) and/or global regression lines for comparison.

Parameters:
  • df (pandas.DataFrame) – Long-format dataframe containing the x, y and facet_col columns.

  • x (str) – Column names to plot on the x- and y-axes of every sub-panel.

  • y (str) – Column names to plot on the x- and y-axes of every sub-panel.

  • sim_name_col (str, optional) – Column names used to color points by system/replica within each sub-panel. Default None.

  • replica_col (str, optional) – Column names used to color points by system/replica within each sub-panel. Default None.

  • facet_col (str) – Column whose unique values define one sub-panel each.

  • facet_order (list, optional) – Explicit ordering of facet values. Default: sorted unique values.

  • ncols (int, optional) – Number of sub-panel columns in the grid. Default 3.

  • max_data (int, optional) – Maximum number of points drawn per facet. Default 50000.

  • quant (float, optional) – If given, axis limits are clipped to this quantile of the data instead of the full range. Default None.

  • s (optional) – Marker styling, forwarded to seaborn.scatterplot().

  • linewidth (optional) – Marker styling, forwarded to seaborn.scatterplot().

  • alpha (optional) – Marker styling, forwarded to seaborn.scatterplot().

  • edgecolors (optional) – Marker styling, forwarded to seaborn.scatterplot().

  • palette (str or dict, optional) – Palette used for system/replica coloring. Default “tab10”.

  • context (str, optional) – Seaborn plotting context. Default “talk”.

  • xlabel (optional) – Axis labels/limits. Labels default to x/y.

  • ylabel (optional) – Axis labels/limits. Labels default to x/y.

  • xlim (optional) – Axis labels/limits. Labels default to x/y.

  • ylim (optional) – Axis labels/limits. Labels default to x/y.

  • shared_axlim (bool, optional) – Use the same x/y limits across all sub-panels so they stay directly comparable. Default True.

  • figsize_per_facet (tuple, optional) – Size of a single sub-panel; the full figure scales with ncols and the number of rows. Default (8, 8).

  • title (str, optional) – Overall figure title.

  • output_file_name (str, optional) – If given (and save_fig is True), the figure is saved to this path.

  • save_fig (bool, optional) – Whether output_file_name (if given) is actually written to disk. Default True.

  • shared_legend (bool, optional) – Draw a single legend for the whole figure instead of one per sub-panel. Default True.

  • legend_loc (optional) – Legend placement, forwarded to seaborn.move_legend().

  • legend_bbox_to_anchor (optional) – Legend placement, forwarded to seaborn.move_legend().

  • legend_ncol (optional) – Legend placement, forwarded to seaborn.move_legend().

  • global_density (bool, optional) – Overlay a 2D KDE density contour on each sub-panel. Default True.

  • density_alpha (optional) – Styling for the density overlay.

  • density_color (optional) – Styling for the density overlay.

  • density_kwargs (optional) – Styling for the density overlay.

  • corr_method ({"pearson", "spearman"}, optional) – Correlation coefficient used when show_corr is True. Default “pearson”.

  • show_corr (bool, optional) – Annotate each sub-panel with its local correlation coefficient. Default False.

  • show_local_reg (bool, optional) – Draw a regression line fitted independently within each facet. Default False.

  • show_global_reg (bool, optional) – Draw a single regression line fitted on the pooled data across all facets, overlaid on every sub-panel for comparison. Default False.

  • local_reg_color (optional) – Styling for the local/global regression lines.

  • global_reg_color (optional) – Styling for the local/global regression lines.

  • local_reg_linestyle (optional) – Styling for the local/global regression lines.

  • global_reg_linestyle (optional) – Styling for the local/global regression lines.

  • reg_linewidth (optional) – Styling for the local/global regression lines.

Returns:

  • fig (matplotlib.figure.Figure) – The figure containing all sub-panels.

  • axes (numpy.ndarray of matplotlib.axes.Axes) – The grid of sub-panel axes.

Line plots (replica-averaged)

plot_lineplot_avg plots a feature against time/frame, averaged across replicas of a system with a shaded spread band.

RepLikCompare.plotting.plot_lineplot_avg.plot_lineplot_avg(df, x, y, quant=None, color='black', max_data=50000, avg_win=100, alpha=0.3, ax=None, context='notebook', xlabel=None, ylabel=None, title='', output_file_name='')[source]

Plot a line with a Gaussian-smoothed average on the y-axis.

Parameters:
  • df (pandas.DataFrame) – Dataframe with the data to plot.

  • x (str) – Name of the column with the x-axis data.

  • y (str) – Name of the column with the y-axis data.

  • quant (float, optional) – Quantile used to filter the data. The default is None.

  • color (str, optional) – Color of the line. The default is “black”.

  • max_data (int, optional) – Maximum number of data points to plot. The default is 50000.

  • avg_win (int, optional) – Window size of the Gaussian filter. The default is 1000.

Returns:

g (matplotlib.axes._subplots.AxesSubplot) – Axes of the plot.

plot_lineplot_facet is the faceted version, with one sub-panel per system.

RepLikCompare.plotting.plot_lineplot_avg.plot_lineplot_facet(df, x, y, facet_col, sim_name_col=None, replica_col=None, facet_order=None, ncols=3, max_data=50000, avg_win=100, quant=None, color='black', lw=0.3, avg_lw=2, alpha=0.3, palette='tab10', context='notebook', xlabel=None, ylabel=None, xlim=None, ylim=None, shared_axlim=True, figsize_per_facet=(8, 5), title='', output_file_name='', save_fig=True, shared_legend=True, legend_loc='center left', legend_bbox_to_anchor=(1, 0.5), legend_ncol=None)[source]

Version facettée de plot_lineplot_avg : un sous-panneau par valeur de facet_col, avec courbe brute (fine, transparente) + moyenne lissée (Gaussienne, épaisse) sur chacun. La moyenne est recalculée séparément par sous-panneau (et par sim_name si sim_name_col est fourni), donc elle ne “fuit” pas d’un facet à l’autre.

Parameters:
  • df (pandas.DataFrame) – Dataframe avec les données à tracer.

  • x (str) – Colonnes des axes x et y.

  • y (str) – Colonnes des axes x et y.

  • facet_col (str) – Colonne utilisée pour créer un sous-panneau par valeur unique.

  • sim_name_col (str, optional) – Si fournis (et présents dans df), les courbes sont colorées par sim_name_col à l’intérieur de chaque sous-panneau.

  • replica_col (str, optional) – Si fournis (et présents dans df), les courbes sont colorées par sim_name_col à l’intérieur de chaque sous-panneau.

  • facet_order (list, optional) – Ordre explicite des valeurs de facet_col. Par défaut, valeurs uniques triées.

  • ncols (int, optional) – Nombre de colonnes de la grille de sous-panneaux.

  • avg_win (int, optional) – Taille de fenêtre du filtre Gaussien.

  • quant (float, optional) – Quantile utilisé pour fixer les limites d’axes (si shared_axlim).

  • shared_axlim (bool, optional) – Si True, tous les sous-panneaux partagent les mêmes limites d’axes.

  • shared_legend (bool, optional) – Si True, une seule légende (dernier sous-panneau) est affichée.

Returns:

fig, axes (matplotlib Figure et array d’Axes.)

Distributions

plot_distri_norm plots the distribution (histogram and/or KDE) of a feature, grouped per system or per replica.

RepLikCompare.plotting.plot_distri_norm.plot_distri_norm(df, x, sim_name_col, replica_col, mode='per_sim', max_data=50000, bins=100, element='step', quant=None, bw_adjust=None, alpha=1, fill=False, kde=True, hist=True, common_norm=False, palette='tab10', ax=None, context='talk', xlabel=None, title=None, output_file_name='', figsize=None, legend_loc='lower center', legend_bbox_to_anchor=None, legend_ncol=None)[source]

Plot a distribution with optional KDE and/or histogram overlays, colored by simulation and/or replica.

Three modes are available via mode:

  • “per_sim”: one curve per simulation (replicas pooled), single panel.

  • “per_rep”: one curve per replica, shaded by its simulation, single panel.

  • “both”: both panels side by side for comparison.

Parameters:
  • df (pandas.DataFrame) – Dataframe containing the data to plot.

  • x (str) – Name of the column to plot on the x-axis.

  • sim_name_col (str) – Name of the column identifying the simulation or system.

  • replica_col (str) – Name of the column identifying the replica.

  • mode (str, optional) – “per_sim”, “per_rep”, or “both”. Default “per_sim”.

  • max_data (int, optional) – Maximum number of points to plot. Downsamples via stepping if exceeded. Default 50000.

  • bins (int, optional) – Number of histogram bins. Default 100.

  • element (str, optional) – Visual element for histogram bars (“bars”, “step”, or “poly”). Default “step”.

  • quant (float, optional) – Quantile used to filter the x-axis bounds (e.g., 0.001 filters bottom 0.1% and top 0.1%). Default None.

  • bw_adjust (float, optional) – Factor that multiplies the default KDE bandwidth. Default None.

  • alpha (float, optional) – Opacity of fill/lines. Default 0.3.

  • fill (bool, optional) – If True, fill the area under the histogram or KDE curves. Default False.

  • kde (bool, optional) – If True, compute and plot a Kernel Density Estimate curve. Default True.

  • hist (bool, optional) – If True, plot the histogram. If False, hides the histogram bars/lines and draws only the KDE curve (if kde=True). Default True.

  • common_norm (bool, optional) – If True, normalize total density across all hue categories to sum to 1. If False, normalize each category independently. Default False.

  • palette (str, optional) – Seaborn palette used for simulations. Default “tab10”.

  • ax (matplotlib.axes.Axes, optional) – Axis to draw on. Ignored if mode=”both” (two axes are created). Default None.

  • context (str, optional) – Seaborn plotting context (e.g., “notebook”, “paper”, “talk”). Default “notebook”.

  • xlabel (str, optional) – Label for the x-axis. Default None (uses x column name).

  • title (str, optional) – Overall plot title or suptitle. Default None.

  • output_file_name (str, optional) – File path to save the generated figure. Default None (does not save).

  • figsize (tuple, optional) – Figure dimensions (width, height). Default (7, 5) for single panel, (12, 4.5) for “both” mode.

  • legend_loc (str, optional) – Position of the legend within the figure layout. Default “lower center”.

  • legend_bbox_to_anchor (tuple, optional) – Explicit bounding box coordinates to anchor the legend. Default None.

  • legend_ncol (int, optional) – Number of columns in the legend. Default None.

Returns:

ax (matplotlib.axes.Axes or np.ndarray of matplotlib.axes.Axes) – The single axis (for “per_sim” / “per_rep”) or array of two axes (for “both”).

Circular distributions (von Mises)

plot_vonmises is the circular equivalent of plot_distri_norm for angular features (e.g. dihedral angles): it fits a von Mises kernel density instead of a linear KDE, so the density correctly wraps around at +-pi.

RepLikCompare.plotting.plot_vonmises.plot_vonmises(df, x, sim_name_col, replica_col, mode='per_sim', unit=None, n_grid=360, kappa=None, kappa_adjust=1.0, max_data=50000, palette='tab10', fill=False, fill_alpha=0.25, linewidth=1.5, linestyle='-', line_alpha=0.85, ax=None, context='talk', xlabel=None, title=None, output_file_name=None, figsize=None, legend_loc=None, legend_bbox_to_anchor=None, legend_ncol=None)[source]

Plot a circular distribution using a von Mises KDE.

Three modes are available via mode:

  • “per_sim”: one curve per simulation (replicas pooled), single panel.

  • “per_rep”: one curve per replica, shaded by its simulation, single panel.

  • “both”: both panels side by side.

The data can be supplied in radians or degrees. The unit is inferred automatically if unit is not provided. The plot is always rendered in degrees in the range [-180, 180].

A handful of seaborn.kdeplot-style styling options are exposed even though this uses a custom circular KDE rather than sns.kdeplot directly: fill/fill_alpha (shade the area under the curve, like kdeplot’s fill=True), linewidth/linestyle/line_alpha, and kappa_adjust (a multiplier applied to the auto-estimated concentration kappa – the circular analogue of kdeplot’s bw_adjust, but inverted since kappa is a concentration (not a bandwidth): >1 sharpens/narrows the curve, <1 widens/smooths it. Ignored if kappa is set explicitly).

Parameters:
  • df (pandas.DataFrame) – Dataframe containing the input data.

  • x (str) – Name of the column containing the circular variable (angle).

  • sim_name_col (str) – Name of the column identifying the simulation or system.

  • replica_col (str) – Name of the column identifying the replica.

  • mode (str, optional) – “per_sim”, “per_rep”, or “both”. Default “both”.

  • unit (str, optional) – “rad” or “deg”. If None (default), the unit is detected automatically.

  • n_grid (int, optional) – Number of points in the KDE evaluation grid. Default 360.

  • kappa (float, optional) – Fixed concentration parameter for the von Mises distribution. If None (default), it is estimated from the data independently for each group (curve).

  • kappa_adjust (float, optional) – Multiplier applied to the auto-estimated kappa (only when kappa=None) – circular analogue of sns.kdeplot’s bw_adjust. sns.kdeplot’s bw_adjust – but inverted, since kappa is a concentration parameter (like an inverse bandwidth): values >1 SHARPEN/narrow the curve (higher concentration), <1 widen/smooth it (lower concentration). Default 1.0 (no adjustment).

  • max_data (int, optional) – Maximum number of points per group used in the KDE. Default 50000.

  • palette (str, optional) – Seaborn palette used for simulations. Default “tab10”.

  • fill (bool, optional) – If True, shade the area under each curve (like sns.kdeplot(…, fill=True)). Default False.

  • fill_alpha (float, optional) – Opacity of the filled area when fill=True. Default 0.25.

  • linewidth (float, optional) – Line width for the KDE curves. Default 1.5.

  • linestyle (str, optional) – Line style for the KDE curves (matplotlib linestyle spec, e.g. “-”, “–”, “:”). Default “-“.

  • line_alpha (float, optional) – Opacity of the curve lines themselves. Default 0.85.

  • ax (matplotlib.axes._subplots.AxesSubplot, optional) – Axis to draw on. Ignored if mode=”both” (two axes are created). Default None.

  • context (str, optional) – Seaborn plotting context. Default “notebook”.

  • xlabel (str, optional) – Label for the x-axis. Default uses the column name x.

  • title (str, optional) – Title (global in “both” mode, axis title otherwise).

  • output_file_name (str, optional) – If non-empty, path to save the figure.

  • figsize (tuple, optional) – Figure size. Default (7, 5) for a single panel, (12, 4.5) for the “both” mode.

  • legend_loc (str, optional) – Legend position. Default None uses a sensible placement.

  • legend_bbox_to_anchor (tuple, optional) – Legend anchor. Default None uses an automatic placement.

  • legend_ncol (int, optional) – Number of columns in the legend. Default None.

Returns:

ax (matplotlib.axes._subplots.AxesSubplot or np.array of AxesSubplot) – The axis (single-panel mode) or both axes (“both” mode).

Free-energy landscapes

plot_free_energy plots a 2D free-energy landscape from two raw feature series, estimated from their joint histogram via Boltzmann inversion (\(F = -kT \ln p\)).

RepLikCompare.plotting.plot_free_energy.plot_free_energy(xall, yall, weights=None, ax=None, nbins=100, ncontours=100, avoid_zero_count=False, minener_zero=True, kT=2.479, vmin=None, vmax=None, cmap='nipy_spectral', cbar=True, cbar_label='free energy (kJ/mol)', cax=None, levels=None, cbar_orientation='vertical', norm=None, range=None, level_gap=None, context='talk', xlabel=None, ylabel=None, xlim=None, ylim=None, title=None, output_file_name='', save_fig=True)[source]

Plot a 2D free-energy landscape from two raw sample series, estimated from their joint histogram via \(F = -kT \ln(p)\) (Boltzmann inversion), with the global minimum shifted to zero.

Parameters:
  • xall (array-like) – Raw 1D sample arrays for the two features (e.g. two collective variables). Not pre-binned – the joint histogram is computed internally.

  • yall (array-like) – Raw 1D sample arrays for the two features (e.g. two collective variables). Not pre-binned – the joint histogram is computed internally.

  • weights (array-like, optional) – Per-sample weights for the histogram (e.g. from biased sampling). Default None (uniform weights).

  • ax (matplotlib.axes.Axes, optional) – Axes to draw on. A new figure/axes is created if None.

  • nbins (int, optional) – Number of histogram bins per axis. Default 100.

  • ncontours (int, optional) – Number of filled contour levels. Default 100.

  • avoid_zero_count (bool, optional) – Replace empty histogram bins with the smallest nonzero count instead of leaving them undefined, before taking the log. Default False.

  • minener_zero (bool, optional) – Kept for API compatibility; the minimum free energy is always shifted to zero.

  • kT (float, optional) – Thermal energy used to convert probability to free energy. Default 2.479 (kJ/mol at ~298 K).

  • vmin (float, optional) – Color-scale bounds. Bins with zero counts are assigned vmax + 0.5 so they render as the landscape’s inaccessible/forbidden regions. Default: computed from the data.

  • vmax (float, optional) – Color-scale bounds. Bins with zero counts are assigned vmax + 0.5 so they render as the landscape’s inaccessible/forbidden regions. Default: computed from the data.

  • cmap (str, optional) – Matplotlib colormap. Default “nipy_spectral”.

  • cbar (bool, optional) – Draw a colorbar. Default True.

  • cbar_label (str, optional) – Colorbar label. Default “free energy (kJ/mol)”.

  • cax (matplotlib.axes.Axes, optional) – Axes to draw the colorbar on, instead of stealing space from ax.

  • levels (int, optional) – If given, use exactly this many evenly-spaced contour/colorbar levels instead of ncontours.

  • cbar_orientation (str, optional) – Colorbar orientation. Default “vertical”.

  • norm (matplotlib.colors.Normalize, optional) – Custom color normalization for the contour fill.

  • range (array-like, optional) – [[xmin, xmax], [ymin, ymax]] histogram range, forwarded to numpy.histogram2d(). Default: data range.

  • level_gap (float, optional) – Alternative to levels: derive the number of contour levels from a fixed free-energy spacing (kT units) between them.

  • context (str, optional) – Seaborn plotting context. Default “talk”.

  • xlabel (str, optional) – Axis labels. Default: inferred from xall/yall names if available.

  • ylabel (str, optional) – Axis labels. Default: inferred from xall/yall names if available.

  • xlim (tuple, optional) – Axis limits.

  • ylim (tuple, optional) – Axis limits.

  • title (str, optional) – Plot title. Default: built from xlabel/ylabel.

  • output_file_name (str, optional) – If given (and save_fig is True), the figure is saved to this path.

  • save_fig (bool, optional) – Whether output_file_name (if given) is actually written to disk. Default True.

Returns:

  • fig (matplotlib.figure.Figure) – The figure containing the plot.

  • ax (matplotlib.axes.Axes) – The axes containing the plot.

  • misc (dict) – Extra objects for further tweaking: mappable (the contour set) and, if cbar=True, cbar (the colorbar object).

plot_free_energy_facet is the faceted version: instead of one global landscape, it draws one local landscape per system (or other grouping column), optionally sharing a common color scale so the panels stay directly comparable.

RepLikCompare.plotting.plot_free_energy.plot_free_energy_facet(df, x, y, facet_col, facet_order=None, ncols=3, figsize_per_facet=(8, 8), shared_colorscale=True, global_density=False, density_alpha=0.5, density_color='black', density_kwargs=None, output_file_name='', context='talk', title=None, save_fig=True, **plot_kwargs)[source]

Faceted version of plot_free_energy(): draws one free-energy landscape per value of facet_col (e.g. one local landscape per system) instead of a single global map, so groups can be compared side by side.

Parameters:
  • df (pandas.DataFrame) – Long-format dataframe containing the x, y and facet_col columns.

  • x (str) – Column names of the two raw sample series to bin per facet.

  • y (str) – Column names of the two raw sample series to bin per facet.

  • facet_col (str) – Column whose unique values define one sub-panel each.

  • facet_order (list, optional) – Explicit ordering of facet values. Default: sorted unique values.

  • ncols (int, optional) – Number of sub-panel columns in the grid. Default 3.

  • figsize_per_facet (tuple, optional) – Size of a single sub-panel; the full figure scales with ncols and the number of rows. Default (8, 8).

  • shared_colorscale (bool, optional) – Compute a single vmin/vmax free-energy range from the pooled data and reuse it for every sub-panel, so colors stay directly comparable across facets. Default True.

  • global_density (bool, optional) – Overlay a 2D KDE density contour of the pooled (x, y) distribution on each sub-panel. Default False.

  • density_alpha (optional) – Styling for the density overlay.

  • density_color (optional) – Styling for the density overlay.

  • density_kwargs (optional) – Styling for the density overlay.

  • output_file_name (str, optional) – If given (and save_fig is True), the figure is saved to this path.

  • context (str, optional) – Seaborn plotting context. Default “talk”.

  • title (str, optional) – Overall figure title. Default: built from x/y/facet_col.

  • save_fig (bool, optional) – Whether output_file_name (if given) is actually written to disk. Default True.

  • **plot_kwargs – Additional keyword arguments forwarded to plot_free_energy() for each sub-panel (e.g. nbins, cmap, kT, vmin, vmax).

Returns:

  • fig (matplotlib.figure.Figure) – The figure containing all sub-panels.

  • axes (numpy.ndarray of matplotlib.axes.Axes) – The grid of sub-panel axes.

RMSD / RMSF

plot_rmsd plots RMSD as a function of time/frame.

RepLikCompare.plotting.plot_rmsd.plot_rmsd(df, time_col, rmsd_col, sim_name_col=None, replica_col=None, hue='sim_name', palette='tab10', ax=None, **kwargs)[source]

Plot RMSD as a function of time/frame, one line per system/replica.

Parameters:
  • df (pandas.DataFrame) –

    Long-format dataframe, one row per frame, with columns:

    • time_col: time or frame index (x-axis).

    • rmsd_col: precomputed RMSD value for that frame (y-axis), e.g. backbone RMSD to a reference structure, in whatever unit it was computed (typically nm or Angstrom – label your axis accordingly via kwargs/afterwards, this function doesn’t assume a unit).

    • sim_name_col / replica_col (optional): identify which system/replica each row belongs to, used for coloring/ faceting.

  • time_col (str) – Column with time or frame index.

  • rmsd_col (str) – Column with the precomputed RMSD value.

  • sim_name_col (str or None, default None) – Columns identifying system/replica. At least one should be given if df contains more than one trajectory, otherwise all rows are drawn as a single line.

  • replica_col (str or None, default None) – Columns identifying system/replica. At least one should be given if df contains more than one trajectory, otherwise all rows are drawn as a single line.

  • hue ({"sim_name", "replica", "both", "replica_shaded", None}, default "sim_name") –

    What to color lines by:

    • ”sim_name”: one color per system; if replica_col is also given, every replica of a system is drawn (via units) but ALL share that system’s single color – lines overlap in the same hue, useful to see the system-level envelope but replicas aren’t individually distinguishable by color.

    • ”replica”: one color per replica value. Only meaningful when df is restricted to a single system (otherwise replica numbers that repeat across systems – e.g. 1,2,3… – would be colored as if they were the same replica; filter by system first, e.g. via Dataset._select_data(sim_name=…)).

    • ”both”: one color per (sim_name, replica) combination, using a plain palette (no visual grouping by system).

    • ”replica_shaded”: like “both”, but colors are a per-system base color shaded lighter/darker per replica (same idea as plot_vonmises’s per-replica mode) – so replicas of the same system are visually grouped by hue family while remaining individually distinguishable. This is what you want for “RMSD per replica, same color family per system” across MULTIPLE systems at once. Requires both sim_name_col and replica_col.

    • None: no hue, all rows drawn as a single line/color.

  • palette (str or list, optional) – Seaborn palette (name) or explicit color list. Used for all hue modes; for “replica_shaded” it’s the base palette (one color per system, then shaded per replica). Default “tab10”.

  • ax (matplotlib.axes.Axes or None, default None) – Axes to draw on. A new figure/axes is created if not given.

  • **kwargs – Forwarded to seaborn.lineplot.

Returns:

matplotlib.axes.Axes – Always returned (whether or not ax was passed in) – grab it to customize the plot further, e.g. ax.set_ylim(…), ax.figure.savefig(…).

Examples

RMSD per replica, all systems at once, same color family per system:

ax = plot_rmsd(df, "frame", "RMSD", sim_name_col="sim_name",
                replica_col="replica", hue="replica_shaded")

RMSD per replica within a single system (plain distinct colors):

wt_df = df[df["sim_name"] == "WT"]
ax = plot_rmsd(wt_df, "frame", "RMSD", replica_col="replica", hue="replica")

plot_rmsf plots RMSF as a function of residue/atom index.

RepLikCompare.plotting.plot_rmsf.plot_rmsf(df, residue_col, rmsf_col, sim_name_col=None, replica_col=None, kind='line', hue='sim_name', palette='tab10', ax=None, **kwargs)[source]

Plot RMSF as a function of residue number/id.

Parameters:
  • df (pandas.DataFrame) –

    One row PER RESIDUE (per system/replica if applicable) – NOT per frame. Expected columns:

    • residue_col: residue number or id (x-axis). Should be numeric or at least sortable; the plot is sorted by this column before drawing.

    • rmsf_col: precomputed RMSF value for that residue (y-axis), typically in Angstrom or nm.

    • sim_name_col / replica_col (optional): identify system/ replica, used for coloring/averaging depending on hue.

  • residue_col (str) – Column with residue number/id.

  • rmsf_col (str) – Column with the precomputed RMSF value.

  • sim_name_col (str or None, default None) – Column identifying the system; used for coloring. If None, all rows are drawn as a single series.

  • replica_col (str or None, default None) – Column identifying the replica.

  • kind ({"line", "bar"}, default "line") – “line” draws a curve per group. “bar” draws grouped bars – more readable for a small number of residues, cluttered for a full protein. hue=”replica_shaded” (individual per-replica lines) is only supported for kind=”line”.

  • hue ({"sim_name", "replica_shaded", None}, default "sim_name") –

    What to color by:

    • ”sim_name” (default): one curve per system. If replica_col is also given, replicas are AVERAGED per (system, residue) into that one curve, with the across-replica std shown as a shaded band (kind=”line” only) – this is a summary view, individual replicas are not separately visible.

    • ”replica_shaded”: one line per individual (system, replica) pair, NOT averaged – a per-system base color shaded lighter/darker per replica (same idea as plot_vonmises’s per-replica mode and plot_rmsd’s hue=”replica_shaded”), so replicas of the same system are visually grouped by hue family while remaining individually distinguishable. This is what you want for “RMSF per replica, same color family per system”. Requires both sim_name_col and replica_col.

    • None: no hue, all rows drawn as a single series (with sim_name_col/replica_col ignored for coloring).

  • palette (str or list, optional) – Seaborn palette (name) or explicit color list. For hue=”replica_shaded” it’s the base palette (one color per system, then shaded per replica). Default “tab10”.

  • ax (matplotlib.axes.Axes or None, default None) – Axes to draw on. A new figure/axes is created if not given.

  • **kwargs – Forwarded to seaborn.lineplot / seaborn.barplot.

Returns:

matplotlib.axes.Axes – Always returned – grab it to customize the plot further, e.g. ax.set_ylim(…), ax.figure.savefig(…).

Examples

RMSF per system, averaged over replicas with a std band:

ax = plot_rmsf(df, "residue", "rmsf", sim_name_col="sim_name",
                replica_col="replica")  # hue="sim_name" default

RMSF per individual replica, same color family per system:

ax = plot_rmsf(df, "residue", "rmsf", sim_name_col="sim_name",
                replica_col="replica", hue="replica_shaded")

Contact maps

plot_contact_map draws a residue-residue (or atom-atom) contact map as a heatmap.

RepLikCompare.plotting.plot_contact_map.plot_contact_map(df=None, resi_col=None, resj_col=None, value_col=None, precomputed_matrix=None, compare_to=None, compare_precomputed_matrix=None, aggfunc='mean', symmetric=True, cmap=None, ax=None, **kwargs)[source]

Draw a residue-residue contact map as a heatmap.

Parameters:
  • df (pandas.DataFrame or None) – Long-format dataframe with one row per (residue_i, residue_j) observation (e.g. one row per frame per contact pair, or already-aggregated one row per pair). Required unless precomputed_matrix is given instead.

  • resi_col (str) – Columns with the two residue numbers/ids of each pair. Order within a pair does not need to be consistent (i,j) vs (j,i) – both are folded into the same symmetric matrix cell when symmetric=True.

  • resj_col (str) – Columns with the two residue numbers/ids of each pair. Order within a pair does not need to be consistent (i,j) vs (j,i) – both are folded into the same symmetric matrix cell when symmetric=True.

  • value_col (str or None, default None) –

    Column with the value to aggregate into each matrix cell, e.g.:

    • a binary 0/1 “in contact this frame” flag -> aggregated with aggfunc=”mean” gives contact FREQUENCY (fraction of frames in contact), the most common use case.

    • a continuous distance -> aggregated with aggfunc=”mean” gives mean distance per residue pair.

    If None, df is assumed to already be one row per (residue_i, residue_j) pair with the value implicitly being a contact COUNT, and the matrix is built from value_col=None by counting rows per pair instead.

  • precomputed_matrix (pandas.DataFrame or None, default None) – Use this instead of df/resi_col/resj_col/value_col if you already have a square residue x residue matrix (index and columns = residue numbers). Takes precedence over df if both are given.

  • compare_precomputed_matrix (compare_to /) – df/precomputed_matrix, default None If given, the plotted matrix is (matrix_from_df - matrix_from_compare_to) instead of the raw matrix – useful to visualize which contacts are gained/lost between two systems (e.g. WT vs mutant, or bound vs unbound). Residues present in only one of the two matrices are treated as 0 in the other before subtracting. Uses a diverging colormap by default in this mode.

  • aggfunc (str or callable, default "mean") – Aggregation used when pivoting long-format df into a matrix (forwarded to pandas.pivot_table). Ignored if precomputed_matrix is given.

  • symmetric (bool, default True) – If True, cell (i, j) and (j, i) are both filled with the same aggregated value (pairs given only as (i, j) in df still produce a full symmetric matrix). Set False if df already contains both orderings explicitly and should not be mirrored.

  • cmap (str or None, default None) – Colormap; defaults to “viridis” for a plain contact map, or “RdBu_r” (centered at 0) when in difference mode (compare_to/compare_precomputed_matrix given).

  • ax (matplotlib.axes.Axes or None, default None) – Axes to draw on. A new figure/axes is created if not given.

  • **kwargs – Forwarded to seaborn.heatmap.

Returns:

matplotlib.axes.Axes

Cluster timelines

plot_cluster_timeline plots how the assigned cluster changes over the course of a trajectory, and can optionally return a table of cluster-to-cluster transitions.

RepLikCompare.plotting.plot_cluster_timeline.plot_cluster_timeline(df, cluster_col, sim_name_col, replica_col=None, time_col=None, noise_labels=(-1,), palette='viridis', nan_color='lightgrey', no_data_color='white', context='notebook', xlabel=None, ylabel='Simulation', title=None, cbar_label='Cluster', figsize=None, ax=None, xtick_step=None, return_transitions=False, output_file_name='')[source]

Plot how an already-computed cluster assignment (e.g. from compute_cluster_hdbscan/compute_cluster_kmean/…) evolves over frames/time, one row per system (or per system-replica), as a categorical “timeline” heatmap. Optionally also returns a per-row transition-statistics table – this is the actual, quantitative answer to “does this trajectory transition between clusters over time, and how often” (the heatmap alone only lets you eyeball it).

The number of clusters and their labels are auto-detected from the values present in cluster_col (no need to hand-set a colormap). Two kinds of “empty” cells are distinguished, with two separate colors:

  • noise / unclustered frames (nan_color): frames where cluster_col is NaN, or equals one of noise_labels – by default (-1,), the standard scikit-learn/HDBSCAN/DBSCAN sentinel for unclustered points. IMPORTANT: if your cluster column comes from HDBSCAN or DBSCAN, its noise points are almost always labeled -1, not NaN – leaving noise_labels=(-1,) at its default is what makes noise render as “unclustered” instead of as a spurious extra cluster.

  • missing data / padding (no_data_color): frames beyond the end of a shorter row, when rows (systems/replicas) don’t all have the same number of frames. Without this distinction these would be visually indistinguishable from real noise.

Parameters:
  • df (pandas.DataFrame) – Dataframe containing, for each frame, a cluster column, a sim_name column (and optionally a replica column).

  • cluster_col (str) – Name of the column holding the cluster label (may contain NaN and/or a noise sentinel such as -1 for unclustered points).

  • sim_name_col (str) – Name of the column identifying the simulation/system (one timeline row per unique value, unless replica_col is given).

  • replica_col (str, optional) – Name of the column identifying the replica. If given, one timeline row is drawn per (sim_name, replica) pair instead of per sim_name alone. Default None.

  • time_col (str, optional) – Name of the time/frame column used to order each series before plotting, and to label the x-axis with real time/frame values instead of raw array positions (labels are taken from the longest row, assuming a shared time axis across rows – if rows use genuinely different time axes, treat the x-axis as approximate). If None (default), the dataframe’s existing row order is used as-is (assumes already sorted by frame) and the x-axis just shows position indices.

  • noise_labels (tuple/list/set or None, optional) – Cluster values to treat as “noise/unclustered” in addition to actual NaN. Default (-1,) (HDBSCAN/DBSCAN convention). Pass None or () if your cluster labels have no noise sentinel (e.g. KMeans/GMM/hierarchical clustering, where every frame has a real cluster assignment).

  • palette (str, list, or dict, optional) –

    Colors for the real clusters (one per detected cluster value). Accepts:

    • a str: seaborn palette name (e.g. “viridis”, “tab10”).

    • a list: explicit colors, assigned in sorted cluster-value order.

    • a dict {cluster_value: color}: manual, explicit assignment – every real cluster value must have an entry, or a ValueError is raised (no silent fallback to a default color for a forgotten value). Use this when you need a specific, reproducible color per cluster (e.g. matching an external legend/figure).

    Default “viridis”.

  • nan_color (str, optional) – Color for noise/unclustered frames. Default “lightgrey”.

  • no_data_color (str, optional) – Color for padding (frames beyond a row’s real length, when rows have unequal length). Default “white”.

  • context (str, optional) – Seaborn context. Default “notebook”.

  • xlabel (str, optional) – X-axis label. Default: time_col if given, else “Frame”.

  • ylabel (str, optional) – Y-axis label. Default “Simulation”.

  • title (str, optional) – Plot title. Default: f”Cluster evolution ({cluster_col})”.

  • cbar_label (str, optional) – Colorbar label. Default “Cluster”.

  • figsize (tuple, optional) – Figure size. Default: auto-computed from the number of rows and frames.

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. Default None (new figure).

  • xtick_step (int, optional) – Step between x-axis ticks. Default: ~10 ticks spread over the full width.

  • return_transitions (bool, optional) – If True, also return a per-row transition-statistics DataFrame (see below). Default False.

  • output_file_name (str, optional) – If non-empty, path to save the figure to.

Returns:

  • ax (matplotlib.axes.Axes) – If return_transitions=False (default).

  • (ax, transitions_df) (tuple) – If return_transitions=True. transitions_df has one row per (sim_name[, replica]) with columns: sim_name[, replica], n_frames, n_transitions, transition_rate (transitions per frame – 0 means the trajectory never left its first state), n_clusters_visited, noise_frac (fraction of frames that were noise/unclustered), dominant_cluster (most visited real cluster), dominant_frac (fraction of frames spent in dominant_cluster). A row with transition_rate == 0 never transitioned; consistently high transition_rate across replicas of a system suggests that system doesn’t settle into a stable conformational state (or that the clustering is too fine- grained / noisy for this feature).

Secondary-structure timelines

compute_secondary_structure_timeline plots secondary-structure assignment (e.g. DSSP output) as a function of residue and time, one row per residue.

RepLikCompare.plotting.compute_secondary_structure_timeline.compute_secondary_structure_timeline(df, residue_col, time_col, ss_col, sim_name_col=None, replica_col=None, code_order=None, colors=None, plot=True)[source]

Summarize and (optionally) plot how each residue’s secondary structure assignment evolves over the trajectory.

Parameters:
  • df (pandas.DataFrame) –

    Long-format dataframe, one row per (residue, frame[, system, replica]), with:

    • residue_col: residue number/id.

    • time_col: frame index or time.

    • ss_col: secondary-structure code for that residue at that frame, e.g. the standard DSSP 8-letter alphabet (“H”, “G”, “I”, “E”, “B”, “T”, “S”, “C”) or a simplified 3-state scheme – any small set of string categories works, see code_order.

    • sim_name_col / replica_col (optional): if given, one timeline is produced per (sim_name, replica) group instead of pooling everything into one.

  • residue_col (str) – See above.

  • time_col (str) – See above.

  • ss_col (str) – See above.

  • sim_name_col (str or None, default None) – Grouping columns for producing one timeline per system/ replica. If both None, df is assumed to already represent a single trajectory.

  • replica_col (str or None, default None) – Grouping columns for producing one timeline per system/ replica. If both None, df is assumed to already represent a single trajectory.

  • code_order (list[str] or None, default None) – Ordered list of the secondary-structure categories expected in ss_col, used both for consistent color assignment and for the summary-table column order. Defaults to the standard DSSP 8-letter alphabet plus “-” for unassigned. Any values in ss_col not in code_order are appended at the end automatically (with a generated color) rather than dropped.

  • colors (list[str] or None, default None) – Hex colors matching code_order (same length). Defaults to a fixed DSSP-style palette when code_order is left as the default; if a custom code_order is given without matching colors, a categorical colormap (tab10/tab20) is generated automatically.

  • plot (bool, default True) – If True (and matplotlib is installed), also render a residue (y) x time (x) categorical heatmap per group.

Returns:

dict with keys

“summary_table”pandas.DataFrame

One row per (group, residue), columns = each SS code in code_order with the FRACTION of frames that residue spent in that state, plus n_frames and dominant_state (the SS code with the highest fraction). Useful for e.g. “which residues are consistently helical vs which ones flicker between states”.

”figures”dict[group_key -> (fig, ax)], only present if

plot=True.

Notebook example