当前位置: 首页 > news >正文

【python视图3】networkx图操作示例

一、说明

        根据定义,图是节点(顶点)以及已识别的节点对(称为边、链接等)的集合。在 NetworkX 中,节点可以是任何可哈希对象,例如文本字符串、图像、XML 对象、另一个图形、自定义节点对象等。

        如果不知道networkx基础的制图,请先看看下文:

【python视图1】networkx操作Graph图

【python视图2】基于networkx的10个绘图技巧 

二、神奇制图

2.1 绘制彩虹图

        生成一个完整的图形,其中包含 13 个节点,呈圆形布局,边按节点距离着色。节点距离由沿圆上任意两个节点之间的弧线遍历的最小节点数给出。

        这样的图是 Ringel 猜想的主题,它指出:任何具有 2n + 1 个节点的完整图都可以被任何具有 n + 1 个节点的树平铺(即树的副本可以放置在完整图上,使得图中的每条边完整的图被恰好覆盖一次)。边缘着色有助于确定如何放置树副本。

  • 效果图: 

  • 代码:

import matplotlib.pyplot as plt
import networkx as nx# A rainbow color mapping using matplotlib's tableau colors
node_dist_to_color = {1: "tab:red",2: "tab:orange",3: "tab:olive",4: "tab:green",5: "tab:blue",6: "tab:purple",
}# Create a complete graph with an odd number of nodes
nnodes = 13
G = nx.complete_graph(nnodes)# A graph with (2n + 1) nodes requires n colors for the edges
n = (nnodes - 1) // 2
ndist_iter = list(range(1, n + 1))# Take advantage of circular symmetry in determining node distances
ndist_iter += ndist_iter[::-1]def cycle(nlist, n):return nlist[-n:] + nlist[:-n]# Rotate nodes around the circle and assign colors for each edge based on
# node distance
nodes = list(G.nodes())
for i, nd in enumerate(ndist_iter):for u, v in zip(nodes, cycle(nodes, i + 1)):G[u][v]["color"] = node_dist_to_color[nd]pos = nx.circular_layout(G)
# Create a figure with 1:1 aspect ratio to preserve the circle.
fig, ax = plt.subplots(figsize=(8, 8))
node_opts = {"node_size": 500, "node_color": "w", "edgecolors": "k", "linewidths": 2.0}
nx.draw_networkx_nodes(G, pos, **node_opts)
nx.draw_networkx_labels(G, pos, font_size=14)
# Extract color from edge data
edge_colors = [edgedata["color"] for _, _, edgedata in G.edges(data=True)]
nx.draw_networkx_edges(G, pos, width=2.0, edge_color=edge_colors)ax.set_axis_off()
fig.tight_layout()
plt.show()

 2.2  随机地理图

代码: 

import matplotlib.pyplot as plt
import networkx as nx# Use seed when creating the graph for reproducibility
G = nx.random_geometric_graph(200, 0.125, seed=896803)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, "pos")# find node near center (0.5,0.5)
dmin = 1
ncenter = 0
for n in pos:x, y = pos[n]d = (x - 0.5) ** 2 + (y - 0.5) ** 2if d < dmin:ncenter = ndmin = d# color by path length from node near center
p = dict(nx.single_source_shortest_path_length(G, ncenter))plt.figure(figsize=(8, 8))
nx.draw_networkx_edges(G, pos, alpha=0.4)
nx.draw_networkx_nodes(G,pos,nodelist=list(p.keys()),node_size=80,node_color=list(p.values()),cmap=plt.cm.Reds_r,
)plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis("off")
plt.show()

2.3  旅行商问题

        这是旅行商问题的绘图解决方案示例

        该函数用于生成解决方案 christofides,其中给定一组节点,它计算旅行者必须遵循的节点路线,以最小化总成本。

代码示例 

