nivedan gowda
nivedan gowda

Reputation: 205

Plot Network Graph and add edge weights to network edges python

I am trying to plot the network Graph with a sample data as below:-

    From    To  Density
0   A       B    296
1   B       C    258
2   C       D    296
3   D       E    274
4   E       F    272
5   F       G    195
6   G       H    286
7   H       I    257
8   I       J    204
9   J       K    66

I want to add the Density number on the edges like how many times A to B has been done and the same goes to rest. Each edge should be having the Density number above the node edge/arrow.

This is what I have tried so far:-

G = nx.from_pandas_edgelist(network_data,'FROM','TO', edge_attr='COUNT',create_using=nx.DiGraph())

fig, ax = plt.subplots(figsize=(20,15))
pos = nx.kamada_kawai_layout(G)
nx.draw_networkx_nodes(G,pos, ax = ax,node_size=1500)
nx.draw_networkx_edges(G, pos, ax=ax)
labels = nx.get_edge_attributes(G,'COUNT')
_ = nx.draw_networkx_labels(G, pos, ax=ax)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
plt.show()
    

But this solution won't give the arrows it just give me the weight between 2 nodes. and also as the data is heavy the plot looks clumsy.

I have seen some of the solutions where the width of the edges is increased but that didn't work in my case as i have 3 digit numbers for Density. I am really new to this and some help will be appreciated. Thanks in advance

Upvotes: 0

Views: 558

Answers (1)

OmriKaduri
OmriKaduri

Reputation: 316

You can use networkx.

Specifically, you can create a networkx graph from a dictionary, as:

import networkx as nx

dod = {'A': {'B': {"weight": 256}},
       'B':{'C':{'weight':258}},
       'C':{'D':{'weight':296}}}

G = nx.from_dict_of_dicts(dod)

If you'll want to draw:

pos=nx.spring_layout(G)
labels = nx.get_edge_attributes(G,'weight')
nx.draw(G,pos)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)

enter image description here

Upvotes: 3

Related Questions