Python 使用 NetworkX

这篇具有很好参考价值的文章主要介绍了Python 使用 NetworkX。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Python 使用 NetworkX

说明:本篇文章主要讲述 python 使用 networkx 绘制有向图;

1. 介绍&安装

NetworkX 是一个用于创建、操作和研究复杂网络的 Python 库。它提供了丰富的功能,可以帮助你创建、分析和可视化各种类型的网络,例如社交网络、Web图、生物网络等。NetworkX 可以用来创建各种类型的网络,包括有向图无向图。它提供了各种方法来添加、删除和修改网络中的节点和边。你可以使用节点和边的属性来进一步描述网络的特性。

NetworkX 还提供了许多图的算法和分析工具。你可以使用这些工具来计算各种网络指标,比如节点的度、网络的直径、最短路径等。你还可以使用它来发现社区结构、进行图的聚类分析等。

除了功能强大的操作和分析工具,NetworkX还提供了多种方式来可视化网络。你可以使用它来绘制网络的节点和边,设置节点的颜色、尺寸和标签等。

总的来说,NetworkX是一个功能丰富、灵活易用的Python库,用于创建、操作和研究各种类型的复杂网络。无论你是在进行学术研究、数据分析还是网络可视化,NetworkX都是一个不错的选择。

安装

pip install networkx

2. 简单的有向图绘制

简单的类展示

import networkx as nx  # 导入 NetworkX 工具包
# 创建 图
G1 = nx.Graph()  # 创建:空的 无向图
G2 = nx.DiGraph()  #创建:空的 有向图
G3 = nx.MultiGraph()  #创建:空的 多图
G4 = nx.MultiDiGraph()  #创建:空的 有向多图

三节点有向图的绘制

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt

# 1. 创建有向图对象, 创建空的有向图的对象
G = nx.DiGraph()

# 2. 添加节点
G.add_node('A')
G.add_node('B')
G.add_node('C')

# 3. 添加有向边
G.add_edge('A', 'B')
G.add_edge('B', 'C')

# 4. 进行图的绘制
pos = nx.spring_layout(G)  # 选择布局算法;
nx.draw(G, pos, with_labels=True)
plt.show()

python networkx,python,php,开发语言

绘制分支节点的有向图

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt

# 1. 创建有向图对象, 创建空的有向图的对象
G = nx.DiGraph()

# 2. 添加节点
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_node('D')
G.add_node('E')

# 3. 添加有向边
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('B', 'D')
G.add_edge('C', 'E')


# 4. 进行图的绘制
pos = nx.spring_layout(G)  # 选择布局算法;
nx.draw(G, pos, with_labels=True)
plt.show()

python networkx,python,php,开发语言

3.有向图的遍历

三节点有向图的遍历

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt

# 1. 创建有向图对象, 创建空的有向图的对象
G = nx.DiGraph()

# 2. 添加节点
G.add_node('A')
G.add_node('B')
G.add_node('C')
# G.add_node('D')
# G.add_node('E')

# 3. 添加有向边
G.add_edge('A', 'B')
G.add_edge('B', 'C')
# G.add_edge('B', 'D')
# G.add_edge('C', 'E')

# 4. 进行图的绘制
pos = nx.spring_layout(G)  # 选择布局算法;
nx.draw(G, pos, with_labels=True)
plt.show()

# 5. 有向图的遍历
print(G.nodes)  # 节点列表, 输出节点 列表
for node in G.nodes():
    print("节点>>>", node)

python networkx,python,php,开发语言

绘制分支节点图形的输出

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt

# 1. 创建有向图对象, 创建空的有向图的对象
G = nx.DiGraph()

# 2. 添加节点
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_node('D')
G.add_node('E')

# 3. 添加有向边
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('B', 'D')
G.add_edge('C', 'E')

# 4. 进行图的绘制
pos = nx.spring_layout(G)  # 选择布局算法;
nx.draw(G, pos, with_labels=True)
plt.show()

# 5. 有向图的遍历
print(G.nodes)  # 节点列表
# print(G.edges)  # 边列表, [('A', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'E')]
for node in G.nodes():
    print("节点>>>", node)
    in_degree = G.in_degree(node)
    print("入度:", in_degree)
    # 获取节点的出度
    out_degree = G.out_degree(node)
    print("出度:", out_degree)
    # 获取节点的邻居节点
    neighbors = G.neighbors(node)
    print("邻居节点:", list(neighbors))

python networkx,python,php,开发语言

4.带权重的边

