繁体   English   中英

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

[英]how to add attributes to ndarrary adjacency matrix in networkx?

最初我有一个标签 co-occ.network 存储在 dataframe 中,如下所示:

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
...

我想将 .net 加载到 .networkx 中以进行数学运算并绘制图形。 所以我使用np.genfromtext方法将数据加载到 ndarrary 中。 我已成功加载数据,但我不知道如何 label 它们。

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.]]

顺便说一句,我可以不使用邻接矩阵而只输入原始dataframe的数据吗?

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

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

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

结果网络

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

更新:
参考set_node_attributes function 为your.network节点添加属性

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM