python---通过networkx使图着色结果可视化

来源:互联网 发布:淘宝上levis眼镜 编辑:程序博客网 时间:2024/05/17 11:36

假定邻接矩阵为:
0 1 1 1 0 0 1 0
1 0 1 1 1 0 0 0
1 1 0 0 1 1 1 0
1 1 0 0 1 0 1 0
0 1 1 1 0 1 1 1
0 0 1 0 1 0 0 1
1 0 1 1 1 0 0 1
0 0 0 0 1 1 1 0

根据图着色算法已求得着色方案:
1 2 3 3 1 2 2 3

接下来可视化图着色结果

import networkx as nx                   #导入NetworkX包,为了少打几个字母,将其重命名为nximport matplotlib.pyplot as plt         #导入绘图包matplotlibfile_read = open('tt.txt', 'r')file_color = open('c.txt', 'r')try:     #读入二维邻接矩阵     matrix = [[0 for x in range(8)] for y in range(8)]   #8*8的零矩阵     i = 0     for line in file_read:             #读入每一行          matrix[i] = line.split(' ')   #将每一行按空格分割          i = i + 1     #创建图        G = nx.Graph()                     #建立一个空的无向图     v = range(1, 8)                    #一维行向量,从1到8递增     G.add_nodes_from(v)                #从v中添加结点,相当于顶点编号为1到8     line = file_color.read()           #读取颜色向量     colors = (line.split(' '))         #颜色向量     for i in range(len(colors)):          colors[i] = int(colors[i])    #将字符转为数字     for x in range(0, len(matrix)):    #添加边          for y in range(0, len(matrix)):               if matrix[x][y] == '1':                    G.add_edge(x, y)     #绘制网络图G,带标签,           用指定颜色给结点上色     nx.draw(G, with_labels=True, node_color=colors)       plt.show()                       #输出方式: 在窗口中显示这幅图像finally:     file_read.close()

这里写图片描述

心得:
通过该例学会了python中以下知识点
1、二维数组创建
2、遍历二维数组
3、文件按行读取
4、使用split对字符串进行分割
5、将字符转为数字

巩固以下python中知识点
1、图的创建
2、添加结点、边
3、使图中结点显示标号,并按特定颜色显示

1 0
原创粉丝点击