微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在networkx中向ndarrary邻接矩阵添加属性?

最初,我在这样的数据框中存储了一个hashtag 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,1,0
#B,0
#C,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,0],[1,[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的属性的文件。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。