import matplotlib.pyplot as plt
import networkx as nx
import networkx.algorithms.approximation as nx_app
import mathG = nx.random_geometric_graph(20, radius=0.4, seed=3)
pos = nx.get_node_attributes(G, "pos")# Depot should be at (0,0)
pos[0] = (0.5, 0.5)H = G.copy()# Calculating the distances between the nodes as edge's weight.
for i in range(len(pos)):for j in range(i + 1, len(pos)):dist = math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1])dist = distG.add_edge(i, j, weight=dist)cycle = nx_app.christofides(G, weight="weight")
edge_list = list(nx.utils.pairwise(cycle))# Draw closest edges on each node only
nx.draw_networkx_edges(H, pos, edge_color="blue", width=0.5)# Draw the route
nx.draw_networkx(G,pos,with_labels=True,edgelist=edge_list,edge_color="red",node_size=200,width=3,
)print("The route of the traveller is:", cycle)
plt.show()

 2.4  权重的灵活绘制

  • 图形示例: 

  • 代码示例: 
import matplotlib.pyplot as plt
import networkx as nxG = nx.Graph()G.add_edge("a", "b", weight=0.6)
G.add_edge("a", "c", weight=0.2)
G.add_edge("c", "d", weight=0.1)
G.add_edge("c", "e", weight=0.7)
G.add_edge("c", "f", weight=0.9)
G.add_edge("a", "d", weight=0.3)elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]pos = nx.spring_layout(G, seed=7)  # positions for all nodes - seed for reproducibility# nodes
nx.draw_networkx_nodes(G, pos, node_size=700)# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6)
nx.draw_networkx_edges(G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color="b", style="dashed"
)# node labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")
# edge weight labels
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels)ax = plt.gca()
ax.margins(0.08)
plt.axis("off")
plt.tight_layout()
plt.show()

2.5 barabasi_albert模型1

import networkx as nx  # 导入networkx包
import matplotlib.pyplot as pltG = nx.random_graphs.barabasi_albert_graph(100, 2)  # 生成一个BA无标度网络G
nx.draw(G)  # 绘制网络G
plt.savefig("ba.png")  # 输出方式1: 将图像存为一个png格式的图片文件
plt.show()  # 输出方式2: 在窗口中显示这幅图像

 2.6 barabasi_albert模型2

import networkx as nx  # 导入networkx包
import matplotlib.pyplot as pltG=nx.Graph()
for u, v in nx.barabasi_albert_graph(10,2,seed=1).edges():G.add_edge(u,v,weight=random.uniform(0,0.4))pos=nx.spring_layout(G,iterations=20)
edgewidth=[]
for (u,v,d) in G.edges(data=True):nodeTmp = list( G.get_edge_data(u,v).values())edgewidth.append(round(nodeTmp[0]*20,2))
nx.draw_networkx_edges(G,pos,width=edgewidth)
nx.draw_networkx_nodes(G,pos)
plt.show()

 图例显示

#!-*- coding:utf8-*-import networkx as nx
import matplotlib.pyplot as plt
import randomG=nx.Graph()
for u, v in nx.barabasi_albert_graph(10,2,seed=1).edges():G.add_edge(u,v,weight=random.uniform(0,0.4))
pos=nx.spring_layout(G,iterations=20)#以下语句绘制以带宽为线的宽度的图
nx.draw_networkx_edges(G,pos,width=[float(d['weight']*10) for (u,v,d) in G.edges(data=True)])
nx.draw_networkx_nodes(G,pos)
plt.show()

2.7 igraph操作

  • 结果图:

代码示例: 

import matplotlib.pyplot as plt
import networkx as nx
import igraph as ig
G = nx.dense_gnm_random_graph(30, 40, seed=42)# largest connected component
components = nx.connected_components(G)
largest_component = max(components, key=len)
H = G.subgraph(largest_component)# convert to igraph
h = ig.Graph.from_networkx(H)# Plot the same network with NetworkX and igraph
fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))# NetworkX draw
ax0.set_title("Plot with NetworkX draw")
nx.draw_kamada_kawai(H, node_size=50, ax=ax0)# igraph draw
ax1.set_title("Plot with igraph plot")
layout = h.layout_kamada_kawai()
ig.plot(h, layout=layout, target=ax1)
plt.axis("off")
plt.show()

Graph | NetworkX 入门教程 - 知乎 (zhihu.com)

相关文章:

【python视图3】networkx图操作示例

