Search code examples
pythonnodesnetworkx

How to show weights as part of the plot?


How do I show the weights as part of the graph?

Plot 1

my_graph = nx.Graph()
edges = nx.read_weighted_edgelist('edges.txt')
nodes = nx.read_adjlist("nodes.txt")
pos = nx.shell_layout(my_graph)
my_graph.add_edges_from(edges.edges())
my_graph.add_nodes_from(nodes)
nx.draw(my_graph, with_labels=True)
plt.show()
plt.close()

I tried another way

labels = {e: g.edges[e]['weight'] for e in g.edges}
nx.draw_networkx_edge_labels(g,pos,edge_labels=labels)

But for this case, I get a very cluttered plot.

Plot 2

How can I get a plot like the first one but with the weights showing?


Solution

  • Use pos = nx.spring_layout(my_graph) instead of pos = nx.shell_layout(my_graph).

    The position of your nodes is determined by your layout command.