根据列表/字典动态更改 networkx 中箭头的大小

Ant*_*ton 5 python data-visualization networkx

我可以通过将值列表传递给 draw_network 函数来动态更改节点大小或节点颜色。但是我怎样才能用 ArrowStyle 做到这一点?假设我想根据值列表更改 ArrowStyle(宽度和长度)。除了单个 int 值外,箭头大小也不接受任何其他内容。

这是一个示例代码:

import matplotlib.patches
import networkx as nx
G = nx.DiGraph()
G.add_edge("reddit", "youtube")
G.add_edge("reddit", "google")
G.add_edge("google", "reddit")
G.add_edge("youtube", "reddit")
print(G.adj)

testArrow = matplotlib.patches.ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.1)


nx.draw_networkx(G,
             arrowsize=30,
             node_size=[5000,50,300],
             arrowstyle=testArrow)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

zoh*_*kom 5

要更改箭头的尺寸:

根据文档,没有选项可以在一次调用中执行此操作。不过,可以通过如下一条一条地绘制边缘来完成:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edge("reddit", "youtube", w=5)
G.add_edge("reddit", "google", w=10)
G.add_edge("google", "reddit", w=30)
G.add_edge("youtube", "reddit", w=20)
print(G.adj)

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=[5000, 50, 300])
nx.draw_networkx_labels(G, pos)
for edge in G.edges(data=True):
    w = edge[2]['w']
    nx.draw_networkx_edges(G, pos, edgelist=[(edge[0],edge[1])], arrowsize=w, node_size=[5000, 50, 300])
plt.show()
Run Code Online (Sandbox Code Playgroud)

这会带来这样的结果:

在此输入图像描述

要更改边缘的尺寸:

边缘的宽度和长度之间存在概念上的差异。虽然宽度是可配置的并且可以轻松设置每条边,但长度是由节点的位置定义的。

要以与节点大小和颜色类似的方式更改边的宽度,您可以调用draw_networkx_edges,并且参数“width”接受浮点数或浮点数数组。

要更改边的长度,您必须更改布局,由 nx.draw_networkx 中的 'pos' 参数设置。默认使用弹簧布局定位。