python将邻接矩阵输出成图
利用networkx,numpy,matplotlib,将邻接矩阵输出为图形。
1,自身确定一个邻接矩阵,然后通过循环的方式添加变,然后输出图像
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
G = nx.Graph()
Matrix = np.array(
[
[0, 1, 1, 1, 1, 1, 0, 0], # a
[0, 0, 1, 0, 1, 0, 0, 0], # b
[0, 0, 0, 1, 0, 0, 0, 0], # c
[0, 0, 0, 0, 1, 0, 0, 0], # d
[0, 0, 0, 0, 0, 1, 0, 0], # e
[0, 0, 1, 0, 0, 0, 1, 1], # f
[0, 0, 0, 0, 0, 1, 0, 1], # g
[0, 0, 0, 0, 0, 1, 1, 0] # h
]
)
for i in range(len(Matrix)):
for j in range(len(Matrix)):
G.add_edge(i, j)
nx.draw(G)
plt.show()
2,有向图
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3, 4, 5, 6])
G.add_cycle([1, 2, 3, 4])
G.add_edge(1, 3)
G.add_edges_from([(3, 5), (3, 6), (6, 7)])
nx.draw(G)
# plt.savefig("youxiangtu.png")
plt.show()
3, 5节点完全图
G = nx.complete_graph(5)
nx.draw(G)
plt.savefig("8nodes.png")
plt.show()
4,无向图
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3, 4, 5, 6])
G.add_cycle([1, 2, 3, 4])
G.add_edge(1, 3)
G.add_edges_from([(3, 5), (3, 6), (6, 7)])
nx.draw(G)
# plt.savefig("wuxiangtu.png")
plt.show()
5,颜色节点图
G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (4, 5), (4, 6), (5, 6)])
pos = nx.spring_layout(G)
colors = [1, 2, 3, 4, 5, 6]
nx.draw_networkx_nodes(G, pos, node_color=colors)
nx.draw_networkx_edges(G, pos)
plt.axis('off')
# plt.savefig("color_nodes.png")
plt.show()
将图转化为邻接矩阵,再将邻接矩阵转化为图,还有图的集合表示,邻接矩阵表示,图形表示,这三种表现形式互相转化的问题是一个值得学习的地方,继续加油!