Search code examples
pythonnetworkxdraw

Positioning the edge weights on a graph?


I wrote this function to draw graphs, but cant make the edge weights position correctly :( tried all the layouts !!!

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


Solution

  • There is a little mistake in your script. You should use pos parameter in your nx.draw_networkx with the same value nx.planar_layout(graph) as in your nx.draw_networkx_edge_labels method. It's also important to calculate your layout AFTER you create a graph so if you uncomment your calculation of pos it won't work properly in your case.

    The last rows of your def should be:

    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