【问题标题】:convert a simple matrix to incidence matrix with python [closed]使用python将简单矩阵转换为关联矩阵[关闭]
【发布时间】:2020-08-29 21:32:49
【问题描述】:

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

【问题讨论】:

  • 你现在是矩阵的形状吗?

标签: python matrix graph networkx adjacency-matrix


【解决方案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'])

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

您很容易注意到,第一种方法使用自动将节点标签分配给索引 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()

【讨论】:

  • 您使用的是什么版本(network-x),运行您的代码会出现以下错误 TypeError: draw_networkx_edge_labels() missing 1 required positional argument: 'pos'
  • 啊,我的错,我在没有检查的情况下简化了我的脚本:(我使用的是布局pos=nx.circular_layout(G)。此外,这应该在draw和nx.draw_networkx_edge_labels中都使用。修复它。
  • 非常感谢。你的回答对我帮助很大
【解决方案2】:

希望对你有帮助,输出显示在最后

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

【讨论】:

  • 非常感谢。你的回答对我帮助很大
猜你喜欢
  • 2021-12-31
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多