Networkx中的多层图

2024-04-18

我想创建一个多层图(如附图所示),通过连接用以下代码编写的两个图,使用networkx

#Graph1
g1 = nx.read_edgelist('sample.txt', nodetype=str)
pos = nx.shell_layout(g)
plt.figure(figsize=(10, 10))
nx.draw_networkx_edges(g, pos, edge_color='khaki', alpha=1)
nx.draw_networkx_nodes(g,pos,node_color='r',alpha=0.5,node_size=1000)
nx.draw_networkx_labels(g, pos, font_size=10,font_family='IPAexGothic')
plt.axis('off')

#Graph2
g2 = nx.read_edgelist('sample2.txt', nodetype=str)
pos = nx.shell_layout(g)
plt.figure(figsize=(10, 10))
nx.draw_networkx_edges(g, pos, edge_color='khaki', alpha=1)
nx.draw_networkx_nodes(g,pos,node_color='r',alpha=0.5,node_size=1000)
nx.draw_networkx_labels(g, pos, font_size=10,font_family='IPAexGothic')
plt.axis('off')

里面没有任何功能networkx目前支持分层布局,更不用说如图所示的可视化了。所以我们需要自己推出。

下面的实现LayeredNetworkGraph假设您有一个图表列表[g1, g2, ..., gn]代表不同的层。在层内,相应的(子)图定义连接性。层与层之间,如果后续层的节点具有相同的节点 ID,则将它们连接起来。

由于没有布局函数(AFAIK)可以通过对层内节点施加平面性约束来计算三个维度的节点位置,因此我们使用一个小技巧:我们在所有层上创建一个图形组合,计算二维位置,然后将这些位置应用到所有层中的节点。人们可以计算出具有平面性约束的真正的力定向布局,但这将是一项艰巨的工作,并且由于您的示例仅使用了外壳布局(不会受到影响),所以我没有打扰。在许多情况下,差异很小。

如果您想更改可视化的各个方面(大小、宽度、颜色),请查看draw方法。您可能需要的大多数更改都可以在那里进行。

#!/usr/bin/env python
"""
Plot multi-graphs in 3D.
"""
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Line3DCollection


