将gephi文件导入到networkx中使用

发布时间 2023-07-15 11:40:17作者: Victooor_swd

最近基于Transbigdata库编写代码获取了某市轨道交通网络的邻接表及shp文件,并使用Gephi对轨道交通网络进行了可视化处理,之后想尝试一下把Gephi的成果快捷地转为networkx格式来计算各种指标,编写了一些代码,步骤如下:

1.将gephi成果导出

打开gephi文件后点击文件—输出—图表文件

选择输出文件类型为json文件

 

用记事本打开json文件,可以看到文件内包括了node,edge两个表格,每个节点和边的属性以字典形式储存

2.代码

在得到了json文件后,编写代码读取json文件并转为networkx的图格式

 1 import csv
 2 import json
 3 import networkx as nx
 4 import matplotlib.pyplot as plt
 5 
 6 #创新新的图对象G
 7 G = nx.Graph()
 8 
 9 
10 f = open('Untitled.json', 'r',encoding = 'utf-8')#此处将路径替换为自己的
11 content = f.read()
12 a = json.loads(content)
13 print(type(a))
14 list_1=a['nodes']
15 list_2=a['edges']
16 dic={}
17 #对点进行处理
18 for lis1 in list_1:
19     pid=lis1['key']
20     label=lis1['attributes']['label']
21     lon=lis1['attributes']['lon']
22     lat=lis1['attributes']['lat']
23     dic[pid]=label
24 #    print(pid,label,lon,lat)此处输出每个节点的信息
25 #在G中添加点
26     G.add_node(label,lon = lon,lat = lat)
27 #print(dic)此处输出最终的节点字典
28 
29 #对边进行处理
30 for lis2 in list_2:
31     s=lis2['source']
32     t=lis2['target']
33     source=dic[s]
34 #    print('source:',source)此处输出每个边的源节点
35     target=dic[t]
36 #    print('target',target)此处输出每个边的目标节点
37 #设置权重
38     wei=lis2['attributes']['weight']
39 #    print(source,target,wei)此处输出边的信息
40 #添加边
41     G.add_edge(source,target,weight=weigh)
42 
43 print(G.nodes(data = True))
44 print(G.edges(data=True))
45 nx.draw(G,node_size = 30)
46 plt.show()

最终得到networkx的加权网络G

 

后续再写一下如何基于transbigdata库获取地铁网络邻接表和shp文件,以及如何通过坐标点绘图和调整节点及边的图像属性