首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用networkx - Python显示自循环

问使用networkx - Python显示自循环
EN

Stack Overflow用户
提问于 2017-05-25 19:51:53
回答 1查看 4.9K关注 0票数 2

我正在使用来自networkx的networkx类,根据文档,它应该允许自循环。但是,在使用Matplotlib进行绘图时,我无法看到任何自循环,无论

代码语言:javascript
复制
print(G.nodes_with_selfloops())

返回具有自循环的节点列表。我想知道如何显示这些自我循环。

我使用这些函数来绘制:

代码语言:javascript
复制
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw_networkx(G,pos,font_color='k',node_size=500, edge_color='b', alpha=0.5)
EN

回答 1

Stack Overflow用户

发布于 2021-08-07 13:29:35

当我试图使用networkx绘制一个chord图时,我也遇到了同样的问题。在较早版本的networkx (2.5)中,自循环是在节点后面用一个点绘制的(这意味着您根本看不到它们)。在新版本(2.6.2)上,自循环绘制的方向与下面的图像相同。

网络中的自循环x 2.6.2

如果这对您来说已经足够了,请尝试更新networkx。看来这个问题已经解决了。至少,文档有一些关于它的信息

但是,如果这对您来说还不够(就像对我一样),您可以编写一个自定义代码来更好地绘制自循环。我为这个任务创建了一个存储库。它允许绘制不同方向的自环,将视线从中心移开:

使用我的代码的自循环

下面简单介绍一下它背后的想法:

  1. 你知道循环的开始和结束坐标。这些只是节点的坐标。
  2. 你还需要2个点才能画出一个Bézier曲线的自循环.你希望他们离中心更远,而不是图的节点。您还希望它们在正交方向远离节点,从中心到节点的向量。

如果这听起来太复杂了,我希望这张图片能清楚地说明:锚的可视化

  1. 当我们得到锚点时,我们可以通过它们绘制Bézier曲线。这就是它的样子:自环

这是代码:

代码语言:javascript
复制
from typing import Optional

import matplotlib.pyplot as plt
from matplotlib.path import Path as MplPath  # To avoid collisions with pathlib.Path
import matplotlib.patches as patches
import networkx as nx
import numpy as np


# Some useful functions
def normalize_vector(vector: np.array, normalize_to: float) -> np.array:
    """Make `vector` norm equal to `normalize_to`
    
    vector: np.array
        Vector with 2 coordinates
    
    normalize_to: float
        A norm of the new vector
        
    Returns
    -------
    Vector with the same direction, but length normalized to `normalize_to`
    """
    
    vector_norm = np.linalg.norm(vector)
    
    return vector * normalize_to / vector_norm


def orthogonal_vector(point: np.array, width: float, normalize_to: Optional[float] = None) -> np.array:
    """Get orthogonal vector to a `point`

    point: np.array
        Vector with x and y coordinates of a point

    width: float
        Distance of the x-coordinate of the new vector from the `point` (in orthogonal direction)

    normalize_to: Optional[float] = None
        If a number is provided, normalize a new vector length to this number
    
    Returns
    -------
    Array with x and y coordinates of the vector, which is orthogonal to the vector from (0, 0) to `point` 
    """
    EPSILON = 0.000001

    x = width
    y = -x * point[0] / (point[1] + EPSILON)

    ort_vector = np.array([x, y])

    if normalize_to is not None:
        ort_vector = normalize_vector(ort_vector, normalize_to)

    return ort_vector


def draw_self_loop(
    point: np.array,
    ax: Optional[plt.Axes] = None,
    padding: float = 1.5,
    width: float = 0.3,
    plot_size: int = 10,
    linewidth = 0.2,
    color: str = "pink",
    alpha: float = 0.5
) -> plt.Axes:
    """Draw a loop from `point` to itself

    !Important! By "center" we assume a (0, 0) point. If your data is centered around a different points,
    it is strongly recommended to center it around zero. Otherwise, you will probably get ugly plots

    Parameters
    ----------
    point: np.array
        1D array with 2 coordinates of the point. Loop will be drawn from and to these coordinates.
    padding: float = 1.5
        Controls how the distance of the loop from the center. If `padding` > 1, the loop will be
        from the outside of the `point`. If `padding` < 1, the loop will be closer to the center
    width: float = 0.3
        Controls the width of the loop
    linewidth: float = 0.2
        Width of the line of the loop
    ax: Optional[matplotlib.pyplot.Axes]:
        Axis on which to draw a plot. If None, a new Axis is generated
    plot_size: int = 7
        Size of the plot sides in inches. Ignored if `ax` is provided    
    color: str = "pink"
        Color of the arrow
    alpha: float = 0.5
        Opacity of the edge
    
    Returns
    -------
    Matplotlib axes with the self-loop drawn
    """

    if ax is None:
        fig, ax = plt.subplots(figsize=(plot_size, plot_size))
    
    point_with_padding = padding * point

    ort_vector = orthogonal_vector(point, width, normalize_to=width)

    first_anchor = ort_vector + point_with_padding
    second_anchor = -ort_vector + point_with_padding

    verts = [point, first_anchor, second_anchor, point]
    codes = [MplPath.MOVETO, MplPath.CURVE4, MplPath.CURVE4, MplPath.CURVE4]

    path = MplPath(verts, codes)

    patch = patches.FancyArrowPatch(
        path=path,
        facecolor='none',
        lw=linewidth,
        arrowstyle="-|>",
        color=color,
        alpha=alpha,
        mutation_scale=30  # arrowsize in draw_networkx_edges()
    )
    ax.add_patch(patch)

    return ax

绘制一个绘图的代码示例:

代码语言:javascript
复制
fig, ax = plt.subplots(figsize=(6, 6))

graph = nx.DiGraph(
    np.array([
        [1, 1, 1, 1, 1],
        [1, 0, 1, 0, 0],
        [1, 1, 1, 0, 1],
        [0, 0, 1, 0, 1],
        [1, 1, 1, 1, 1]
    ])
)

pos = nx.circular_layout(graph, center=(0, 0))

nx.draw_networkx_nodes(graph, pos, ax=ax)
nx.draw_networkx_edges(graph, pos, ax=ax)

for node in graph.nodes:
    if (node, node) in graph.edges:
        draw_self_loop(point=pos[node], ax=ax, color="k", alpha=1, linewidth=1)
        
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)

结果:弦图

您可以在我的存储库中找到更多的示例和函数来绘制一个漂亮的chord图。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44188755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档