pythonrgraph-theorybipartitenetwork-analysis

Draw multipartite graphs with fixed levels in Python (or R)


I have two adjacency matrices a and b that express a set of relationship in a hierarchical order. Basically, the rows of a are the nodes of a, and the columns of b are the nodes of b. So the nodes of a points to the nodes of b. The same applies for b: the rows of b (that are equal to the columns of a) are the nodes of b, which point to the nodes of c, represented in the columns.

Here is a Python representation in the form of two adjacency matrices (list of lists)

import numpy as np
import pandas as pd
import networkx as nx

a_net= [[1,1,0],[0,0,0]]
b_net = [[1,0],[1,1],[0,0]]

They can be represented as pandas dataframes:

data_a = pd.DataFrame(a_net)
data_a.index = ['a1','a2'] 
data_a.columns = ['b1','b2','b3'] 

data_b = pd.DataFrame(b_net)
data_b.index = data_a.columns
data_b.columns = ['c1','c2']

matrix_a matrix_b

If necessary, I wrote a code to concatenate them into a unique matrix

#JOINING THE MATRICES INTO A UNIQUE ONE
for i in range(1,len(data_a.columns)+1):
    data_b['b'+str(i)] = [0]*len(data_b)
    
data_a['c1'] = [0]*len(data_a)
data_a['c2'] = [0]*len(data_a)

adj = pd.concat([data_a,data_b])

adj['a1'] = [0]*len(adj)
adj['a2'] = [0]*len(adj)

c1c2 = pd.DataFrame([[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]])
c1c2.index = ['c1','c2']
c1c2.columns = adj.columns

adj = pd.concat([adj,c1c2])
adj

adj_matrix

I'd like to obtain a multilayer plot were nodes that starts with "a" are at the first layer, with "b" at the second, and with "c" at the third:

plot

As you can see, I want that also nodes without links (like a2 and b3) are visualized at the right levels.

What can I do? If you know a way to do it in R it would also be good. In that case, you could run these commands to export the tables and to load them in R:

a_net.to_csv("a_net.csv")
b_net.to_csv("b_net.csv")

Solution

  • Another option:

    import pandas as pd
    import multipartitegraph as mp
    
    a_net= [[1,1,0],[0,0,0]]
    b_net = [[1,0],[1,1],[0,0]]
    c_net = [[1,1,0],[0,0,1]]
    d_net = [[0,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0]]
    
    data_a = pd.DataFrame(a_net)
    data_a.index = ['a1','a2']
    data_a.index.name = 'source'
    data_a.columns = ['b1','b2','b3'] 
    
    data_b = pd.DataFrame(b_net)
    data_b.index = data_a.columns
    data_b.index.name = 'source'
    data_b.columns = ['c1','c2']
    
    data_c = pd.DataFrame(c_net)
    data_c.index = data_b.columns
    data_c.index.name = 'source'
    data_c.columns = ['d1','d2','d3']
    
    data_d = pd.DataFrame(d_net)
    data_d.index = data_c.columns
    data_d.index.name = 'source'
    data_d.columns = ['e1','e2','e3','e4','e5']
    
    myNet = mp.Net([data_a, data_b, data_c, data_d])
    myNet.plot()
    

    enter image description here