呵w 在networkx中将属性添加到Ndarary邻接矩阵中?

2024-04-29 19:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

最初,我在数据帧中存储了一个标签co occ网络,如下所示:

0        ['#A', '#B', '#C', '#D]
1        ['#A', '#E']
2        ['#b', '#c', '#D']
3        ['#C', '#D']

然后我把它转换成如下的邻接矩阵:

,#A,#B,#C,#D,#E,#F,#G,#H,#I,#J,#K
#A,0,1,1,0,1,1,1,1,0,1,0
#B,1,0,0,0,1,1,1,1,0,1,0
#C,1,0,0,0,1,1,1,1,0,1,0
...

我想将网络加载到networkx中,以便进行数学运算并绘制图形。因此,我使用np.genfromtext方法将数据加载到Ndarary中。我已成功加载数据,但不知道如何标记它们

mydata = genfromtxt(src5+fname[0], delimiter=',',encoding='utf-8',comments='**')
adjacency = mydata[1:,1:]
print(adjacency)


[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

顺便问一下,我可以从原始数据帧输入数据而不是使用邻接矩阵吗


Tags: 数据方法网络networkx图形np绘制数学
1条回答
网友
1楼 · 发布于 2024-04-29 19:15:16

您可以同时显示边和节点标签。

假设您有邻接矩阵和标签列表:

# matrix from question
A = np.array([[0,1,1,0,1,1,1,1,0,1,0],
[1,0,0,0,1,1,1,1,0,1,0],
[1,0,0,0,1,1,1,1,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0]])

labels = ['#A','#B','#C','#D','#E','#F','#G','#H','#I','#J','#K']

以下是一些可视化示例:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

# labels to dict
labels = {k: v for k, v in enumerate(labels)}

# create graph and compute layout coords
G = nx.from_numpy_matrix(A, parallel_edges=True)
# k controls node closeness, 0 <= k <= 1
coord = nx.spring_layout(G, k=0.55, iterations=20)

# optional: set label coords a bit upper the nodes
node_label_coords = {}
for node, coords in coord.items():
    node_label_coords[node] = (coords[0], coords[1] + 0.04)

# draw the network, node and edge labels
plt.figure(figsize=(20, 14))
nx.draw_networkx_nodes(G, pos=coord)
nx.draw_networkx_edges(G, pos=coord)
nx.draw_networkx_edge_labels(G, pos=coord)
nx.draw_networkx_labels(G, pos=node_label_coords, labels=labels)

resultion network

您可以在NetworkX documentation
上找到有关创建邻接矩阵图的更多信息

更新:
请参阅set_node_attributes函数向网络节点添加属性

degree_centr = nx.degree_centrality(G)
nx.set_node_attributes(G, degree_centr, "degree")
nx.write_gexf(G, "test.gexf")

使用write_gexf将图形保存到文件后,您将拥有一个具有适合Gephi的属性的文件

相关问题 更多 >