Python根据已知邻接矩阵绘制无向图操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python根据已知邻接矩阵绘制无向图操作。分享给大家供大家参考,具体如下:

有六个点:[0,1,2,3,4,5,6],六个点之间的邻接矩阵如表格所示,根据邻接矩阵绘制出相对应的图



0

1

2

3

4

5

6

0

0

1

0

1

0

1

0

1

1

0

1

1

1

1

1

2

0

1

0

1

0

1

0

3

1

1

1

0

1

1

1

4

0

1

0

1

1

1

1

5

1

1

1

1

1

0

0

6

0

1

0

1

1

0

0


将点之间的联系构造成如下矩阵

N = [[0, 3, 5, 1],
 [1, 5, 4, 3],
   [2, 1, 3, 5],
   [3, 5, 1, 4],
   [4, 5, 1, 3],
   [5, 3, 4, 1],
 [6, 3, 1, 4]]

代码如下

# -*- coding:utf-8 -*-
#! python3
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
point=[0,1,2,3,4,5,6]
G.add_nodes_from(point)
edglist=[]
N = [[0, 3, 5, 1],[1, 5, 4, 3],[2, 1, 3, 5],[3, 5, 1, 4],[4, 5, 1, 3],[5, 3, 4, 1],[6, 3, 1, 4]]
for i in range(7):
  for j in range(1,4):
    edglist.append((N[i][0],N[i][j]))
G=nx.Graph(edglist)
position = nx.circular_layout(G)
nx.draw_networkx_nodes(G,position, nodelist=point, node_color="r")
nx.draw_networkx_edges(G,position)
nx.draw_networkx_labels(G,position)
plt.show()

显示结果:

更多关于Python相关内容可查看本站专题:《Python数学运算技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python 正则表达式实现计算器功能

Python 正则表达式实现计算器功能

需求: 用户输入运算表达式,终端显示计算结果 代码: # !/usr/bin/env/ python3 # -*- coding: utf-8 -*- """用户输入计算表达式,显...

Python 中list ,set,dict的大规模查找效率对比详解

很多时候我们可能要频繁的进行元素的find 或in操作,本人一直天真的以为python的list做了hash,通过红黑树来高效查找···直到今天我真正来测试它和set,dict的查找效率...

Python实现微信好友的数据分析

Python实现微信好友的数据分析

基于微信开放的个人号接口python库itchat,实现对微信好友的获取,并对省份、性别、微信签名做数据分析。 效果: 直接上代码,建三个空文本文件stopwords.txt,ne...

python中的协程深入理解

python中的协程深入理解

先介绍下什么是协程:   协程,又称微线程,纤程,英文名Coroutine。协程的作用,是在执行函数A时,可以随时中断,去执行函数B,然后中断继续执行函数A(可以自由切换)。但这一过程...

python3 打开外部程序及关闭的示例

如下所示: import os import time import subprocess subprocess.Popen(r'cmd') print('打开成功') time...