python - 基于列表/字典动态更改 networkx 中箭头的大小

标签 python data-visualization networkx

我可以通过将值列表传递给 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)

enter image description here

最佳答案

改变箭头的尺寸:

根据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()

这会带来这样的结果:

enter image description here

改变边的尺寸:

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

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

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

关于python - 基于列表/字典动态更改 networkx 中箭头的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073849/

相关文章:

python - 将多维数组从 perl 脚本传递到 python 脚本

python - 使用 SQLAlchemy 获取第一个和最后一个元素

javascript - 在 Javascript/Google 图表中处理来自 Excel 的大量输入数据的最佳方法

c - 从中心动画正弦波

python - 带 Python Networkx 的加权邻接列表

python - 在 Spring 布局+网络中更改节点的颜色

python - stack-less Python的微线程在游戏状态机实现上比Lua的协程有什么优势?

python - 在 Windows 10 上使用 CUDA 9.1 和 Python 3.6 安装 Tensorflow

d3.js - 如何在 D3.js 中制作多个组网络节点的凸包

python - 使用 NetworkX 查找从一个到另一个的最短和最长权重