Search code examples
pythonnetworkx

How to create a network were central nodes represent shared objects?


I want to create a network with two types of nodes : owners and shared objects. Here is a toy example, assume that 3 children : Tom, Sam and Mary share 3 pies.

Name Pie Share
Tom Chocolate 0.5
Tom Apple 0.1
Tom Pear 0.4
Sam Chocolate 0.3
Sam Apple 0.8
Sam Pear 0.4
Mary Chocolate 0.2
Mary Apple 0.1
Mary Pear 0.2

I would like to use the Network X library in Python to create the desired output : enter image description here

Where the size of the edges are weighted by the share of pie each of the child owns.


Solution

  • This is called a bipartite network, and you can create that just like a regular network.

    import networkx as nx
    
    G = nx.DiGraph()
    
    G.add_node('Tom')
    G.add_node('Sam')
    G.add_node('Mary')
    
    G.add_node('Chocolate')
    G.add_node('Apple')
    G.add_node('Pear')
    
    G.add_edge('Tom','Chocolate',weight=0.5)
    G.add_edge('Tom','Apple',weight=0.1)
    ...
    

    You drew directional links, so I used a DiGraph, but if you don't care about the direction, then you can just use a regular Graph. The fact that it's bipartite just means you can break the full network into two sets of nodes which don't share any edges.