本章节的内容主要展示带权重的边的绘制,并且求取出最大值和最小值;

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt

# 创建有向图
G = nx.DiGraph()
# 直接创建边, 自动添加两个节点, 并且设置边的权重
G.add_edge('A', 'B', weight=3)
G.add_edge('B', 'C', weight=5)
G.add_edge('C', 'D', weight=2)
G.add_edge('C', 'E', weight=5)

pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
# 获取边的权重
labels = nx.get_edge_attributes(G, 'weight')
# 绘制带有权重的边
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.show()
# 获取边的权重值列表
weights = nx.get_edge_attributes(G, 'weight').values()
print("边的权重值列表>>>", weights)
max_weight = max(weights)
min_weight = min(weights)

print("最大权重的边:", max_weight)
print("最小权重的边:", min_weight)

python networkx,python,php,开发语言

求取图形中得最短路径

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt


def get_shortest_path(graph, source, target):
    try:
        shortest_path = nx.shortest_path(graph, source, target)
        return shortest_path
    except nx.exception.NetworkXNoPath:
        return "不存在最短路径"


def get_longest_path(graph, source, target):
    all_paths = nx.all_simple_paths(graph, source, target)
    longest_path = max(all_paths, key=len)
    return longest_path


# 创建有向图
G = nx.DiGraph()
G.add_edge('A', 'B')
G.add_edge('A', 'C')
G.add_edge('B', 'C')
G.add_edge('B', 'D')
G.add_edge('C', 'D')
pos = nx.spring_layout(G)  # 选择布局算法;
nx.draw(G, pos, with_labels=True)
plt.show()
# 求取最短路径
shortest_path = get_shortest_path(G, 'A', 'D')
print("最短路径:", shortest_path)

# 求取最长路径
longest_path = get_longest_path(G, 'A', 'D')
print("最长路径:", longest_path)

python networkx,python,php,开发语言

按照权重求最短路径&最长路径

# -*- coding: utf-8 -*-
import networkx as nx
import matplotlib.pyplot as plt

# 创建有向带权重图
G = nx.DiGraph()
G.add_edge('A', 'B', weight=3)
G.add_edge('A', 'C', weight=5)
G.add_edge('B', 'C', weight=2)
G.add_edge('B', 'D', weight=4)
G.add_edge('C', 'D', weight=1)
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
# 获取边的权重
labels = nx.get_edge_attributes(G, 'weight')
# 绘制带有权重的边
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.show()

# 按照权重求取最短路径
shortest_path = nx.dijkstra_path(G, 'A', 'D', weight='weight')
shortest_distance = nx.dijkstra_path_length(G, 'A', 'D', weight='weight')

print("最短路径:", shortest_path)
print("最短距离:", shortest_distance)

python networkx,python,php,开发语言

import networkx as nx

# 创建有向带权重图
G = nx.DiGraph()
G.add_edge('A', 'B', weight=3)
G.add_edge('A', 'C', weight=5)
G.add_edge('B', 'C', weight=2)
G.add_edge('B', 'D', weight=4)
G.add_edge('C', 'D', weight=1)

# 将边的权重取相反数
G_neg = nx.DiGraph()
for u, v, data in G.edges(data=True):
    G_neg.add_edge(u, v, weight=-data['weight'])

# 按照权重取相反数的图中求取最短路径
longest_path = nx.dijkstra_path(G_neg, 'A', 'D', weight='weight')
longest_distance = -nx.dijkstra_path_length(G_neg, 'A', 'D', weight='weight')

print("最长路径:", longest_path)
print("最长距离:", longest_distance)

5.json 数据的转换

**说明:**前后端交互的时候通常传回的时候的 json 格式化后的数据,通常需要构建一下,因此最好创建一个统一的类进行封装。

# -*- coding: utf-8 -*-
"""图的封装;
"""
import networkx as nx
import matplotlib.pyplot as plt


