根据 NetworkX 中的权重改变边的厚度

Vary thickness of edges based on weight in NetworkX

我正在尝试使用 Python Networkx 包绘制网络图。我想根据赋予边缘的权重来改变边缘的厚度。

我正在使用以下绘制图表的代码,但我无法让边缘根据重量改变其厚度。有人可以帮我解决这个问题吗?提前致谢。

df = pd.DataFrame({ 'from':['D', 'A', 'B', 'C','A'], 'to':['A', 'D', 'A', 'E','C'], 'weight':['1', '5', '8', '3','20']})
G=nx.from_pandas_edgelist(df, 'from', 'to', edge_attr='weight', create_using=nx.DiGraph() )
nx.draw_shell(G, with_labels=True, node_size=1500, node_color='skyblue', alpha=0.3, arrows=True, 
              weight=nx.get_edge_attributes(G,'weight').values())

为了设置每条边的宽度,即使用类似数组的边,您必须使用 nx.draw_networkx_edges through the width parameter, since nx.draw only accepts a single float. And the weights can be obtaind with nx.get_edge_attributes.

您还可以使用 nx.shell_layout 使用 shell 布局绘制并使用它来定位节点而不是 nx.draw_shell:

import networkx as nx
from matplotlib import pyplot as plt

widths = nx.get_edge_attributes(G, 'weight')
nodelist = G.nodes()

plt.figure(figsize=(12,8))

pos = nx.shell_layout(G)
nx.draw_networkx_nodes(G,pos,
                       nodelist=nodelist,
                       node_size=1500,
                       node_color='black',
                       alpha=0.7)
nx.draw_networkx_edges(G,pos,
                       edgelist = widths.keys(),
                       width=list(widths.values()),
                       edge_color='lightblue',
                       alpha=0.6)
nx.draw_networkx_labels(G, pos=pos,
                        labels=dict(zip(nodelist,nodelist)),
                        font_color='white')
plt.box(False)
plt.show()