simjas - 1 month ago 14

Python Question

I have projected a bipartite graph and made a new weighted graph. I would like to draw the graph, and show the edge weights.

Here is my attempt.

`import networkx as nx`

import matplotlib.pyplot as plt

from networkx.algorithms import bipartite

g=nx.Graph()

g.add_nodes_from(['s1','s2','s3','s4','s5'],bipartite=0)

g.add_nodes_from(['t1','t2','t3','t4'],bipartite=1)

g.add_edges_from([('s1','t1'),('s1','t4'),('s2','t1'),('s2','t2'),('s3','t1'),('s3','t4'),('s4','t3'),('s5','t2'),('s5','t3')])

l=bipartite.weighted_projected_graph(g,['s1','s2','s3','s4','s5'])

nx.draw(l, with_labels=True)

plt.show()

The node labels appear, but not the edge weights. How can I show the edge weights?

Answer

I've modified your code to include `nx.draw_networkx_edge_labels`

```
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
g=nx.Graph()
g.add_nodes_from(['s1','s2','s3','s4','s5'],bipartite=0)
g.add_nodes_from(['t1','t2','t3','t4'],bipartite=1)
g.add_edges_from([('s1','t1'),('s1','t4'),('s2','t1'),('s2','t2'),('s3','t1'),('s3','t4'),('s4','t3'),('s5','t2'),('s5','t3')])
l=bipartite.weighted_projected_graph(g,['s1','s2','s3','s4','s5'])
pos = nx.spring_layout(l)
nx.draw(l, pos = pos, with_labels=True)
nx.draw_networkx_edge_labels(l, pos)
```

This will probably show more than you want. I think it's set up for cases where edges may have somewhat arbitrary attributes. I think what you want is to do everything up to defining `pos`

and then:

```
edge_weights = {(u,v,):d['weight'] for u,v,d in l.edges(data=True)}
nx.draw(l, pos = pos, with_labels=True)
nx.draw_networkx_edge_labels(l,pos,edge_labels=edge_weights)
```