登录/注册
tom
1857
占位
1
占位
0
浏览量
占位
粉丝
占位
关注
用NetworkX生成并绘制(带权)无向图
tom
2022-06-07 09:30:09 2022-06-07
37
0

NetworkX是一个非常强大的网络科学工具,它封装了图的数据结构和许多经典图算法,也内置了许多可视化函数可供调用。

1. 随机图生成

最经典的随机图当属我们在上一篇博客《Erdos-Renyi随机图的生成方式及其特性》中讲到的Erdős-Rény随机图了,我们这里选用其中的

(𝐺_{np})

形式,调用以下API:

G = nx.erdos_renyi_graph(10, 0.3, seed=1)

这里表示生成10个顶点的图,且图的每条边都以0.3的概率产生。

当然,此时生成的图不具有权重,我们想在此基础上均匀随机初始化[0, 0.4]之间的权重,可以这样写:

G = nx.Graph()
for u, v in nx.erdos_renyi_graph(10, 0.3, seed=1).edges():
G.add_edge(u, v, weight=random.uniform(0, 0.4))

2. 2D布局可视化

随机图生成好之后,我们就要对其进行可视化了。首先我们需要计算每个节点在图中摆放的位置,经典的Fruchterman-Reingold force-directed 算法可以完成这个操作,对应NetworkX中的spring_layout函数:

pos = nx.spring_layout(G, iterations=20) #我们设算法迭代次数为20次

然后就可以分别绘制图的边、节点和节点标签了:

nx.draw_networkx_edges(G, pos, edge_color="orange")
nx.draw_networkx_nodes(G, pos, node_color="black")
nx.draw_networkx_labels(G, pos, font_color="white")
plt.show()

绘图结果如下:

NLP多任务学习

当然,这样图的权值是无法体现于图上的,如果我们需要图的权值体现于图上,可以使图中边的宽度按照权值大小来设置:

nx.draw_networkx_edges(G,pos, width=[float(d['weight']*10) for (u,v,d) in G.edges(data=True)], edge_color="orange")
nx.draw_networkx_nodes(G,pos, node_color="black")
nx.draw_networkx_labels(G, pos, font_color="white")
plt.show()

此时的绘图结果如下:

NLP多任务学习

3. 3D布局可视化

如果你觉得2D布局过于扁平,还不够直观地体现节点之间的拓扑关系,那你可以采用如下的代码对图进行三维可视化:

# 3d spring layout
pos = nx.spring_layout(G, dim=3, seed=779)
# Extract node and edge positions from the layout
node_xyz = np.array([pos[v] for v in sorted(G)])
edge_xyz = np.array([(pos[u], pos[v]) for u, v in G.edges()])
# Create the 3D figure
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
# Plot the nodes - alpha is scaled by "depth" automatically
ax.scatter(*node_xyz.T, s=100, ec="w")
# Plot the edges
for vizedge in edge_xyz:
ax.plot(*vizedge.T, color="tab:gray")
def _format_axes(ax):
"""Visualization options for the 3D axes."""
# Turn gridlines off
ax.grid(False)
# Suppress tick labels
for dim in (ax.xaxis, ax.yaxis, ax.zaxis):
dim.set_ticks([])
# Set axes labels
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
_format_axes(ax)
fig.tight_layout()
plt.show()

此时的绘图结果如下:

NLP多任务学习

参考

暂无评论