Home > Net >  plot a dictionary of dictionary using networkx
plot a dictionary of dictionary using networkx

Time:10-27

I have this dictionary which has two dictionaries inside it

tdict={'a1':{
    'aa1':{'aaa101':{'information'},'aaa201':{'information'}},
    'aa2':{'cca101':{'information'},'aca201':{'information'}},
    'ab1':{'aasdfaa101':{'information'},'aadaa201':{'information'}}
}
       ,'a2':{
           'ab1':{'aasdfaa101':{'information'},'aadaa201':{'information'}},
           'ab2':{'zz101':{'information'},'azz201':{'information'}},
           'ac2':{'aaa101':{'information'},'aaa201':{'information'}}
       }
       ,'a3':{
           'ac1':{'aaa101':{'information'},'aaa201':{'information'}},
           'ac2':{'aaa101':{'information'},'aaa201':{'information'}}

       }}

I would like to plot the network and see each node that is connected to I used the from_dict_of_dicts method from networkx and it works but it does not show the final dict which has for example aaa201,aaa101 but only shows the keys for these two values

enter image description here

how I can include the nodes aaa201,zz101 in the same plot

CodePudding user response:

You can use recursion to traverse the dictionary and populate the graph with nodes and corresponding edges:

import networkx as nx
import matplotlib.pyplot as plt
tdict = {'a1': {'aa1': {'aaa101': {'information'}, 'aaa201': {'information'}}, 'aa2': {'cca101': {'information'}, 'aca201': {'information'}}, 'ab1': {'aasdfaa101': {'information'}, 'aadaa201': {'information'}}}, 'a2': {'ab1': {'aasdfaa101': {'information'}, 'aadaa201': {'information'}}, 'ab2': {'zz101': {'information'}, 'azz201': {'information'}}, 'ac2': {'aaa101': {'information'}, 'aaa201': {'information'}}}, 'a3': {'ac1': {'aaa101': {'information'}, 'aaa201': {'information'}}, 'ac2': {'aaa101': {'information'}, 'aaa201': {'information'}}}}
G = nx.Graph()
def create_graph(d, g, p = None):
   for a, b in d.items():
      g.add_node(a)
      if p is not None:
         g.add_edge(p, a)
      if not isinstance(b, set):
         create_graph(b, g, a)

create_graph(tdict, G)
nx.draw(G, with_labels = True)
plt.show()

Output:

enter image description here

  • Related