我可以通过将值列表传递给 draw_network 函数来动态更改节点大小或节点颜色。但是我怎样才能用 ArrowStyle 做到这一点?假设我想根据值列表更改 ArrowStyle(宽度和长度)。 arrowsize 只接受一个 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)
最佳答案
改变箭头的尺寸:
根据documentation没有选项可以在一次通话中做到这一点。但是,可以通过如下方式一条一条地绘制边缘来完成:
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()
这会带来这样的结果:
改变边的尺寸:
边的宽度和长度之间存在概念上的差异。虽然宽度是可配置的并且可以很容易地为每条边设置,但长度是由节点的位置定义的。
要以类似于节点大小和颜色的方式更改边的宽度,您可以调用 draw_networkx_edges
,并且参数“宽度”接受 float 或 float 数组。
要更改边的长度,您必须更改 layout ,由 nx.draw_networkx 中的“pos”参数设置。默认使用 spring 布局定位。
关于python - 基于列表/字典动态更改 networkx 中箭头的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073849/