我正在尝试使用 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
通过宽度参数,因为 nx.draw
只接受一个浮点数。权重可以通过 nx.get_edge_attributes
获得.
您也可以使用 nx.shell_layout
绘制外壳布局。并使用它来定位节点而不是 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()
关于python - 根据 NetworkX 中的权重改变边缘的厚度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62935983/