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

news/2024/4/18 16:07:23/文章来源:https://blog.csdn.net/gongdiwudu/article/details/130299770

一、说明

        根据定义,图是节点(顶点)以及已识别的节点对(称为边、链接等)的集合。在 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)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_103812.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

perf生成火焰图

文章目录 1&#xff0c;top发现webserver进程空转情况下CPU占用高达200%2&#xff0c;使用性能分析工具perf来进行分析2.1&#xff0c;抓取采集样本2.2&#xff0c;使用perf简单分析性能数据 3&#xff0c;火焰图3.1&#xff0c;生成火焰图3.2&#xff0c;将生成的.svg文件用浏…

Chapter 4 :Constraining I/O Delay(ug903)

4.1 About Constraining I/O Delay 要在设计中准确地建模外部时序上下文&#xff0c;必须为输入和输出端口提供时序信息。由于XilinxVivado集成设计环境&#xff08;IDE&#xff09;只能识别FPGA边界内的时序&#xff0c;因此必须使用以下命令来指定超出这些边界的延迟…

数据库系统工程师——第五章 网络基础知识

文章目录 &#x1f4c2; 第五章、网络基础知识 &#x1f4c1; 5.1 计算机网络概述 &#x1f4d6; 5.1.1 计算机网络的概念 &#x1f4d6; 5.1.2 计算机网络的分类 &#x1f4d6; 5.1.3 网络的拓扑结构 &#x1f4c1; 5.2 网络硬件基础 &#x1f4d6; 5.2.1 网络设备 &…

【k8s】ruoyi微服务迁移到k8s

书接上回【传统方式部署Ruoyi微服务】&#xff0c;此刻要迁移至k8s。 环境说明 31 master &#xff0c; 32 node1 &#xff0c; 33 node2迁移思路 交付思路: 其实和交付到Linux主机上是一样的&#xff0c;无外乎将这些微服务都做成了Docker镜像; 1、微服务数据层: MySQL、 R…

“井电双控”地下水远程计量设施-实现地下水资源合理利用

“井电双控”地下水远程计量设施&#xff08;MGTR-W4122C&#xff09;是针对取水计量控制系统开发智能终端产品。集预收费、流量监测、电量监测、余额提醒、欠费停机、无线传输、远程控制等多种功能于一体&#xff0c;并可根据项目需求选择实体IC卡和APP电子卡取水两种方式。其…

换肤实现及LayoutInflater原理

文章目录 背景实现换肤步骤解析插件 apk 的包信息获取插件 apk 的 Resources 对象替换资源 简单的插件化换肤实现和存在的问题换肤如何动态刷新&#xff1f;控件换肤刷新的性能考虑如何降低 xml 布局中 View 的替换成本LayoutInflater 原理LayoutInflater.Factory2 替换 View 小…

David Silver Reinforcement Learning -- Markov process

1 Introduction 这个章节介绍关键的理论概念。 马尔科夫过程的作用&#xff1a; 1&#xff09;马尔科夫过程描述强化学习环境的方法&#xff0c;环境是完全能观测的&#xff1b; 2&#xff09;几乎所有的RL问题可以转换成MDP的形式&#xff1b; 2 Markov Processes 2.1 Mark…

从源码全面解析LinkedBlockingQueue的来龙去脉

&#x1f44f;作者简介&#xff1a;大家好&#xff0c;我是爱敲代码的小黄&#xff0c;独角兽企业的Java开发工程师&#xff0c;CSDN博客专家&#xff0c;阿里云专家博主&#x1f4d5;系列专栏&#xff1a;Java设计模式、数据结构和算法、Kafka从入门到成神、Kafka从成神到升仙…

mall-swarm微服务商城系统

mall-swarm是一套微服务商城系统&#xff0c;采用了 Spring Cloud 2021 & Alibaba、Spring Boot 2.7、Oauth2、MyBatis、Docker、Elasticsearch、Kubernetes等核心技术&#xff0c;同时提供了基于Vue的管理后台方便快速搭建系统。mall-swarm在电商业务的基础集成了注册中心…

【Excel统计分析插件】上海道宁为您提供统计分析、数据可视化和建模软件——Analyse-it

