python将邻接矩阵输出成图的实现

yipeiwu_com5年前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()

将图转化为邻接矩阵,再将邻接矩阵转化为图,还有图的集合表示,邻接矩阵表示,图形表示,这三种表现形式互相转化的问题是一个值得学习的地方,继续加油!

以上这篇python将邻接矩阵输出成图的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python(Django)项目与Apache的管理交互的方法

Python(Django)项目与Apache的管理交互的方法

准备:Django的环境(Python)、Apache、Wsgi(必须文件) 首先需要电脑有Python基础下并且安装好Django的环境,下载Apache文件和Wsgi文件。 Apac...

Python中%是什么意思?python中百分号如何使用?

常见的两种 第一种:数值运算 1 % 3 是指模运算, 取余数(remainder) >>> 7%2 1 # -*- coding: utf-8 -*...

基于PyQt4和PySide实现输入对话框效果

基于PyQt4和PySide实现输入对话框效果

今天做了个基于PyQt4和PySide的输入对话框.已放到PyPi中,包名wlab,大家可以使用pip安装: pip install wlab 在程序输入中,有时会要求同时改变多个参...

python基于celery实现异步任务周期任务定时任务

python基于celery实现异步任务周期任务定时任务

这篇文章主要介绍了python基于celery实现异步任务周期任务定时任务,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 hello,...

Python安装官方whl包和tar.gz包的方法(推荐)

Windows环境:   安装whl包:pip install wheel    ->    pip install&n...