Plotting Utilities

causationentropy.core.plotting.roc_curve(TPRs, FPRs)[source]

Plot Receiver Operating Characteristic (ROC) curve.

This function creates a ROC curve visualization, which is a graphical plot that illustrates the diagnostic ability of a binary classifier system. The ROC curve plots the True Positive Rate against the False Positive Rate at various threshold settings.

The ROC curve is defined by the parametric equations:

\[ \begin{align}\begin{aligned}\text{TPR}(t) = \frac{\text{TP}(t)}{\text{TP}(t) + \text{FN}(t)} = \frac{\text{TP}(t)}{P}\\\text{FPR}(t) = \frac{\text{FP}(t)}{\text{FP}(t) + \text{TN}(t)} = \frac{\text{FP}(t)}{N}\end{aligned}\end{align} \]

where t is the classification threshold, P is the total number of positives, and N is the total number of negatives.

Parameters:
  • TPRs (array-like) – True Positive Rates (Sensitivity, Recall) for different thresholds. Values should be in [0, 1].

  • FPRs (array-like) – False Positive Rates (1 - Specificity) for different thresholds. Values should be in [0, 1].

Notes

ROC Curve Interpretation: - Perfect classifier: Curve passes through (0, 1) - high TPR, zero FPR - Random classifier: Diagonal line from (0, 0) to (1, 1) - Useless classifier: Curve below the diagonal

Key Points: - (0, 0): No false positives, but also no true positives (very conservative) - (1, 1): All positives detected, but all negatives misclassified (very liberal) - (0, 1): Perfect classification (ideal classifier)

AUC (Area Under Curve): - AUC = 1.0: Perfect classifier - AUC = 0.5: Random classifier - AUC < 0.5: Worse than random (can be inverted)

Applications: - Medical diagnosis evaluation - Network reconstruction assessment - Causal discovery method comparison - Binary classification performance analysis

The function automatically computes and displays the AUC value on the plot using the trapezoidal integration rule.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from causationentropy.core.plotting import roc_curve
>>>
>>> # Perfect classifier example
>>> tpr_perfect = [0, 1, 1]
>>> fpr_perfect = [0, 0, 1]
>>>
>>> plt.figure(figsize=(8, 6))
>>> roc_curve(tpr_perfect, fpr_perfect)
>>> plt.legend(['Perfect Classifier'])
>>> plt.show()
>>>
>>> # Random classifier comparison
>>> tpr_random = [0, 0.5, 1]
>>> fpr_random = [0, 0.5, 1]
>>> roc_curve(tpr_random, fpr_random)
>>> plt.legend(['Random Classifier'])

See also

causationentropy.core.stats.auc

Compute area under ROC curve

causationentropy.core.stats.Compute_TPR_FPR

Compute TPR and FPR from confusion matrix

causationentropy.core.plotting.plot_causal_network(G, pos=None, seed=7, figsize=(14, 14), dpi=None, node_size=8000, node_color='white', node_linewidth=5.0, edge_width_range=(1.0, 8.0), arrowsize=30, stats_fontsize=16, label_fontsize=16, legend_fontsize=10, colorbar_fontsize=14, title_fontsize=24, colormaps=None, colorblind_safe=False, show_colorbar=True, use_pvalue_alpha=True, pvalue_threshold=0.05, show_edge_labels=False, show_statistics=True, title='Discovered Causal Network', save_path=None, file_format='png', transparent=False, show_plot=True)[source]

Plot a causal network from a MultiDiGraph object with production-quality styling.

This function visualizes a causal network, accounting for edge attributes like lag, p-value, and conditional mutual information (CMI). It is designed to produce publication-quality plots with high readability, customizable styling, and multiple output options.

