在图上定位边权重?

Positioning the edge weights on a graph?

我写了这个函数来画图,但是无法正确设置边权重的位置:( 尝试了所有布局!!!

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

你的脚本有点错误。您应该在 nx.draw_networkx 中使用 pos 参数,其值 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