如何用networkx绘制社区

2024-03-25

如何使用 python networkx 绘制其社区的图表,如下图所示:

图片网址 https://data.graphstream-project.org/talks/CSSS2012/media/Community_Structure2.jpg


的文档networkx.draw_networkx_nodes and networkx.draw_networkx_edges解释如何设置节点和边缘颜色。可以通过找到每个社区的节点位置然后绘制一个补丁(例如,matplotlib.patches.Circle)包含所有位置(然后是一些位置)。

难点是图形布局/设置节点位置。 AFAIK,networkx 中没有例程来实现“开箱即用”所需的图形布局。您想要执行的操作如下:

  1. 相对于彼此定位社区:创建一个新的加权图,其中每个节点对应于一个社区,权重对应于社区之间的边数。使用您最喜欢的图形布局算法(例如spring_layout).

  2. 在每个社区内定位节点:为每个社区创建一个新图。找到子图的布局。

  3. 合并 1) 和 3) 中的节点位置。例如。将 1) 中计算出的社区位置缩放至 10 倍;将这些值添加到该社区内所有节点的位置(如 2)中计算的那样。

I have been wanting to implement this for a while. I might do it later today or over the weekend.

EDIT:

瞧。现在您只需在节点周围(后面)绘制您最喜欢的补丁即可。

import numpy as np
import matplotlib.pyplot as plt
import networkx as nx

def community_layout(g, partition):
    """
    Compute the layout for a modular graph.


    Arguments:
    ----------
    g -- networkx.Graph or networkx.DiGraph instance
        graph to plot

    partition -- dict mapping int node -> int community
        graph partitions


    Returns:
    --------
    pos -- dict mapping int node -> (float x, float y)
        node positions

    """

    pos_communities = _position_communities(g, partition, scale=3.)

    pos_nodes = _position_nodes(g, partition, scale=1.)

    # combine positions
    pos = dict()
    for node in g.nodes():
        pos[node] = pos_communities[node] + pos_nodes[node]

    return pos

def _position_communities(g, partition, **kwargs):

    # create a weighted graph, in which each node corresponds to a community,
    # and each edge weight to the number of edges between communities
    between_community_edges = _find_between_community_edges(g, partition)

    communities = set(partition.values())
    hypergraph = nx.DiGraph()
    hypergraph.add_nodes_from(communities)
    for (ci, cj), edges in between_community_edges.items():
        hypergraph.add_edge(ci, cj, weight=len(edges))

    # find layout for communities
    pos_communities = nx.spring_layout(hypergraph, **kwargs)

    # set node positions to position of community
    pos = dict()
    for node, community in partition.items():
        pos[node] = pos_communities[community]

    return pos

def _find_between_community_edges(g, partition):

    edges = dict()

    for (ni, nj) in g.edges():
        ci = partition[ni]
        cj = partition[nj]

        if ci != cj:
            try:
                edges[(ci, cj)] += [(ni, nj)]
            except KeyError:
                edges[(ci, cj)] = [(ni, nj)]

    return edges

def _position_nodes(g, partition, **kwargs):
    """
    Positions nodes within communities.
    """

    communities = dict()
    for node, community in partition.items():
        try:
            communities[community] += [node]
        except KeyError:
            communities[community] = [node]

    pos = dict()
    for ci, nodes in communities.items():
        subgraph = g.subgraph(nodes)
        pos_subgraph = nx.spring_layout(subgraph, **kwargs)
        pos.update(pos_subgraph)

    return pos

def test():
    # to install networkx 2.0 compatible version of python-louvain use:
    # pip install -U git+https://github.com/taynaud/python-louvain.git@networkx2
    from community import community_louvain

    g = nx.karate_club_graph()
    partition = community_louvain.best_partition(g)
    pos = community_layout(g, partition)

    nx.draw(g, pos, node_color=list(partition.values())); plt.show()
    return

Addendum

尽管总体想法是合理的,但我上面的旧实现有一些问题。最重要的是,对于规模不均的社区来说,实施效果不佳。具体来说,_position_communities在画布上为每个社区提供相同数量的房地产。如果一些社区比其他社区大得多,这些社区最终会被压缩到与小社区相同的空间内。显然,这并不能很好地反映图的结构。

