如何用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绘制社区 的相关文章

随机推荐

  • 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