Parameters:
  • G (nx.MultiDiGraph) – The causal network graph to plot. Expected to have ‘lag’, ‘cmi’, and optionally ‘p_value’ as edge attributes.

  • pos (dict, optional) – A dictionary with nodes as keys and positions as values. If not provided, an optimized circular layout will be computed.

  • seed (int, default=7) – Seed for the random number generator used in layout optimization.

  • figsize (tuple of float, default=(14, 14)) – Figure size in inches (width, height).

  • dpi (int, optional) – Resolution in dots per inch. If None, uses matplotlib’s default (~100). Use 300+ for publication quality.

  • node_size (int, default=8000) – Size of nodes in the plot.

  • node_color (str, default='white') – Color of nodes.

  • node_linewidth (float, default=5.0) – Width of node borders.

  • edge_width_range (tuple of float, default=(1.0, 8.0)) – Range for edge width scaling based on CMI values (min_width, max_width).

  • arrowsize (int, default=30) – Size of arrow heads on directed edges.

  • label_fontsize (int, default=16) – Font size for node labels.

  • title_fontsize (int, default=24) – Font size for the plot title.

  • colormaps (list of str, optional) – List of matplotlib colormap names to use for different lags. If None, defaults to [‘Blues’, ‘Greens’, ‘Oranges’, ‘Purples’, ‘Reds’]. If colorblind_safe=True, this is overridden with accessible palettes.

  • colorblind_safe (bool, default=False) – If True, use colorblind-safe color palettes (viridis, plasma, cividis, etc.).

  • show_colorbar (bool, default=True) – If True, display a colorbar showing the CMI scale for each lag.

  • use_pvalue_alpha (bool, default=True) – If True, use p-value to set edge transparency (more significant = more opaque). Requires ‘p_value’ in edge attributes.

  • pvalue_threshold (float, default=0.05) – Significance threshold for filtering edges. Edges with p > threshold are drawn with reduced opacity.

  • show_edge_labels (bool, default=False) – If True, display CMI values as edge labels.

  • show_statistics (bool, default=True) – If True, display network statistics (nodes, edges, max lag) in a text box.

  • title (str, default='Discovered Causal Network') – Title for the plot.

  • save_path (str, optional) – Path to save the figure. If None, figure is not saved.

  • file_format (str, default='png') – File format for saving (‘png’, ‘pdf’, ‘svg’, ‘eps’, etc.).

  • transparent (bool, default=False) – If True, save figure with transparent background.

  • show_plot (bool, default=True) – If True, display the plot using plt.show().

  • stats_fontsize (int)

  • legend_fontsize (int)

  • colorbar_fontsize (int)

Returns:

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

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

Notes

Layout Optimization:

Nodes are arranged in a circular layout. If pos is not provided, the node order is optimized to minimize edge crossings and improve readability using simulated annealing.

Edge Rendering:
  • Edges for lag 1 are drawn as straight lines (connectionstyle radius=0).

  • Edges for lags > 1 are drawn as arcs outside the circle, with arc radius increasing for higher lags to prevent overlap.

  • Edge color and width are scaled by the CMI value within each lag group.

  • Edge transparency (alpha) is modulated by p-value if use_pvalue_alpha=True.

Color Accessibility:

When colorblind_safe=True, the function uses perceptually uniform and colorblind-accessible colormaps from matplotlib (viridis, plasma, cividis, inferno, magma). This ensures the plot is accessible to readers with color vision deficiencies.

P-value Visualization:

If edge attributes include ‘p_value’ and use_pvalue_alpha=True: - Edges with p < pvalue_threshold are drawn with alpha=1.0 (fully opaque) - Edges with p >= pvalue_threshold are drawn with alpha=0.3 (translucent) This provides a visual indication of statistical significance.

Publication Quality:
  • DPI parameter allows control of resolution (use 300-600 for journals)

  • Large fonts and thick lines ensure readability when scaled

  • Optional statistics box provides at-a-glance network properties

  • Multiple export formats supported (PNG, PDF, SVG, EPS)

Examples

Basic usage with default settings:

>>> import networkx as nx
>>> from causationentropy.core.plotting import plot_causal_network
>>> G = nx.MultiDiGraph()
>>> G.add_edge('X1', 'X2', lag=1, cmi=0.5, p_value=0.01)
>>> G.add_edge('X2', 'X3', lag=1, cmi=0.3, p_value=0.03)
>>> fig, ax = plot_causal_network(G)

Colorblind-safe plot with custom styling:

>>> fig, ax = plot_causal_network(
...     G,
...     colorblind_safe=True,
...     figsize=(16, 16),
...     node_size=10000,
...     show_edge_labels=True
... )

Save high-resolution plot for publication:

>>> fig, ax = plot_causal_network(
...     G,
...     dpi=600,
...     save_path='causal_network.pdf',
...     file_format='pdf',
...     show_plot=False
... )

Customize colors and disable statistics:

>>> custom_cmaps = ['YlOrRd', 'PuBu', 'BuGn']
>>> fig, ax = plot_causal_network(
...     G,
...     colormaps=custom_cmaps,
...     show_statistics=False,
...     title='Custom Causal Network'
... )

See also

optimize_circular_order

Optimize node ordering for circular layout

causationentropy.core.discovery.discover_network

Discover causal networks

Parameters: