问题描述
我编写了此函数来绘制图形,但是无法正确设置边缘权重:( 尝试了所有布局!!!
def draw(triple_lst):
graph = nx.DiGraph(directed=True )
plt.figure()
options = {
'node_color': '#aaaaff','node_size': 700,'width': 2,'arrowstyle': '-|>','arrowsize': 12,'with_labels':True,'font_weight':'bold'
}
# pos = graphviz_layout(graph,prog='dot')
for triple in triple_lst :
n1 = graph.add_node(triple[0])
n2 = graph.add_node(triple[1])
graph.add_edge(triple[0],triple[1],weight=f'{triple[2]:.2f}')
nx.draw_networkx(graph,**options)
# edge_labels = dict([ ( (u,v),w['weight'] ) for u,v,w in graph.edges(data=True) if 'weight' in w ])
edge_labels = nx.get_edge_attributes(graph,'weight')
nx.draw_networkx_edge_labels(graph,pos=nx.planar_layout(graph),label_pos=0.5,edge_labels=edge_labels)
return graph
解决方法
您的脚本中有一个小错误。您应该在pos
中使用nx.draw_networkx
参数,并将其值nx.planar_layout(graph)
与nx.draw_networkx_edge_labels
方法中的参数相同。创建图形后计算布局也很重要,因此,如果取消注释pos
的计算,则在您的情况下将无法正常工作。
def
的最后一行应该是:
pos = nx.planar_layout(graph)
nx.draw_networkx(graph,**options,pos=pos)
edge_labels = nx.get_edge_attributes(graph,'weight')
nx.draw_networkx_edge_labels(graph,pos=pos,label_pos=0.5,edge_labels=edge_labels)
return graph