class LayeredNetworkGraph(object):

    def __init__(self, graphs, node_labels=None, layout=nx.spring_layout, ax=None):
        """Given an ordered list of graphs [g1, g2, ..., gn] that represent
        different layers in a multi-layer network, plot the network in
        3D with the different layers separated along the z-axis.

        Within a layer, the corresponding graph defines the connectivity.
        Between layers, nodes in subsequent layers are connected if
        they have the same node ID.

        Arguments:
        ----------
        graphs : list of networkx.Graph objects
            List of graphs, one for each layer.

        node_labels : dict node ID : str label or None (default None)
            Dictionary mapping nodes to labels.
            If None is provided, nodes are not labelled.

        layout_func : function handle (default networkx.spring_layout)
            Function used to compute the layout.

        ax : mpl_toolkits.mplot3d.Axes3d instance or None (default None)
            The axis to plot to. If None is given, a new figure and a new axis are created.

        """

        # book-keeping
        self.graphs = graphs
        self.total_layers = len(graphs)

        self.node_labels = node_labels
        self.layout = layout

        if ax:
            self.ax = ax
        else:
            fig = plt.figure()
            self.ax = fig.add_subplot(111, projection='3d')

        # create internal representation of nodes and edges
        self.get_nodes()
        self.get_edges_within_layers()
        self.get_edges_between_layers()

        # compute layout and plot
        self.get_node_positions()
        self.draw()


    def get_nodes(self):
        """Construct an internal representation of nodes with the format (node ID, layer)."""
        self.nodes = []
        for z, g in enumerate(self.graphs):
            self.nodes.extend([(node, z) for node in g.nodes()])


    def get_edges_within_layers(self):
        """Remap edges in the individual layers to the internal representations of the node IDs."""
        self.edges_within_layers = []
        for z, g in enumerate(self.graphs):
            self.edges_within_layers.extend([((source, z), (target, z)) for source, target in g.edges()])


    def get_edges_between_layers(self):
        """Determine edges between layers. Nodes in subsequent layers are
        thought to be connected if they have the same ID."""
        self.edges_between_layers = []
        for z1, g in enumerate(self.graphs[:-1]):
            z2 = z1 + 1
            h = self.graphs[z2]
            shared_nodes = set(g.nodes()) & set(h.nodes())
            self.edges_between_layers.extend([((node, z1), (node, z2)) for node in shared_nodes])


    def get_node_positions(self, *args, **kwargs):
        """Get the node positions in the layered layout."""
        # What we would like to do, is apply the layout function to a combined, layered network.
        # However, networkx layout functions are not implemented for the multi-dimensional case.
        # Futhermore, even if there was such a layout function, there probably would be no straightforward way to
        # specify the planarity requirement for nodes within a layer.
        # Therefor, we compute the layout for the full network in 2D, and then apply the
        # positions to the nodes in all planes.
        # For a force-directed layout, this will approximately do the right thing.
        # TODO: implement FR in 3D with layer constraints.

        composition = self.graphs[0]
        for h in self.graphs[1:]:
            composition = nx.compose(composition, h)

        pos = self.layout(composition, *args, **kwargs)

        self.node_positions = dict()
        for z, g in enumerate(self.graphs):
            self.node_positions.update({(node, z) : (*pos[node], z) for node in g.nodes()})


    def draw_nodes(self, nodes, *args, **kwargs):
        x, y, z = zip(*[self.node_positions[node] for node in nodes])
        self.ax.scatter(x, y, z, *args, **kwargs)


    def draw_edges(self, edges, *args, **kwargs):
        segments = [(self.node_positions[source], self.node_positions[target]) for source, target in edges]
        line_collection = Line3DCollection(segments, *args, **kwargs)
        self.ax.add_collection3d(line_collection)


    def get_extent(self, pad=0.1):
        xyz = np.array(list(self.node_positions.values()))
        xmin, ymin, _ = np.min(xyz, axis=0)
        xmax, ymax, _ = np.max(xyz, axis=0)
        dx = xmax - xmin
        dy = ymax - ymin
        return (xmin - pad * dx, xmax + pad * dx), \
            (ymin - pad * dy, ymax + pad * dy)


    def draw_plane(self, z, *args, **kwargs):
        (xmin, xmax), (ymin, ymax) = self.get_extent(pad=0.1)
        u = np.linspace(xmin, xmax, 10)
        v = np.linspace(ymin, ymax, 10)
        U, V = np.meshgrid(u ,v)
        W = z * np.ones_like(U)
        self.ax.plot_surface(U, V, W, *args, **kwargs)


    def draw_node_labels(self, node_labels, *args, **kwargs):
        for node, z in self.nodes:
            if node in node_labels:
                ax.text(*self.node_positions[(node, z)], node_labels[node], *args, **kwargs)


    def draw(self):

        self.draw_edges(self.edges_within_layers,  color='k', alpha=0.3, linestyle='-', zorder=2)
        self.draw_edges(self.edges_between_layers, color='k', alpha=0.3, linestyle='--', zorder=2)

        for z in range(self.total_layers):
            self.draw_plane(z, alpha=0.2, zorder=1)
            self.draw_nodes([node for node in self.nodes if node[1]==z], s=300, zorder=3)

        if self.node_labels:
            self.draw_node_labels(self.node_labels,
                                  horizontalalignment='center',
                                  verticalalignment='center',
                                  zorder=100)


