问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

NetworkX绘图,更上一层

创作时间:
作者:
@小白创作中心

NetworkX绘图,更上一层

引用
1
来源
1.
https://cloud.tencent.com/developer/article/2427400

NetworkX是Python中一个强大的图论和网络分析库,广泛应用于社交网络分析、生物信息学、计算机网络等领域。本文将详细介绍NetworkX的高级绘图功能,包括自定义图形边缘色、中心点、节点颜色、布局等,并通过具体代码示例帮助读者掌握这些技巧。

自定义边缘色图Edge Colormap

通过自定义边缘色,可以更直观地展示图中边的属性或权重。以下是一个使用颜色映射绘制星星图的示例:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.star_graph(20)  # 创建星星图;参数表示中心点的邻居数量
pos = nx.spring_layout(G, seed=63)   # 布局设置
colors = range(20)  # 颜色设置
options = {   # 绘图选项
    "node_color": "#A01BE2", # 点的颜色
    "edge_color": colors,  # 边缘色
    "width": 3,  # 宽线条度
    "edge_cmap": plt.cm.Blues,
    "with_labels": True,   # 是否显示数值
}
nx.draw_networkx(G, pos, **options)
plt.show()  

自定义图形中心点

在某些情况下,我们可能希望将某个特定节点设置为中心点,其他节点围绕其布局。以下是一个将第5个节点设置为中心点的示例:

G = nx.path_graph(20) # 20个节点
center_node = 5   # 中心节点
edge_nodes = set(G) - {center_node}  # 边缘节点
pos = nx.circular_layout(G.subgraph(edge_nodes))  # 边缘节点布局
pos[center_node] = np.array([0, 0])  # 设置中心节点位置
nx.draw_networkx(G, pos, with_labels=True)  # 绘制图形  

自定义节点颜色

通过为每个节点分配不同的颜色,可以更直观地展示节点的属性或特征。以下是一个使用颜色映射绘制环形图的示例:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.cycle_graph(30)
pos = nx.circular_layout(G)
nx.draw_networkx(G, pos, node_color=range(30), node_size=600, cmap=plt.cm.Blues)
plt.show()  

自定义图形布局

对于复杂的网络图,合理的布局可以更清晰地展示网络结构。以下是一个使用社区检测算法优化布局的示例:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.davis_southern_women_graph()    
communities = nx.community.greedy_modularity_communities(G)  
superpos = nx.spring_layout(G, scale=50, seed=429)  # 计算原始图的布局
centers = list(superpos.values())
pos = {}
for center, comm in zip(centers, communities):
    pos.update(nx.spring_layout(nx.subgraph(G, comm), center=center, seed=1430))
for nodes, clr in zip(communities, ("tab:blue", "tab:orange", "tab:green")):
    nx.draw_networkx_nodes(G, pos=pos, nodelist=nodes, node_color=clr, node_size=100)
nx.draw_networkx_edges(G, pos=pos)
plt.tight_layout()
plt.show()  

权重图Weighted Graph

在实际应用中,边的权重往往反映了节点间关系的强度。以下是一个绘制带有权重的图的示例:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_edge("a", "b", weight=0.6)
G.add_edge("a", "c", weight=0.2)
G.add_edge("c", "d", weight=0.5)
G.add_edge("c", "e", weight=0.7)
G.add_edge("c", "f", weight=0.9)
G.add_edge("a", "d", weight=0.3)
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]
pos = nx.spring_layout(G,seed=7)
nx.draw_networkx_nodes(G, pos, node_size=700)
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=4)
nx.draw_networkx_edges(G, pos, edgelist=esmall, width=4, alpha=0.5, edge_color="b", style="dashed")
nx.draw_networkx_labels(G, pos, font_size=15, font_family="sans-serif")
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels)
ax = plt.gca()
ax.margins(0.08)
plt.axis("off")
plt.tight_layout()
plt.show()  

度分析degree analysis