一、说明 根据定义&#xff0c;图是节点&#xff08;顶点&#xff09;以及已识别的节点对&#xff08;称为边、链接等&#xff09;的集合。在 NetworkX 中&#xff0c;节点可以是任何可哈希对象&#xff0c;例如文本字符串、图像、XML 对象、另一个图形、自定义节点对象等。 如…...

网络地址转换应用

如图所示,企业使用一台AR 路由器作为出口设备,路由器配置NAT Outbound为私网用户提供访问Internet服务,同时配置NAT Server将私网WEB服务器发布到公网上,对外网用户提供服务。运营商仅为该单位分配了一个公网IP,此地址既作为AR出接口的IP地址,也作为NAT Outbound和NAT Se…...

强化学习-Double DQN、竞争网络结构和Rainbow(第4章)

来源书籍&#xff1a; TENSORFLOW REINFORCEMENT LEARNING QUICK START GUIDE 《TensorFlow强化学习快速入门指南-使用Python动手搭建自学习的智能体》 著者&#xff1a;[美]考希克巴拉克里希南&#xff08;Kaushik Balakrishnan&#xff09; 译者&#xff1a;赵卫东 出版…...

Unity 性能优化锦集

Unity作为一款主流的游戏开发引擎&#xff0c;不仅提供了强大的编辑器和开发工具&#xff0c;还可以让开发者轻松地实现高质量的3D游戏。但是&#xff0c;随着游戏规模的不断扩大和玩家需求的增加&#xff0c;游戏的性能问题也变得越来越重要。因此&#xff0c;在使用Unity进行…...

JS之Map的基本使用

一、Map的基本API 创建&#xff1a; const map new Map()插入&#xff1a;map.set("name", "郑建")读取&#xff1a;map.get("name")判断&#xff1a;map.has("name")删除&#xff1a;map.delete大小&#xff1a;map.size遍历&#…...

音视频八股文(6)-- ffmpeg大体介绍和内存模型

播放器框架 常用音视频术语 • 容器&#xff0f;文件&#xff08;Conainer/File&#xff09;&#xff1a;即特定格式的多媒体文件&#xff0c; 比如mp4、flv、mkv等。 • 媒体流&#xff08;Stream&#xff09;&#xff1a;表示时间轴上的一段连续数据&#xff0c;如一 段声音…...

4.25~~~~~

接着之前PE文件结构的预习 DOS 定位到NT 怎么操作的&#xff1f; 用的是e_lfanew&#xff0c;然后是相对于文件头的偏移量&#xff08;也就是raw表示方法&#xff09; 现在有个问题&#xff0c;为什么e_lfanew 这个变量不直接存储PE头 的绝对地址呢&#xff1f; 比如说&…...

Android 9.0 系统设置显示主菜单添加屏幕旋转菜单实现旋转屏幕功能

1.前言 在android9.0的系统rom定制化开发中,在对系统设置进行定制开发中,有产品需求要求增加旋转屏幕功能的菜单,就是在点击旋转屏幕菜单后弹窗显示旋转0度,旋转 90度,旋转180度,旋转270度针对不同分辨率的无重力感应的大屏设备的屏幕旋转功能的实现,接下来就来分析实现…...

Python数据结构与算法-欧几里算法(p95)

一、欧几里算法原理 欧几里得公式 欧几里得算法&#xff1a;gcd(a,b) gcd(b, a mod b) &#xff1b; mod是指模&#xff0c;即a/b取余数。 运算示例&#xff1a; gcd&#xff08;60,21&#xff09; gcd(21,18) gcd(18,3)gcd(3,0) 证明略 最大公约数-欧几里得求解 &#xff08…...

【故障诊断】用于轴承故障诊断的性能增强时变形态滤波方法及用于轴承断层特征提取的增强数学形态算子研究(Matlab代码实现)

&#x1f4a5; &#x1f4a5; &#x1f49e; &#x1f49e; 欢迎来到本博客 ❤️ ❤️ &#x1f4a5; &#x1f4a5; &#x1f3c6; 博主优势&#xff1a; &#x1f31e; &#x1f31e; &#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 …...

水羊转债,超达转债,晓鸣转债上市价格预测