if __name__ == '__main__':

    # define graphs
    n = 5
    g = nx.erdos_renyi_graph(4*n, p=0.1)
    h = nx.erdos_renyi_graph(3*n, p=0.2)
    i = nx.erdos_renyi_graph(2*n, p=0.4)

    node_labels = {nn : str(nn) for nn in range(4*n)}

    # initialise figure and plot
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    LayeredNetworkGraph([g, h, i], node_labels=node_labels, ax=ax, layout=nx.spring_layout)
    ax.set_axis_off()
    plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Networkx中的多层图 的相关文章

  • 如何在Python的SciPy中更改稀疏矩阵中的元素?

    我构建了一个小代码 我想用它来解决涉及大型稀疏矩阵的特征值问题 它工作正常 我现在要做的就是将稀疏矩阵中的一些元素设置为零 即最顶行中的元素 对应于实现边界条件 我可以调整下面的列向量 C0 C1 和 C2 来实现这一点 不过我想知道是否有
  • 使用 matplotlib 从“列表列表”绘制 3D 曲面

    我已经搜索了一些 虽然我可以找到许多有用的网格网格示例 但没有一个清楚地表明我如何将列表列表中的数据转换为可接受的形式 以适应我所讨论的各种方式 当谈到 numpy matplotlib 以及我所看到的建议的术语和步骤顺序时 我有点迷失 我
  • opencv水印周围的轮廓

    我想在图像中的水印周围画一个框 我已经提取了水印并找到了轮廓 但是 不会在水印周围绘制轮廓 轮廓是在我的整个图像上绘制的 请帮我提供正确的代码 轮廓坐标的输出为 array 0 0 0 634 450 634 450 0 dtype int
  • Kivy - 有所有颜色名称的列表吗?

    在 Kivy 中 小部件 color属性允许输入其值作为字符串颜色名称 也 例如在 kv file Label color red 是否有所有可能的颜色名称的列表 就在这里 来自Kivy 的文档 https kivy org doc sta
  • 工作日重新订购 Pandas 系列

    使用 Pandas 我提取了一个 CSV 文件 然后创建了一系列数据来找出一周中哪几天崩溃最多 crashes by day bc DAY OF WEEK value counts 然后我将其绘制出来 但当然它按照与该系列相同的排名顺序绘制
  • 如何在 Python 中加密并在 Java 中解密?

    我正在尝试在 Python 程序中加密一些数据并将其保存 然后在 Java 程序中解密该数据 在Python中 我像这样加密它 from Crypto Cipher import AES KEY 1234567890123456789012
  • 如何使用文本相似性删除 pandas 数据框中相似(不重复)的行?

    我有数千个数据 这些数据可能相似也可能不相似 使用 python 的默认函数 drop duplicates 并没有真正的帮助 因为它们只检测相似的数据 例如 如果我的数据包含类似以下内容怎么办 嗨 早上好 嗨 早上好 Python 不会将
  • 结构差异 sudo() run('sudo 命令')

    我想知道函数之间有什么区别sudo 和函数run sudo u user smth 文档上有 sudo 在所有运行方式上都是相同的 除了它总是换行 调用 sudo 程序中的给定命令以提供超级用户 特权 但有几次 sudo cmd 提示我输入
  • 从扫描文档中提取行表 opencv python

    我想从扫描的表中提取信息并将其存储为 csv 现在我的表提取算法执行以下步骤 应用倾斜校正 应用高斯滤波器进行去噪 使用 Otsu 阈值进行二值化 进行形态学开局 Canny 边缘检测 进行霍夫变换以获得表格行 去除重复行 10像素范围内相
  • Django 的 request.FILES 出现 UnicodeDecodeError

    我在视图调用中有以下代码 def view request body u for filename f in request FILES items body body Filename filename n f read n 在某些情况下
  • Tensorflow 与 Keras 的兼容性

    我正在使用 Python 3 6 和 Tensorflow 2 0 并且有一些 Keras 代码 import keras from keras models import Sequential from keras layers impo
  • Matplotlib 中 x 轴标签的频率和旋转

    我在下面编写了一个简单的脚本来使用 matplotlib 生成图形 我想将 x tick 频率从每月增加到每周并轮换标签 我不知道从哪里开始 x 轴频率 我的旋转线产生错误 TypeError set xticks got an unexp
  • 如何在 pandas 中使用 read_fwf 跳过空行?

    I use pandas read fwf http pandas pydata org pandas docs stable generated pandas read fwf htmlPython pandas 0 19 2 中的函数读
  • Python:IndexError:修改代码后列表索引超出范围

    我的代码应该提供以下格式的输出 我尝试修改代码 但我破坏了它 import pandas as pd from bs4 import BeautifulSoup as bs from selenium import webdriver im
  • ANTLR 获取并拆分词法分析器内容

    首先 对我的英语感到抱歉 我还在学习 我为我的框架编写 Python 模块 用于解析 CSS 文件 我尝试了 regex ply python 词法分析器和解析器 但我发现自己在 ANTLR 中 第一次尝试 我需要解析 CSS 文件中的注释
  • 将seaborn.palplot轴添加到现有图形中以可视化不同调色板

    将seaborn人物添加到子图中是usually https seaborn pydata org examples cubehelix palette html创建图形时通过传递 ax 来完成 例如 sns kdeplot x y cma
  • Python SSL X509:KEY_VALUES_MISMATCH

    Python HTTPS server from http server import HTTPServer SimpleHTTPRequestHandler import ssl https stackoverflow com a 408
  • 如何与其他用户一起使用 pyenv?

    如何与其他用户一起使用 pyenv 例如 如果我在用户 test 的环境中安装了 pyenv 则当我以 test 身份登录时可以使用 pyenv 但是 当我以其他用户 例如 root 身份登录时如何使用 pyenv 即使你这么做了 我也会s
  • python 线程安全可变对象复制

    Is 蟒蛇的copy http docs python org 2 library copy html模块线程安全吗 如果不是 我应该如何在 python 中以线程安全的方式复制 deepcopy 可变对象 蟒蛇的GIL http en w
  • TKinter 中的禁用/启用按钮

    我正在尝试制作一个像开关一样的按钮 所以如果我单击禁用按钮 它将禁用 按钮 有效 如果我再次按下它 它将再次启用它 我尝试了 if else 之类的东西 但没有成功 这是一个例子 from tkinter import fenster Tk

