1 基本的图操作
import network as nx
import matplotlib.pyplot as plt
建立空图
# 无向图
graph = nx.Graph()
# 有向图
graph = nx.DiGraph()
添加节点
# 单个节点
graph.add_node('a')
# 点集合
graph.add_nodes_from(['1','2'])
graph.add_nodes_from(range(1, nodes_count+1))
# 输出所有节点
print(graph.nodes())
添加边
G.add_edge('1','2')
G.add_edges_from([('1','2'),('1','3')])
# 导入所有边的文件
# df = pd.read_csv(data_path, header=None)
# for edge in range(0, len(df)):
# graph.add_edge(df.loc[edge,0],df.loc[edge,1])
# print('图的边数:', graph.number_of_edges())
画图
def graph_construction(graph):
# nx.draw(graph)
# nx.draw_random(graph)
nx.draw_circular(graph)
# nx.draw_spectral(graph)
plt.show()
2 划分子图
community.community_louvain.best_partition(graph)输出:{节点编号:社区编号}
import community
subgraph = community.community_louvain.best_partition(graph)
with open('{}.csv'.format(saved_file_name),'w',encoding='utf-8',newline='') as f:
writer = csv.writer(f, dialect='excel')
write_list = []
for x in range(1, len(subgraph)):
# print('第{}个节点属于社区{}'.format(x, subgraph[x]))
write_list.append(subgraph[x])
# 按行写入
writer.writerows(map(lambda i: [i], write_list))
python文件:/GLocalKD-main/graph_construt.py