'NetworkX package using dataframe with weights labeled
I have a portion of dataframe as below (con_df):
from to fw
1 2 no fw
1 4 fw
2 3 no fw
2 5 no fw
2 6 no fw
2 7 fw
with 3 variables
want to make a graph using NetworkX
network = nx.from_pandas_edgelist(df=con_df, source='from', target='to',
edge_attr='fw', create_using=nx.MultiGraph())
nx.draw(network, with_labels = True)
above is the code i used, the output is below, the problem is that the weight option is not shown on the graph. i thought that the edge_attr option is for the weight attribute, but it does not work
what i want is the fw variable is being labeled in the edge of the graph
is there a problem in the code or should i approach in different way?

Solution 1:[1]
with_labels refers to the nodes labels, not that of the edges.
You need to use nx.draw_networkx_edge_labels:
labels = {x[:2]: network.get_edge_data(*x)['fw'] for x in network.edges}
pos = nx.spring_layout(network)
nx.draw(network, pos, with_labels=True)
nx.draw_networkx_edge_labels(network, pos, edge_labels=labels)
output:
content of the labels dictionary:
{(1, 2): 'no fw',
(1, 4): 'fw',
(2, 3): 'no fw',
(2, 5): 'no fw',
(2, 6): 'no fw',
(2, 7): 'fw'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