随机推荐

  • 更改不同值的单元格颜色 - Gridview

    我需要区分两个连续的单元格 一行中的每个值 如果它们具有不同的值 则在将值绑定到网格视图时 因此 如果在第 1 行中我有单元格 ABC 在第 2 行中我有单元格 CBA 我需要用不同的颜色为每个单元格着色 最好的方法是什么 这称为条件格式
  • 什么是渐进增强?

    Jeff 在谈论使用 JQuery 编写 stackoverflow 时提到了 渐进增强 的概念 经过快速谷歌之后 我发现了一些关于它的高层讨论 谁能推荐一个作为程序员开始的好地方 具体来说 我一直在用 PHP 编写 Web 应用程序 并希
  • 如何解锁 Eclipse 4.2 (Juno) 中的工具栏

    我从 Eclipse Indigo 3 7 迁移到 Juno 4 2 在 Juno 中 所有工具栏似乎都被永久锁定 有没有办法解锁它们以便可以移动或重新排列它们 尝试 Windows 首选项 外观 看打印 然后在搜索框中输入 主题 或转到
  • 使用 R 代码的移动平均线

    我需要 R 代码的第一部分是 编写一个执行以下操作的 R 函数 给定一个序列 xN x1 x2 xN of N 观察 该函数返回一个移动平均值向量 其中计算每个平均值 k 个连续观察值 将函数命名为 ma 其参数为 向量 xN 和 k 到目
  • 基于文件类型的应用程序选择对话框

    我正在尝试创建一个对话框 它将显示打开给定文件类型的可用应用程序列表 我一直在 stackoverflow 上查看一些解决相同问题的问题 但由于缺乏答案而迷失了方向 我特别关注这个问题 在 Android 中 如何根据文件类型显示应用程序选
  • 使用 jquery post for mvc 3 在部署时不起作用

    所以我有这个 MVC 3 应用程序 它有一个下拉列表 我用它通过 jquery 填充 div 它在本地工作正常 但当我将其部署到服务器时 它重定向不正确 这是我的 jquery ddlCategoryMain change function
  • 将 mm/dd/yyyy 转换为 yyyymmdd (VB.NET)

    有什么方法可以将日期格式 dd mm yyyy 转换为 yyyymmdd 格式吗 例如从 25 07 2011 到 20110725 在 VB NET 中 日期本身不have固有的格式 您可以将字符串解析为DateTime通过解析它dd M
  • 如何在bash函数中显示数字到小数点后两位

    我应该如何获取以百分之秒为单位的数字并将其以秒为单位显示到小数点后两位 我不确定遵循 dTime 函数的伪代码 但我认为您会得到我的目标 function time echo date N 10000000 function dTime e
  • 用于存储用户位置历史记录的 MongoDB 架构

    我想使用 MongoDB 来存储我的用户位置历史记录 当然要征得他们的同意 我看到以下三个选项 为所有用户创建一个位置集合 每个文档都有一个 userId 字段和一个时间字段 这两个字段都将被索引 该集合中的行数可能会增长到超过 1 亿行
  • 绑定到 Date() 对象时如何格式化 input[time] 的值

    我将变量绑定到时间类型的输入字段 但显示的格式错误 它显示时间如下 08 54 30 088我真正需要的是这样的格式 08 54 我尝试使用过滤器设置输入字段的值 value datetime date date HH mm 但我的编辑说我
  • 为什么Windows和Linux的标准库函数名称不同?

    我正在将 Windows 库移植到 Android 使用 GNU 标准 C 库选项 libstdc v3 VC 和 GNU 库之间似乎存在许多命名差异 例如 stricmp叫做strcasecmp instead unlink叫做unlin
  • 使用 Sharepoint 事件接​​收器在文档库中创建文件夹

    我使用以下代码在文档库中创建一个文件夹 该事件被触发并执行到我的代码的最后一行 没有任何问题 但是 该文件夹未在我的文档库中创建或列出 public override void ItemAdded SPItemEventProperties
  • 如何在javascript中处理(® ´ © ¿ ¡ ° À ) 特殊字符?

    我需要开发一个 javascript 函数 不允许字符串中出现特殊字符 问题是IE8无法识别字符串中的特殊字符 并且在使用indexOf 方法时返回 1 处理这些特殊字符的正确方法是什么 只要您的所有编码都是正确的 您是否将文件另存为 UT
  • numpy 的花式索引是如何实现的?

    我正在对 2D 列表和 numpy 数组进行一些实验 由此 我提出了三个我很想知道答案的问题 首先 我初始化了一个 2D python 列表 gt gt gt my list 1 2 3 4 5 6 7 8 9 然后我尝试用元组索引列表 g
  • 收到错误:WebSphere MQ 原因代码 2538?

    我在 Linux 上安装了 WebSphere MQ 和 WebSphere Message Broker 当我执行mqsicreateexecutiongroup我收到一条错误消息 BIP1046E 无法连接到队列管理器 无法连接到队列管
  • Laravel 5 强制使用 HTTPS 登录路由到 HTTP 的问题

    Laravel 版本 Laravel 5 4 30 我遇到一个问题 我的生产代码托管在通过 HTTPS 提供服务的负载均衡器后面的 AWS Elastic Beanstalk 上 当使用内置的 auth 特征和 make auth 控制器来
  • 在 Android 上将游戏资源下载到 SD 卡

    我正在开发一个安卓游戏必须下载一些assets to the SD card使应用程序的大小尽可能小 我正在考虑使用未压缩的zip文件来捆绑所有资产 客户的一个要求是protect尽可能多地使用这些资产 作为 apk 的一部分被认为是足够的
  • Android Twilio 视频通话,唤醒应用程序并带到前台

    我正在尝试使用 Twilio Video Call 提供本机视频通话体验 这是场景 人 AAA 称人 BBB BBB 没有打开应用程序 在后台或前台 应用程序处于终止状态 手机甚至可能被锁定 当来自 AAA 的电话到达时 应用程序将打开 并
  • 投影 - 将 3d 转换为 2d

    我有问题或者很好 我不知道如何将具有 x y z 值的 3d 点转换为 2d 点 我必须绘制投影 其中我确实有点的 x y z 值 但我不知道如何将它们转换为 2d 以便我可以将它们移动到我的轴上 我一直在浏览维基和谷歌 但是我不太确定应该
  • Networkx中的多层图

    我想创建一个多层图 如附图所示 通过连接用以下代码编写的两个图 使用networkx Graph g1 nx read edgelist sample txt nodetype str pos nx shell layout g plt f