Analyse-it是Microsoft Excel中的 统计分析插件 它为Microsoft Excel带来了 易于使用的统计软件 Analyse-it在软件中 引入了一些新的创新统计分析 Analyse-it与 许多Excel加载项开发人员不同 使用完善的软件开发和QA实践 包括单元/集成/系统测试 敏捷开发、代码审查 …

HCIA-RS实验-ENSP搭建一个基础的IP网络

HCIA-RS是华为认证网络工程师&#xff08;Routing & Switching&#xff09;的缩写。通过考取HCIA-RS证书&#xff0c;可以证明自己有能力设计、实现和维护小型网络。而HCIA-RS实验则是考试的一部分&#xff0c;是考生必须要完成的实践环节。这将是第一篇文章&#xff0c;后…

【Android Framework (八) 】- Service

文章目录 知识回顾启动第一个流程initZygote的流程system_serverServiceManagerBinderLauncher的启动AMS 前言源码分析1.startService2.bindService 拓展知识1:Service的两种启动方式对Service生命周期有什么影响&#xff1f;2:Service的启动流程3:Service的onStartCommand返回…

紧密联结玩家 | 2023 Google 游戏开发者峰会

玩家的选择是对游戏莫大的认可&#xff0c;重视玩家反馈并和他们建立联系是您的游戏取得成功的关键。我们也在努力创造更多机会&#xff0c;让您的游戏从琳琅满目的列表中脱颖而出&#xff0c;帮助您吸引更多用户。 上篇内容我们介绍了帮助您优化游戏性能的几大功能更新&#x…

❀五一劳动节来啦❀

今年“五一”&#xff0c;4月29日至5月3日放假调休&#xff0c;共5天。 如果你在5月4日到5月6日请假3天&#xff0c;加上5月7日周日&#xff0c;就可以形成9天的假期。 一&#xff0c;五一劳动节的由来⭐ 国际劳动节又称“五一国际劳动节”“国际示威游行日”&#xff08;英语…

GPT详细安装教程-GPT软件国内也能使用

GPT (Generative Pre-trained Transformer) 是一种基于 Transformer 模型的自然语言处理模型&#xff0c;由 OpenAI 提出&#xff0c;可以应用于各种任务&#xff0c;如对话系统、文本生成、机器翻译等。GPT-3 是目前最大的语言模型之一&#xff0c;其预训练参数超过了 13 亿个…

python+vue 健康体检预约管理系统

该专门体检预约管理系统包括会员和管理员。其主要功能包括个人中心、会员管理、体检服务管理、类型管理、订单信息管理、取消订单管理、 体检报告管理、通知信息管理、交流论坛、系统管理等功能。 目 录 一、绪论 1 1.1研发背景和意义 2 1.2 国内研究动态 3 1.3论文主…

Cookies和Session案例-注册

1. 注册功能改进 1.1 service 将之前的注册案例的代码进行优化&#xff0c;将获取sqlsession工厂对象、获取sqlsession、获取mapper等操作从servlet中分离出来转变为三层架构的形式 在service目录下创建UserService public class UserService {SqlSessionFactory sqlSessionFa…

Docker compose-实现多服务、nginx负载均衡、--scale参数解决端口冲突问题

Docker compose-实现多服务、nginx负载均衡、--scale参数解决端口冲突问题 问题&#xff1a;scale参数端口冲突解决方法&#xff1a;nginx实现多服务、负载均衡修改docker-compose.yml配置新增nginx本地配置文件验证启动容器查看容器状态访问web应用 问题&#xff1a;scale参数…

Linux中的YUM源仓库和NFS文件共享服务(うたかたの夢)

YUM仓库源的介绍和相关信息 简介 yum是一个基于RPM包&#xff08;是Red-Hat Package Manager红帽软件包管理器的缩写&#xff09;构建的软件更新机制&#xff0c;能够自动解决软件包之间的依赖关系。 yum由仓库和客户端组成&#xff0c;也就是整个yum由两部分组成&#xff0…

Python小姿势 - 知识点:

知识点&#xff1a; Python的字符串格式化 标题&#xff1a; Python字符串格式化实例解析 顺便介绍一下我的另一篇专栏&#xff0c; 《100天精通Python - 快速入门到黑科技》专栏&#xff0c;是由 CSDN 内容合伙人丨全站排名 Top 4 的硬核博主 不吃西红柿 倾力打造。 基础知识…