i want to make graph network from incidence Matrix, but i don't have an incidence Matrix, i have just a simple Matrix.so my question is: how to convert a simple Matrix to a incidence Matrix to draw a graph network with python?
Asked
Active
Viewed 1,136 times
-2
-
Do you now a shape of matrix? – mathfux Aug 29 '20 at 21:41
2 Answers
-1
I hope this is helpful, the output is shown at the end
import numpy as np
import networkx as nx #version 2.2
import matplotlib.pyplot as plt
import pandas as pd
# matrix goes here
Mat = [
[0,0,-1,0,0],
[1,1,-1,-1,0],
[1,-1,0,0,0],
[1,0,0,-1,0],
[1,0,1,-1,1]
]
A = pd.DataFrame(Mat)
#refine rowname and colnames
nodes = ["a","b","c","d","e"]
A.index = nodes
A.columns = nodes
#create graph
G0 = nx.from_pandas_adjacency(A)
#create weight labels
combs = {}
adjc = G0.adj
for i in adjc:
suba = adjc[i]
for j in suba:
combs[(i,j)] = suba[j]['weight']
#define network structure i.e shell
nx.draw_shell(G0, with_labels=True )
nx.draw_networkx_edge_labels(G0, pos=nx.shell_layout(G0), edge_labels=combs)
plt.draw()

hxalchemy
- 366
- 1
- 10
-1
Both matrices are adjacency matrices. The most important thing is to know that they are different datatypes:
import pandas as pd
import numpy as np
adjacency = [[0,0,-1,0,0], [1,1,-1,-1,0], [1,-1,0,0,0], [1,0,0,-1,0], [1,0,1,-1,1]]
df = pd.DataFrame(adjacency, columns = ['A','B','C','D','E'], index = ['A','B','C','D','E'])
This results in different methods of handling incidencies as well as different structure of graph:
As you can note easily, first method uses automatic assignment of node labels to indices 0, 1, 2, 3, 4.
Another surprising facts: you don't need to collect weights manually. They are stored in weight
attribute of edges.
Usage:
You can access edge attributes with nx.get_edge_attributes(G, 'weight')
. This is my simplified version of diagram structure:
G = nx.from_pandas_adjacency(df)
pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels=True, bbox = dict(fc="lightgreen", ec="black", boxstyle="circle", lw=3),
width=2, arrowsize=30)
nx.draw_networkx_edge_labels(G, pos, edge_labels = nx.get_edge_attributes(G, 'weight'))
plt.show()

mathfux
- 5,759
- 1
- 14
- 34
-
what version are you using (network-x), running your code gives me the following error TypeError: draw_networkx_edge_labels() missing 1 required positional argument: 'pos' – hxalchemy Aug 30 '20 at 00:58
-
Ah, my bad, I simplified my script too much without check :( I was using layout `pos=nx.circular_layout(G)`. Moreover, this should be used in both `draw` and `nx.draw_networkx_edge_labels`. Fixed it. – mathfux Aug 30 '20 at 08:50
-