class GraphDict(object):
    """有向图的构造;
    """

    def __init__(self):
        """初始化的封装;
        """
        self.graph = None  # 有向图的构建
        self.graph_weight = None  # 有向图带权重

    def dict_to_graph(self, data: list):
        """
        图的字典模式;
        :param data:
        :return:

        example:
            data=[{
              source: 'Node 1',
              target: 'Node 3'
            },
            {
              source: 'Node 2',
              target: 'Node 3'
            },
            {
              source: 'Node 2',
              target: 'Node 4'
            },
            {
              source: 'Node 1',
              target: 'Node 4'
            }]
        """
        graph = nx.DiGraph()  # 创建有向图
        # 循环添加边, 直接添加上节点
        for item in data:
            graph.add_edge(item.get('source'), item.get("target"))
        # 赋值并返回
        self.graph = graph
        return graph

    def dict_to_graph_weight(self, data: list):
        """
        图的字典模式, 带权重;
        :param data:
        :return:

        example:
            data = [
                {
                  source: 'Node 1',
                  target: 'Node 3',
                  weight: 5
                },
                {
                  source: 'Node 2',
                  target: 'Node 3',
                  weight: 3,
                },
                {
                  source: 'Node 2',
                  target: 'Node 4',
                  weight: 5,
                },
                {
                  source: 'Node 1',
                  target: 'Node 4',
                  weight: 5
                }
            ]
        """
        graph = nx.DiGraph()  # 创建有向图
        # 循环添加边, 直接添加上节点, 并且为边赋值上权重;
        for item in data:
            graph.add_edge(item.get('source'), item.get("target"), weight=item.get("weight"))
        # 赋值并返回
        self.graph_weight = graph
        return graph

    def graph_to_dict(self):
        """
        图的数据转换成为字典的数据;
        :return:
        """
        assert self.graph is not None or self.graph_weight is not None, "必须首先通过该类创建一个有向图"
        if self.graph is None:
            edges = self.graph_weight.edges(data=True)
            return [{"source": s, "target": t, "weight": w['weight']} for s, t, w in edges]
        else:
            edges = self.graph.edges()
            return [{"source": s, "target": t} for s, t in edges]

    def show(self):
        """
        有向图的显示;
        :return:
        """
        assert self.graph is not None or self.graph_weight is not None, "必须首先通过该类创建一个有向图"
        if self.graph is None:
            pos = nx.spring_layout(self.graph_weight)
            nx.draw(self.graph_weight, pos, with_labels=True)
            labels = nx.get_edge_attributes(self.graph_weight, 'weight')
            nx.draw_networkx_edge_labels(self.graph_weight, pos, edge_labels=labels)
            plt.show()
        else:
            pos = nx.spring_layout(self.graph)
            nx.draw(self.graph, pos, with_labels=True)
            plt.show()

    def to_png(self, name: str):
        """
        导出有向图的 png 图片;
        :param name; str, 想要导出 png 图片的名称;
        :return:
        """
        assert self.graph is not None or self.graph_weight is not None, "必须首先通过该类创建一个有向图"
        if self.graph is None:
            pos = nx.spring_layout(self.graph_weight)
            nx.draw(self.graph_weight, pos, with_labels=True)
            labels = nx.get_edge_attributes(self.graph_weight, 'weight')
            nx.draw_networkx_edge_labels(self.graph_weight, pos, edge_labels=labels)
            plt.savefig(name)
        else:
            pos = nx.spring_layout(self.graph)
            nx.draw(self.graph, pos, with_labels=True)
            plt.savefig(name)


if __name__ == '__main__':
    graph = GraphDict()
    data = [
        {
            "source": 'Node 1',
            "target": 'Node 3'
        },
        {
            "source": 'Node 2',
            "target": 'Node 3'
        },
        {
            "source": 'Node 2',
            "target": 'Node 4'
        },
        {
            "source": 'Node 1',
            "target": 'Node 4'
        }]
    data_weight = [
        {
            "source": 'Node 1',
            "target": 'Node 3',
            "weight": 3
        },
        {
            "source": 'Node 2',
            "target": 'Node 3',
            "weight": 3
        },
        {
            "source": 'Node 2',
            "target": 'Node 4',
            "weight": 3
        },
        {
            "source": 'Node 1',
            "target": 'Node 4',
            "weight": 3
        }]
    # graph.dict_to_graph(data)
    # graph.to_png("有向图的导出")
    graph.dict_to_graph_weight(data_weight)
    graph.to_png("权重")
    v = graph.graph_to_dict()
    print(v)

python networkx,python,php,开发语言

继续努力,终成大器;文章来源地址https://www.toymoban.com/news/detail-723704.html

