如何将NetworkX生成的Barabasi-Albert无向图转为有向图?能否绘制出入度分布?
实现无向Barabasi-Albert图转有向图并分析度分布
完全可以实现,下面给你两种可行方案:
方案一:将现有无向图转为有向图
无向图的每条边可以直接转为双向有向边,用NetworkX的nx.DiGraph()就能快速完成转换:
import networkx as nx import matplotlib.pyplot as plt # 生成无向Barabasi-Albert图 N = 200 m = 2 G_barabasi = nx.barabasi_albert_graph(n=N, m=m) # 转为有向图(每条无向边对应两个方向的有向边) G_directed = nx.DiGraph(G_barabasi)
方案二:直接生成原生有向Barabasi-Albert图
NetworkX提供了专门的有向版模型nx.directed_barabasi_albert_graph,生成的图更贴合有向网络的演化逻辑,推荐优先使用:
# 直接生成有向Barabasi-Albert图 # 参数说明:n=节点总数,m=每个新节点连接的已有节点数,alpha=偏好连接权重(默认1) G_directed = nx.directed_barabasi_albert_graph(n=N, m=m, alpha=1.0)
绘制入度和出度分布
不管用哪种方法得到有向图,都可以用以下代码统计并可视化度分布:
# 提取所有节点的入度和出度 in_degrees = [d for _, d in G_directed.in_degree()] out_degrees = [d for _, d in G_directed.out_degree()] # 绘制常规直方图 plt.figure(figsize=(12, 5)) # 入度分布 plt.subplot(1, 2, 1) plt.hist(in_degrees, bins=15, edgecolor='black') plt.title('入度分布') plt.xlabel('入度值') plt.ylabel('节点数量') # 出度分布 plt.subplot(1, 2, 2) plt.hist(out_degrees, bins=15, edgecolor='black') plt.title('出度分布') plt.xlabel('出度值') plt.ylabel('节点数量') plt.tight_layout() plt.show()
如果想验证幂律特性,可改用双对数坐标绘制:
plt.figure(figsize=(12, 5)) # 入度分布(双对数) plt.subplot(1, 2, 1) plt.hist(in_degrees, bins=15, edgecolor='black', log=True) plt.title('入度分布(双对数)') plt.xlabel('入度值') plt.ylabel('节点数量(对数)') # 出度分布(双对数) plt.subplot(1, 2, 2) plt.hist(out_degrees, bins=15, edgecolor='black', log=True) plt.title('出度分布(双对数)') plt.xlabel('出度值') plt.ylabel('节点数量(对数)') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者MansaSeyi
相关产品推荐
相关产品推荐

