使用python将简单矩阵转换为关联矩阵

时间:2020-08-29 21:32:49

标签: python matrix graph networkx adjacency-matrix

我想从关联矩阵建立图网络,但是我没有关联矩阵, 我只有一个简单的Matrix.so,我的问题是:如何将一个简单的Matrix转换为一个入射矩阵以使用python绘制图形网络?

enter image description here

2 个答案:

答案 0 :(得分:-1)

我希望这会有所帮助,输出显示在最后

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()

enter image description here

答案 1 :(得分:-1)

这两个矩阵都是邻接矩阵。最重要的是要知道它们是不同的数据类型:

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'])

这导致处理偶发事件的方法不同以及图形的结构不同:

enter image description here

您可以轻松地注意到,第一种方法是将节点标签自动分配给索引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()