Skip to content
Advertisement

How to draw a networkx MultiGraph for nested data that has nested nodes with sizes as values in the dict?

I am trying to show 2 graphs that are not connected which represent the data as follows –

demo_data = {"TOPIC1": {"SIZE": 50, 
                        "WORDS": {"cat": 20, "dog": 30}}, 
             "TOPIC2": {"SIZE": 25, 
                        "WORDS": {"bat": 4, "rat": 9}}}

The data is flexible in the sense that I control how it is nested/looks. The main idea is to be able to show a graph like following –

There are 2 main nodes – Topic1 and Topic2 with their sizes as 50 and 25 respectively. Topic1 is connected/surrounded by Cat node with size 20 and Dog node with size 30. Similarly for Topic2. Topic1 and Topic2 are not connected – but this is flexible. enter image description here If a different representation of the data is more suited for that, then that works too.

How do I go about making that graph from the given data? What I have tried so far is this –

import networkx as nx

demo_data = {"TOPIC1": {"SIZE": 500, "WORDS": {"cat": 1, "dog": 300}}, "TOPIC2": {"SIZE": 25, "WORDS": {"bat": 50, "rat": 90}}}

G = nx.MultiGraph()
G.add_nodes_from(demo_data.keys())
G.add_nodes_from(demo_data['TOPIC1']['WORDS'], node_size=demo_data['TOPIC1']['WORDS'].values())
G.add_nodes_from(demo_data['TOPIC2']['WORDS'], node_size=demo_data['TOPIC2']['WORDS'].values())
nx.draw(G,with_labels=True)

But the node sizes are not working, neither are the positions as I want them to be. It was also difficult to figure out how to add edges between existing nodes programmatically.

Advertisement

Answer

The node_size you are providing is an attribute of the node itself. It does not impact how it is drawn.

The size of the node that is drawn needs to be passed in the nx.draw function as a list. The default node size is 300.

One way of doing this would be like this:

demo_data = {"TOPIC1": {"SIZE": 50, 
                        "WORDS": {"cat": 20, "dog": 30}}, 
             "TOPIC2": {"SIZE": 25, 
                        "WORDS": {"bat": 4, "rat": 9}}}

for key in demo_data.keys():
  G.add_node(key, size=demo_data[key]["SIZE"] * 10)
  for animal, size in demo_data[key]["WORDS"].items():
    G.add_node(animal, size=size*10)
    G.add_edge(animal, key)

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement