gpt4 book ai didi

python - 如何向networkx中的ndarrary邻接矩阵添加属性?

转载 作者:行者123 更新时间:2023-12-04 08:46:17 28 4
gpt4 key购买 nike

最初我有一个标签 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方法将数据加载到ndarrary。我已成功加载数据,但我不知道如何标记它们。
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.]]
顺便说一句,我可以只输入原始数据帧中的数据而不是使用邻接矩阵吗?

最佳答案

您可以同时显示边和节点标签。假设你有邻接矩阵和标签列表:

# 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 的属性的文件。

关于python - 如何向networkx中的ndarrary邻接矩阵添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64300999/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com