度分析是网络分析中的重要指标,可以通过度的秩图和直方图来展示。以下是一个绘制随机图度分布的示例:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.gnp_random_graph(100, 0.02, seed=1234)
degree_sequence = sorted((d for n, d in G.degree()), reverse=True)
d_max = max(degree_sequence)
fig = plt.figure("Degree of a random graph",figsize=(8,8))
axgrid = fig.add_gridspec(5,4)
Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
pos = nx.spring_layout(Gcc, seed=1234)
nx.draw_networkx_nodes(Gcc, pos, ax=axgrid[0:3,:], node_size=20)
nx.draw_networkx_edges(Gcc, pos, ax=axgrid[0:3,:], alpha=0.4)
axgrid[0:3,:].set_title("Connected components of G")
axgrid[0:3,:].set_axis_off()
ax1 = fig.add_subplot(axgrid[3:, :2])
ax1.plot(degree_sequence, "b-", marker="o")
ax1.set_title("Degree Rank Plot")
ax1.set_ylabel("Degree")
ax1.set_xlabel("Rank")
ax2 = fig.add_subplot(axgrid[3:, 2:])
ax2.bar(*np.unique(degree_sequence, return_counts=True))
ax2.set_title("Degree histogram")
ax2.set_xlabel("Degree")
ax2.set_ylabel("# of Nodes")
fig.tight_layout()
plt.show()  

自我网络图Ego graph

自我网络图(Ego Network Graph)用于研究个体及其直接联系人之间的关系。以下是一个绘制巴尔巴西-阿尔伯特网络中度数最大节点的自我网络图的示例:

from operator import itemgetter
import matplotlib.pyplot as plt
import networkx as nx

m, n, seed = 3, 1000, 20532
G = nx.barabasi_albert_graph(n, m, seed=seed)
node_and_degree = G.degree()
(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
hub_ego = nx.ego_graph(G, largest_hub)
pos = nx.spring_layout(hub_ego, seed=seed)  
nx.draw_networkx(hub_ego, pos, node_color="b", node_size=50, with_labels=False)
options = {"node_size": 400, "node_color": "r"}
nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], **options)
plt.show()  

随机几何图Random Geometric Graph

随机几何图(Random Geometric Graph, RGG)用于模拟无线通信网络中的节点分布和连接。以下是一个绘制200个节点的随机几何图的示例:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.random_geometric_graph(200,0.125,seed=1234)  
pos = nx.get_node_attributes(G, "pos")  
dmin = 1  
n_center = 0  
for n in pos:  
    x,y = pos[n]
    d = (x - 0.5) ** 2 + (y - 0.5) ** 2
    if d < dmin:
        n_center = n
        dmin = d
p = dict(nx.single_source_shortest_path_length(G, n_center))
plt.figure(figsize=(8,8)) 
nx.draw_networkx_edges(G, pos, alpha=0.4)  
nx.draw_networkx_nodes(
    G,
    pos,
    nodelist=list(p.keys()),  
    node_size=80,
    node_color=list(p.values()),
    cmap=plt.cm.Reds_r, 
)
plt.xlim(-0.05, 1.05)  
plt.ylim(-0.05, 1.05)
plt.axis("off")   
plt.show()  

多部图Multipartite Layout

多部图(Multipartite Graph)是一种特殊的图结构,其中节点被分为多个不相交的子集,且边只存在于不同子集之间。以下是一个绘制多部图的示例:

import itertools  
import matplotlib.pyplot as plt
import networkx as nx

subset_sizes = [1, 5, 4, 3, 2, 4, 4, 3]
subset_color = ["gold","violet","violet","violet","violet","limegreen","limegreen","darkorange"]
def multilayered_graph(*subset_sizes): 
    extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))  
    layers = [range(start, end) for start, end in extents]  
    G = nx.Graph()  
    for i, layer in enumerate(layers):  
        G.add_nodes_from(layer, layer=i)
    for layer1, layer2 in nx.utils.pairwise(layers):  
        G.add_edges_from(itertools.product(layer1, layer2))  
    return G
G = multilayered_graph(*subset_sizes)  
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)] 
pos = nx.multipartite_layout(G, subset_key="layer")
plt.figure(figsize=(6, 6))
nx.draw_networkx(G, pos, node_color=color, with_labels=True)  
plt.axis("equal")
plt.show()  

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号