如何使用Python的Multinetx库绘制指定样式的多层网络?
Complete Multilayer Network Drawing with Multinetx
Here's a polished, complete version of your code to draw the multilayer network as intended, plus explanations for key parts and troubleshooting tips:
import Multinetx as mx import matplotlib.pyplot as plt # Assuming mst_pearson, mst_kendall, mst_tail are pre-built NetworkX graphs (your MSTs) mg = mx.MultilayerGraph(list_of_layers=[mst_pearson, mst_kendall, mst_tail]) # Optional: Add inter-layer edges to connect identical nodes across layers (remove if not needed) for node in mst_pearson.nodes(): mg.add_edge((0, node), (1, node)) # Connect Pearson layer to Kendall layer mg.add_edge((1, node), (2, node)) # Connect Kendall layer to Tail layer # Hide axis for a cleaner visualization plt.axis('off') # Calculate node positions: base layout from Pearson MST, shift layers vertically pos = mx.get_position( mg, mx.fruchterman_reingold_layout(mst_pearson), layer_vertical_shift=0.2, layer_horizontal_shift=0.0, proj_angle=47 ) # Draw the full multilayer network mx.draw_networkx( mg, pos=pos, node_size=50, with_labels=False, # Set to True if you need node labels (adjust node_size if so) node_color=['#1f78b4', '#33a02c', '#e31a1c'], # Distinct colors per layer for clarity edge_color='gray', alpha=0.7 # Soften edges to avoid visual clutter ) # Add layer labels to make the plot easier to interpret plt.text(-1.2, 0.4, 'Pearson MST', fontsize=10) plt.text(-1.2, 0.0, 'Kendall MST', fontsize=10) plt.text(-1.2, -0.4, 'Tail MST', fontsize=10) # Render the final plot plt.show()
Key Improvements & Notes:
- Completed
with_labels: Set toFalsehere (small node size would make labels unreadable). Flip toTrueif you need node identifiers, and increasenode_sizeto ~150+. - Inter-layer edges: This optional block creates connections between the same node across layers—great for showing correspondence between your MSTs. Remove it if you want strictly separate layers.
- Layer-specific colors: Assigning unique colors to each layer makes it instantly clear which nodes belong to which MST.
- Layer labels: Added text annotations next to each layer so viewers don’t have to guess which is which.
- Final
plt.show(): Critical step to actually display the plot (your original code was missing this).
Troubleshooting Common Issues:
- Overlapping nodes: Increase
layer_vertical_shiftto 0.3 or higher, or switch the base layout algorithm tomx.spring_layoutfor more spread-out nodes. - Messy inter-layer edges: If you don’t want all cross-node connections, filter which nodes to link (e.g., only nodes with significant correlations).
- Import errors: Make sure Multinetx is installed correctly (
pip install multinetx) and you’re using a compatible NetworkX version (Multinetx works best with NetworkX 2.x).
内容的提问来源于stack exchange,提问作者taylor
相关产品推荐
相关产品推荐