到了这里,关于Python 使用 NetworkX的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • IIS perl python cbrother php脚本语言配置及简单测试样例程序

    上篇笔记写了 IIS 配置 CGI, IIS CGI配置和CGI程序FreeBasic, VB6, VC 简单样例_Mongnewer的博客-CSDN博客 这篇在IIS上配置一些脚本语言。为了操作方便,每种语言在站点下分设文件夹。 1. IIS perl配置 Perl CGI方式是曾经流行的做法。先下载一个开源的 Perl.exe 解释器,在免费的 sambar 服务器

    2024年02月09日
    浏览(34)
  • 全面对比 Python、Go、VB、PHP、C/C++、C#、.Net、Java、… 等多编程语言区别

    1. 语言类型: 首先,C/C++、Java 、Python都是 强类型 的语言。强类型语言的定义如下: 强类型语言是一种强制类型定义的语言,即一旦某一个变量被定义类型,如果不经强制转换,那么它永远就是该数据类型。而弱类型语言是一种弱类型定义的语言,某一个变量被定义类型,

    2024年02月02日
    浏览(46)
  • 数据分析课程设计(数学建模+数据分析+数据可视化)——利用Python开发语言实现以及常见数据分析库的使用

    目录 数据分析报告——基于贫困生餐厅消费信息的分类与预测 一、数据分析背景以及目标 二、分析方法与过程 数据探索性与预处理 合并文件并检查缺失值 2.计算文件的当中的值 消费指数的描述性分析 首先对数据进行标准化处理 聚类模型的评价 聚类模型的结果关联 利用决

    2024年02月12日
    浏览(43)
  • 性能对比 Go、Python、PHP、C/C++、C# .Net、Java、Node.js、… 等多编程语言

    1. 有人说 Python 性能没那么 Low? 这个我用 pypy 2.7 确认了下,确实没那么差, 如果用 NumPy 或其他版本 Python 的话,性能更快。但 pypy 还不完善,pypy3 在 beta,  所以一般情况,我是说一般情况下,这点比较让人不爽。   2. 有人说怎么没有 C#、Rust、Ruby 这个那个的? 我只想说语

    2024年03月09日
    浏览(66)
  • 全面对比 Python、Go、VB、PHP、C/C++、C#、.Net、Java、… 等多种编程语言的区别

    1. 语言类型: 首先,C/C++、Java 、Python都是 强类型 的语言。强类型语言的定义如下: 强类型语言是一种强制类型定义的语言,即一旦某一个变量被定义类型,如果不经强制转换,那么它永远就是该数据类型。而弱类型语言是一种弱类型定义的语言,某一个变量被定义类型,

    2024年02月03日
    浏览(46)
  • 【开发语言】C语言与Python的互操作详解

    博主未授权任何人或组织机构转载博主任何原创文章,感谢各位对原创的支持! 博主链接 本人就职于国际知名终端厂商,负责modem芯片研发。 在5G早期负责终端数据业务层、核心网相关的开发工作,目前牵头6G算力网络技术标准研究。 博客内容主要围绕:        5G/6G协议

    2024年02月10日
    浏览(38)
  • 入门Python编程:了解计算机语言、Python介绍和开发环境搭建

    计算机语言是用来控制计算机行为的一种语言,通过它可以告诉计算机该做什么。计算机语言和人类语言在本质上没有太大区别,只是交流的对象不同。 计算机语言发展经历了三个阶段: 1. 机器语言 机器语言使用二进制编码来编写程序。 执行效率高,但编写起来麻烦。 2

    2024年02月09日
    浏览(44)
  • 自动化理论基础(2)—开发语言之Python

    一、知识汇总 掌握 Python 编程语言需要具备一定的基础知识和技能,特别是对于从事自动化测试等领域的工程师。以下是掌握 Python 的一些关键方面: 基本语法: 理解 Python 的基本语法,包括变量、数据类型、运算符、条件语句、循环语句等。 数据结构: 熟悉并能够使用

    2024年01月18日
    浏览(50)
  • [开发语言][c++][python]:C++与Python中的赋值、浅拷贝与深拷贝

    写在前面 :Python和C++中的赋值与深浅拷贝,由于其各自语言特性的问题,在概念和实现上稍微有点差异,本文将这C++和Python中的拷贝与赋值放到一起,希望通过对比学习两语言实现上的异同点,加深对概念的理解。 C++中所谓的 浅拷贝 就是由(系统默认的) 拷贝构造函数对

    2024年02月02日
    浏览(39)
  • 如何查询chatgpt-API-KEY接口的使用额度,代码php和python源码

    ChatGPT是一款由OpenAI开发的强大自然语言处理模型,可以帮助开发者实现各种自然语言相关的应用场景。为了能够使用ChatGPT,开发者需要通过OpenAI获取API-KEY,然后才能使用模型接口进行开发。 但是,在使用ChatGPT的过程中,开发者需要时刻关注API-KEY的使用情况,以确保不会因

    2024年02月12日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包