水羊转债 基本信息 转债名称&#xff1a;水羊转债&#xff0c;评级&#xff1a;A&#xff0c;发行规模&#xff1a;6.94987亿元。 正股名称&#xff1a;水羊股份&#xff0c;今日收盘价&#xff1a;13.94元&#xff0c;转股价格&#xff1a;13.71元。 当前转股价值 转债面值 /…...

从数据管理到数据资产管理

数据已经与土地、劳动力、资本、技术并称为五种生产要素&#xff0c;数据的价值是毋庸置疑的。数据甚至成为了国家的基础性战略资源&#xff0c;数字经济也正在成为经济增长的强大创新动力。那么—— 数据到底指的是什么&#xff1f; 数据管理又是怎么回事&#xff1f; 数据如何…...

RabbitMQ【#1】是什么,有什么用

RabbiMQ是什么&#xff1f; RabbitMQ是一种开源的消息队列软件&#xff0c;它实现了高级消息队列协议&#xff08;AMQP&#xff09;并支持多种编程语言。它可以用于将消息从一个应用程序传递到另一个应用程序或进程&#xff0c;并支持分布式系统中的异步消息通信。RabbitMQ的主…...

RabbitMQ防止消息丢失

生产者没有成功把消息发送到MQ 丢失的原因 &#xff1a;因为网络传输的不稳定性&#xff0c;当生产者在向MQ发送消息的过程中&#xff0c;MQ没有成功接收到消息&#xff0c;但是生产者却以为MQ成功接收到了消息&#xff0c;不会再次重复发送该消息&#xff0c;从而导致消息的丢…...

ImageJ用户手册——第二部分(ImageJ操作)

ImageJ用户手册-第二部分 ImageJ的使用4. 使用键盘快捷键5. 查找命令6. 撤消和重做7. 图像类型和格式原生格式非原生格式 8. 堆栈、虚拟堆栈、超堆栈Stacks&#xff08;堆栈&#xff09;Virtual Stacks&#xff08;虚拟堆栈&#xff09;Hyperstacks&#xff08;超堆栈&#xff…...

Java中Lambda表达式(面向初学者)

目录 一、Lambda表达式是什么&#xff1f;什么场景下使用Lambda&#xff1f; 1.Lambda 表达式是什么 2.函数式接口是什么 第二章、怎么用Lambda 1.必须有一个函数式接口 2.省略规则 3.Lambda经常用来和匿名内部类比较 第三章、具体使用场景举例&#xff08;&#xff09; …...

2023年淮阴工学院五年一贯制专转本数字电子技术考试大纲

2023年淮阴工学院五年一贯制专转本数字电子技术考试大纲 一、考核对象 本课程的考核对象是五年一贯制高职专转本电子科学与技术专业普通在校生考生。 二、考试目的及总体要求 通过本课程的考试&#xff0c;检查学生对掌握数字电路的基础理论知识的掌握程度&#xff0c;是否…...

使用 GO 编写 Web 应用:学习如何使用 GO 语言编写 Web 应用,包括使用 HTTP 路由、模板引擎等。

GO 语言是一个高效、可靠和简洁的编程语言,越来越多的开发者开始选择 GO 语言来编写 Web 应用。本文将介绍如何使用 GO 语言编写 Web 应用,并且将重点关注使用 HTTP 路由和模板引擎。 使用 HTTP 路由 HTTP 路由是 Web 应用中非常重要的一个概念。它可以帮助我们将请求路由到…...

Leetcode-day4【88】【167】【125】【345】

文章目录 88. 合并两个有序数组题目解题思路解题思路【学习】尾插入法 167. 两数之和 II - 输入有序数组题目解题思路 125. 验证回文串题目解题思路 345. 反转字符串中的元音字母题目解题思路 88. 合并两个有序数组 题目 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums…...

【IoT】如何使用软件加密(文件夹加密工具.exe),并破解工具

目录 第一步&#xff1a;显示隐藏的文件。 第二步&#xff1a;将隐藏文件变成文件夹。 第三步&#xff1a;解密文件。 有时候出差或者有些商务场合&#xff0c;需要对一些敏感文件做一下简单的加密&#xff0c;这样在分享内容的时候&#xff0c;可以起到初步的保护作用。 当…...

