首页 > 解决方案 > 使用python将简单矩阵转换为关联矩阵

问题描述

我想从关联矩阵制作图形网络,但我没有关联矩阵,我只有一个简单的矩阵。所以我的问题是:如何将简单的矩阵转换为关联矩阵以使用 python 绘制图形网络?

在此处输入图像描述

标签: pythonmatrixgraphnetworkxadjacency-matrix

解决方案


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

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

在此处输入图像描述


推荐阅读