networkx.drawing.layout.circular\u布局的节点顺序

2024-05-19 12:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python编码比较陌生,我使用以下代码生成一个包含40个节点的图,并使用以下代码给出节点的布局:

 pos = nx.circular_layout(graph_anchor, **kwargs)

以下代码创建图形锚定:

    graph_anchor = convert_ebunch_to_graph(ebunch_anchor)

def convert_ebunch_to_graph(ebunch):
    g = nx.DiGraph()
    g.add_weighted_edges_from(ebunch)

我的问题是,我如何计算出节点被绘制的顺序,也就是说,我如何计算出代码如何决定将哪些节点放在彼此旁边,以及以什么顺序排列它们


Tags: to代码posconvert编码节点布局代码生成
1条回答
网友
1楼 · 发布于 2024-05-19 12:25:56

nx.circular_layout的来源:

def circular_layout(G, dim=2, scale=1, center=None):
    # dim=2 only
    """Position nodes on a circle.

    Parameters
         
    G : NetworkX graph or list of nodes

    dim : int
       Dimension of layout, currently only dim=2 is supported

    scale : float
        Scale factor for positions

    center : array-like or None
       Coordinate pair around which to center the layout.

    Returns
       -
    dict :
       A dictionary of positions keyed by node

    Examples
        
    >>> G=nx.path_graph(4)
    >>> pos=nx.circular_layout(G)

    Notes
       
    This algorithm currently only works in two dimensions and does not
    try to minimize edge crossings.

    """
    import numpy as np

    G, center = process_params(G, center, dim)

    if len(G) == 0:
        pos = {}
    elif len(G) == 1:
        pos = {G.nodes()[0]: center}
    else:
        # Discard the extra angle since it matches 0 radians.
        theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
        theta = theta.astype(np.float32)
        pos = np.column_stack([np.cos(theta), np.sin(theta)])
        pos = _rescale_layout(pos, scale=scale) + center
        pos = dict(zip(G, pos))

    return pos

似乎位置是由360度除以节点数生成的。 哪一个节点在哪里结束由这一行决定:

        pos = dict(zip(G, pos))

zip(G,pos)按顺序遍历图的节点。并为他们分配职位。如果你想改变位置,你需要改变顺序

例如:

# make dummy graph
G = nx.from_numpy_array(np.random.rand(12,12)>0.5)

# test order of nodes:
for node in G.nodes:
    print(node)

0
1
2
3
4
5
6
7
8
9
10
11

pos = nx.circular_layout(G)
nx.draw_networkx(G, pos=pos)

enter image description here

这里,分配的第一个位置是节点0的位置,然后我们逆时针走

我找不到一种简单的方法来改变G中节点的顺序,因此这里有一个小的解决方法,它创建了一个随机顺序的新图形:

nodes = list(G.nodes(data=True))
edges = list(G.edges(data=True))
np.random.shuffle(nodes)

H=nx.Graph()
H.add_nodes_from(nodes)
H.add_edges_from(edges)

pos = nx.circular_layout(H)
nx.draw_networkx(H, pos=pos)

enter image description here

因此,更改图中节点的顺序会更改它们最终在循环布局中的位置

相关问题 更多 >