使用 python 将简单矩阵转换为关联矩阵
convert a simple matrix to incidence matrix with python
我想从关联矩阵制作图形网络,但我没有关联矩阵,
我只有一个简单的 Matrix.so 我的问题是:如何将简单矩阵转换为关联矩阵以使用 python 绘制图形网络?
希望对您有所帮助,输出显示在最后
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()
两个矩阵都是邻接矩阵。最重要的是要知道它们是不同的数据类型:
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'])
这导致处理事件的不同方法以及不同的图形结构:
如您所见,第一种方法使用自动将节点标签分配给索引 0、1、2、3、4。
另一个令人惊讶的事实:您不需要手动收集权重。它们存储在边缘的 weight
属性中。
用法:
您可以使用 nx.get_edge_attributes(G, 'weight')
访问边缘属性。这是我简化版的图表结构:
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()
我想从关联矩阵制作图形网络,但我没有关联矩阵, 我只有一个简单的 Matrix.so 我的问题是:如何将简单矩阵转换为关联矩阵以使用 python 绘制图形网络?
希望对您有所帮助,输出显示在最后
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()
两个矩阵都是邻接矩阵。最重要的是要知道它们是不同的数据类型:
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'])
这导致处理事件的不同方法以及不同的图形结构:
如您所见,第一种方法使用自动将节点标签分配给索引 0、1、2、3、4。
另一个令人惊讶的事实:您不需要手动收集权重。它们存储在边缘的 weight
属性中。
用法:
您可以使用 nx.get_edge_attributes(G, 'weight')
访问边缘属性。这是我简化版的图表结构:
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()