浅谈 React Hooks

React Hooks 是 React 16.8 引入的一组 API&#xff0c;用于在函数组件中使用 state 和其他 React 特性&#xff08;例如生命周期方法、context 等&#xff09;。Hooks 通过简洁的函数接口&#xff0c;解决了状态与 UI 的高度解耦&#xff0c;通过函数式编程范式实现更灵活 Rea…...

idea大量爆红问题解决

问题描述 在学习和工作中&#xff0c;idea是程序员不可缺少的一个工具&#xff0c;但是突然在有些时候就会出现大量爆红的问题&#xff0c;发现无法跳转&#xff0c;无论是关机重启或者是替换root都无法解决 就是如上所展示的问题&#xff0c;但是程序依然可以启动。 问题解决…...

React第五十七节 Router中RouterProvider使用详解及注意事项

前言 在 React Router v6.4 中&#xff0c;RouterProvider 是一个核心组件&#xff0c;用于提供基于数据路由&#xff08;data routers&#xff09;的新型路由方案。 它替代了传统的 <BrowserRouter>&#xff0c;支持更强大的数据加载和操作功能&#xff08;如 loader 和…...

JavaScript 中的 ES|QL:利用 Apache Arrow 工具

作者&#xff1a;来自 Elastic Jeffrey Rengifo 学习如何将 ES|QL 与 JavaScript 的 Apache Arrow 客户端工具一起使用。 想获得 Elastic 认证吗&#xff1f;了解下一期 Elasticsearch Engineer 培训的时间吧&#xff01; Elasticsearch 拥有众多新功能&#xff0c;助你为自己…...

3.3.1_1 检错编码(奇偶校验码)

从这节课开始&#xff0c;我们会探讨数据链路层的差错控制功能&#xff0c;差错控制功能的主要目标是要发现并且解决一个帧内部的位错误&#xff0c;我们需要使用特殊的编码技术去发现帧内部的位错误&#xff0c;当我们发现位错误之后&#xff0c;通常来说有两种解决方案。第一…...

Springboot社区养老保险系统小程序

一、前言 随着我国经济迅速发展&#xff0c;人们对手机的需求越来越大&#xff0c;各种手机软件也都在被广泛应用&#xff0c;但是对于手机进行数据信息管理&#xff0c;对于手机的各种软件也是备受用户的喜爱&#xff0c;社区养老保险系统小程序被用户普遍使用&#xff0c;为方…...

通过MicroSip配置自己的freeswitch服务器进行调试记录

之前用docker安装的freeswitch的&#xff0c;启动是正常的&#xff0c; 但用下面的Microsip连接不上 主要原因有可能一下几个 1、通过下面命令可以看 [rootlocalhost default]# docker exec -it freeswitch fs_cli -x "sofia status profile internal"Name …...

Linux部署私有文件管理系统MinIO

最近需要用到一个文件管理服务&#xff0c;但是又不想花钱&#xff0c;所以就想着自己搭建一个&#xff0c;刚好我们用的一个开源框架已经集成了MinIO&#xff0c;所以就选了这个 我这边对文件服务性能要求不是太高&#xff0c;单机版就可以 安装非常简单&#xff0c;几个命令就…...

rknn toolkit2搭建和推理

安装Miniconda Miniconda - Anaconda Miniconda 选择一个 新的 版本 &#xff0c;不用和RKNN的python版本保持一致 使用 ./xxx.sh进行安装 下面配置一下载源 # 清华大学源&#xff08;最常用&#xff09; conda config --add channels https://mirrors.tuna.tsinghua.edu.cn…...

uni-app学习笔记三十五--扩展组件的安装和使用

由于内置组件不能满足日常开发需要&#xff0c;uniapp官方也提供了众多的扩展组件供我们使用。由于不是内置组件&#xff0c;需要安装才能使用。 一、安装扩展插件 安装方法&#xff1a; 1.访问uniapp官方文档组件部分&#xff1a;组件使用的入门教程 | uni-app官网 点击左侧…...