在图表上放置边缘权重?

问题描述

我编写了此函数来绘制图形,但是无法正确设置边缘权重:( 尝试了所有布局!!!

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

enter image description here

解决方法

您的脚本中有一个小错误。您应该在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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...