如何绘制网络图?附本人现有实现代码及需求说明
Hey there! Let's work through how to get your network graphs looking exactly how you want them. From your code snippet, it seems you're dealing with minimum spanning trees (MSTs) built from different correlation matrices—Pearson, Kendall, and Tail—and using a mix of NetworkX and pymnet. Let's clean up and expand your code step by step:
First, there's a small typo in your layout call (mst_pearso... should be mst_pearson). Let's also structure your imports for clarity:
import matplotlib matplotlib.use('TkAgg') # Use this backend for interactive plot windows import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx from itertools import product from scipy.sparse import csr_matrix from scipy.sparse.csgraph import minimum_spanning_tree import pymnet import matplotlib.colors as mcolors
mst_tree Function Your code references mst_tree() but doesn't include its definition. Here's a standard implementation that converts a correlation matrix to an MST NetworkX graph:
def mst_tree(corr_matrix): # Convert correlation to distance (MST uses distance metrics) dist_matrix = 1 - np.abs(corr_matrix) # Convert to sparse matrix and compute MST sparse_dist = csr_matrix(dist_matrix) mst_sparse = minimum_spanning_tree(sparse_dist) # Convert sparse MST to a NetworkX graph object mst_graph = nx.from_scipy_sparse_array(mst_sparse) return mst_graph
Now let's render your three MSTs with consistent, polished styling. You can tweak sizes, colors, and layouts to match your desired look:
# Assume you've already calculated your correlation matrices (pearson, kendall, tail) mst_pearson = mst_tree(pearson) mst_kendall = mst_tree(kendall) mst_tail = mst_tree(tail) # Set up a 3-subplot figure to compare all MSTs fig, axes = plt.subplots(1, 3, figsize=(18, 6)) # Define reusable style parameters node_size = 800 font_size = 10 edge_color = "#888888" node_color = "#4287f5" layout_seed = 42 # Use a seed for consistent, reproducible layouts # Draw Pearson Correlation MST ax1 = axes[0] pos_pearson = nx.spring_layout(mst_pearson, seed=layout_seed) nx.draw(mst_pearson, pos=pos_pearson, ax=ax1, node_size=node_size, node_color=node_color, edge_color=edge_color, with_labels=True, font_size=font_size, font_weight="bold") ax1.set_title("Pearson Correlation MST", fontsize=12) # Draw Kendall Correlation MST ax2 = axes[1] pos_kendall = nx.spring_layout(mst_kendall, seed=layout_seed) nx.draw(mst_kendall, pos=pos_kendall, ax=ax2, node_size=node_size, node_color=node_color, edge_color=edge_color, with_labels=True, font_size=font_size, font_weight="bold") ax2.set_title("Kendall Correlation MST", fontsize=12) # Draw Tail Correlation MST ax3 = axes[2] pos_tail = nx.spring_layout(mst_tail, seed=layout_seed) nx.draw(mst_tail, pos=pos_tail, ax=ax3, node_size=node_size, node_color=node_color, edge_color=edge_color, with_labels=True, font_size=font_size, font_weight="bold") ax3.set_title("Tail Correlation MST", fontsize=12) # Adjust spacing and display the plot plt.tight_layout() plt.show()
If you're aiming for a unique look—like weighted edges, colored nodes by category, or multilayer networks—here are quick tweaks:
- Weighted Edges: Map edge width to MST weights (if your graph stores them):
edge_weights = nx.get_edge_attributes(mst_pearson, 'weight') nx.draw_networkx_edges(mst_pearson, pos_pearson, ax=ax1, width=[w * 5 for w in edge_weights.values()], edge_color=edge_color) - Node Coloring by Category: Use a custom colormap for node groups:
node_categories = [0, 1, 0, 1, 2] # Example category list matching your nodes cmap = mcolors.ListedColormap(["#4287f5", "#f54242", "#42f56f"]) nx.draw(mst_pearson, pos=pos_pearson, ax=ax1, node_size=node_size, node_color=node_categories, cmap=cmap, with_labels=True) - Multilayer Networks with pymnet: If you're working with layered graphs, use pymnet's built-in drawing:
multinet = pymnet.MultilayerNetwork(aspects=1) # Add your nodes and edges to the multilayer network here pymnet.draw(multinet, layout="spring", nodeSize=0.05, edgeWidth=0.5) plt.show()
内容的提问来源于stack exchange,提问作者taylor