我写了一个用于可视化网络的库,它被称为netgraph https://github.com/paulbrodersen/netgraph。它包括上述社区布局例程的改进版本,在安排社区时还考虑了社区的大小。它完全兼容networkx and igraph图形对象,因此应该可以轻松快速地制作美观的图形(至少是这样的想法)。

import matplotlib.pyplot as plt
import networkx as nx

# installation easiest via pip:
# pip install netgraph
from netgraph import Graph

# create a modular graph
partition_sizes = [10, 20, 30, 40]
g = nx.random_partition_graph(partition_sizes, 0.5, 0.1)

# since we created the graph, we know the best partition:
node_to_community = dict()
node = 0
for community_id, size in enumerate(partition_sizes):
    for _ in range(size):
        node_to_community[node] = community_id
        node += 1

# # alternatively, we can infer the best partition using Louvain:
# from community import community_louvain
# node_to_community = community_louvain.best_partition(g)

community_to_color = {
    0 : 'tab:blue',
    1 : 'tab:orange',
    2 : 'tab:green',
    3 : 'tab:red',
}
node_color = {node: community_to_color[community_id] for node, community_id in node_to_community.items()}

Graph(g,
      node_color=node_color, node_edge_width=0, edge_alpha=0.1,
      node_layout='community', node_layout_kwargs=dict(node_to_community=node_to_community),
      edge_layout='bundled', edge_layout_kwargs=dict(k=2000),
)

plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用networkx绘制社区 的相关文章

  • SQLAlchemy 通过关联对象声明式多对多自连接

    我有一个用户表和一个朋友表 它将用户映射到其他用户 因为每个用户可以有很多朋友 这个关系显然是对称的 如果用户A是用户B的朋友 那么用户B也是用户A的朋友 我只存储这个关系一次 除了两个用户 ID 之外 Friends 表还有其他字段 因此
  • 使 django 服务器可以在 LAN 中访问

    我已经安装了Django服务器 可以如下访问 http localhost 8000 get sms http 127 0 0 1 8000 get sms 假设我的IP是x x x x 当我这样做时 从同一网络下的另一台电脑 my ip
  • 通过最小元素比较对 5 个元素进行排序

    我必须在 python 中使用元素之间的最小比较次数来建模对 5 个元素的列表进行排序的执行计划 除此之外 复杂性是无关紧要的 结果是一个对的列表 表示在另一时间对列表进行排序所需的比较 我知道有一种算法可以通过 7 次比较 总是在元素之间
  • Python - StatsModels、OLS 置信区间

    在 Statsmodels 中 我可以使用以下方法拟合我的模型 import statsmodels api as sm X np array 22000 13400 47600 7400 12000 32000 28000 31000 6
  • Flask 会话变量

    我正在用 Flask 编写一个小型网络应用程序 当两个用户 在同一网络下 尝试使用应用程序时 我遇到会话变量问题 这是代码 import os from flask import Flask request render template
  • 根据列值突出显示数据框中的行?

    假设我有这样的数据框 col1 col2 col3 col4 0 A A 1 pass 2 1 A A 2 pass 4 2 A A 1 fail 4 3 A A 1 fail 5 4 A A 1 pass 3 5 A A 2 fail 2
  • 测试 python Counter 是否包含在另一个 Counter 中

    如何测试是否是pythonCounter https docs python org 2 library collections html collections Counter is 包含在另一个中使用以下定义 柜台a包含在计数器中b当且
  • Python 函数可以从作用域之外赋予新属性吗?

    我不知道你可以这样做 def tom print tom s locals locals def dick z print z name z name z guest Harry print z guest z guest print di
  • 如何加速Python中的N维区间树?

    考虑以下问题 给定一组n间隔和一组m浮点数 对于每个浮点数 确定包含该浮点数的区间子集 这个问题已经通过构建一个解决区间树 https en wikipedia org wiki Interval tree 或称为范围树或线段树 已经针对一
  • IO 密集型任务中的 Python 多线程

    建议仅在 IO 密集型任务中使用 Python 多线程 因为 Python 有一个全局解释器锁 GIL 只允许一个线程持有 Python 解释器的控制权 然而 多线程对于 IO 密集型操作有意义吗 https stackoverflow c
  • python获取上传/下载速度

    我想在我的计算机上监控上传和下载速度 一个名为 conky 的程序已经在 conky conf 中执行了以下操作 Connection quality alignr wireless link qual perc wlan0 downspe
  • 无法在 Python 3 中导入 cProfile

    我试图将 cProfile 模块导入 Python 3 3 0 但出现以下错误 Traceback most recent call last File
  • Pandas:merge_asof() 对多行求和/不重复

    我正在处理两个数据集 每个数据集具有不同的关联日期 我想合并它们 但因为日期不完全匹配 我相信merge asof 是最好的方法 然而 有两件事发生merge asof 不理想的 数字重复 数字丢失 以下代码是一个示例 df a pd Da
  • 每个 X 具有多个 Y 值的 Python 散点图

    我正在尝试使用 Python 创建一个散点图 其中包含两个 X 类别 cat1 cat2 每个类别都有多个 Y 值 如果每个 X 值的 Y 值的数量相同 我可以使用以下代码使其工作 import numpy as np import mat
  • 如何在 Python 中追加到 JSON 文件?

    我有一个 JSON 文件 其中包含 67790 1 kwh 319 4 现在我创建一个字典a dict我需要将其附加到 JSON 文件中 我尝试了这段代码 with open DATA FILENAME a as f json obj js
  • Conda SafetyError:文件大小不正确

    使用创建 Conda 环境时conda create n env name python 3 6 我收到以下警告 Preparing transaction done Verifying transaction SafetyError Th
  • 如何计算 pandas 数据帧上的连续有序值

    我试图从给定的数据帧中获取连续 0 值的最大计数 其中包含来自 pandas 数据帧的 id date value 列 如下所示 id date value 354 2019 03 01 0 354 2019 03 02 0 354 201
  • 在 Qt 中自动调整标签文本大小 - 奇怪的行为

    在 Qt 中 我有一个复合小部件 它由排列在 QBoxLayouts 内的多个 QLabels 组成 当小部件调整大小时 我希望标签文本缩放以填充标签区域 并且我已经在 resizeEvent 中实现了文本大小的调整 这可行 但似乎发生了某
  • 使用 Python 的 matplotlib 选择在屏幕上显示哪些图形以及将哪些图形保存到文件中

    我想用Python创建不同的图形matplotlib pyplot 然后 我想将其中一些保存到文件中 而另一些则应使用show 命令 然而 show 显示all创建的数字 我可以通过调用来避免这种情况close 创建我不想在屏幕上显示的绘图
  • 如何将输入读取为数字?

    这个问题的答案是社区努力 help privileges edit community wiki 编辑现有答案以改进这篇文章 目前不接受新的答案或互动 Why are x and y下面的代码中使用字符串而不是整数 注意 在Python 2

随机推荐

  • Pygame水波纹效果

    我已经用 Google 搜索过它 但没有现成的脚本 与 Flash 上的相同效果相反 我已经检查过算法水效应解释 http www gamedev net page resources technical graphics programm
  • SuppressWarnings 不适用于 FindBugs

    我在 Eclipse 项目上运行 FindBugs 并收到一个潜在的错误警告 我想出于特定原因 在本问题的上下文之外 抑制该错误 这是代码 public class LogItem private String name private v
  • Visual Studio -- 不创建 exe 文件

    我正在使用 Visual Studio 2015 for C 并创建了以下基本程序 include
  • Bud1%@@@@E%DSDB`@@@是什么?

    我为客户制作了一个小应用程序 该应用程序扫描files包含几个文本文件的目录 然后它将每个文件读入一个字符串 每个文件都有标题和文章文本 这两部分用管道字符分隔 如下所示 article title article text 该脚本显示用于
  • 我自己的 Python OCR 程序

    我还是一个初学者 但我想写一个字符识别程序 这个程序还没有准备好 而且我编辑了很多 所以评论可能不完全一致 我将使用 8 个连通性来标记连通分量 from PIL import Image import numpy as np im Ima
  • 文件夹浏览器对话框的问题

    如果对话框中单击Make newfolder 则开始编辑刚刚创建的文件夹的名称并单击OK OKdialogrezalt返回 但在属性中SelectedPath他将文件夹命名为New文件夹 然后就有默认的名称 发生这种情况是因为当我们创建时
  • 为什么对 Deref::deref 结果断言会因类型不匹配而失败?

    以下是Deref示例来自Rust 编程语言 https doc rust lang org book first edition deref coercions html除了我添加了另一个断言 为什么assert eq与deref也相等 a
  • 如何在nodeJS项目中使用Jest全局Setup和Teardown?

    我使用 jest 将测试添加到我的 Node js 项目中 但对于每个测试套件 都有一个 beforeAll 方法用于创建新的测试服务器并连接到 mongo 数据库 还有一个 afterAll 方法用于关闭测试服务器和数据库 我想对所有测试
  • AWS DocumentDB 与 Robo 3T (Robomongo)

    我想将 Mac 笔记本电脑上的 Robo 3T 以前称为 robomongo 与 AWS 的 DocumentDB 连接 我遵循了大量教程 但找不到任何特定于 DocumentDB 的教程 在测试阶段 它通过了步骤 1 连接到我的 EC2
  • INSTALL_FAILED_OLDER_SDK 的 minSdkVersion 低于设备 API 版本

    在全新安装最新的 AndroidStudio 时 运行新项目模板 最小 SDK 选择为 15 ICS 尝试在运行 API 19 的 Nexus 5 上运行 我收到 INSTALL FAILED OLDER SDK 错误并显示以下输出 我没有
  • 类型不匹配:无法从连接转换为连接

    我想要 JDBC 连接到 MS Access 但 Class forName sun jdbc odbc JdbcOdbcDriver Connection con DriverManager getConnection jdbc odbc
  • 如何在 Room 中插入具有一对多关系的实体

    我正在使用 Room 构建一个数据库 但我不知道如何将具有关系 在我的例子中是一对多 的新元素插入到数据库中 没有解决方案曾经讨论过插入 他们只讨论了查询数据 这是 DAO Dao abstract class ShoppingListsD
  • 在WPF中,为什么MouseLeave触发而不是MouseDown?

    这是我的代码
  • 这个特权准则有什么问题吗?

    如何检查 检查 php代码或页面中的权限 我使用爆炸和 in array 用户登录并进入 检查 页面后 代码必须检查用户的权限是否具有 dataDisplay 权限 但 检查 页面中的代码不会执行此操作 我的 检查 页面代码有什么问题 这是
  • Windows10 上使用 VirtualBox 的 Vagrant:在您的 PATH 中找不到“Rsync”

    我在 Windows 7 系统上使用 Vagrant 一段时间了 现在我有一台装有 Windows 10 的新 PC 我安装了 Oracle Virtual Box 和 Vagrant 并尝试使用命令 vagrant up 启动计算机 Va
  • r 中的 ifelse 匹配向量

    我有一个如下所示的数据框 gt df lt data frame A c NA 1 2 3 4 B c NA 5 2 6 4 C c NA NA 2 NA NA gt df A B C 1 NA NA NA 2 1 5 NA 3 2 2 2
  • C/C++ 的多线程内存分配器

    我目前有大量的多线程服务器应用程序 并且我正在寻找一个好的多线程内存分配器 到目前为止 我在以下两点之间左右为难 太阳乌梅 谷歌的tcmalloc 英特尔的线程构建块分配器 埃默里 伯杰的宝藏 据我所知 hoard 可能是最快的 但我在今天
  • 为什么冒泡排序最好情况的时间复杂度是O(n)

    我按照书中使用的方法推导了冒泡排序在最佳情况下的时间复杂度算法2 2 但结果是 O n 2 以下是我的推导 希望大家帮我找出哪里错了 public void bubbleSort int arr for int i 0 len arr le
  • 让 Kotlin 序列化器与 Retrofit 配合使用

    我无法让 Kotlin Serializer 与 Retrofit 一起使用 我在用com jakewharton retrofit retrofit2 kotlinx serialization converter 0 5 0与 Retr
  • 如何用networkx绘制社区

    如何使用 python networkx 绘制其社区的图表 如下图所示 图片网址 https data graphstream project org talks CSSS2012 media Community Structure2 jp