如何在图形网络中设置自上而下的位置x

how to set a top-down position in a graph networkx

这是我从 开始的扩展工作。 我想设置 unique_liss 中的最后一个元素 'm' 像这样 出现在其余节点的顶部位置。 然而,大多数生成的图像是这样的:

这是我的代码:

Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
for node in edgesList:
    print('node-', node)
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A
import numpy as np
seed = 31
pos = nx.spring_layout(G)
plt.figure(figsize=(15,8))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500,
        seed=seed, node_color = 'skyblue')

尽管我将 for ..loop 更改为如下所示的反向循环:

for node in reversed(edgesList):
    print('node-', node)
    G.add_edge(*node,sep=',')

它不保证节点 'm' 的最后一个元素被应用到其余元素的顶部位置。 是否有人可以帮助如何设置最后一个节点永久出现在顶部位置?

这里有一个想法,根据感兴趣的节点相对于图形中心的相对位置来更新布局中的位置:

def get_graph_centroid(pos):
    return np.mean(np.array([a for a in pos.values()]), axis=0)

def find_flip(node_of_interest, pos):

    node_x, node_y = pos[node_of_interest]
    cx, cy = get_graph_centroid(pos)

    flip = [1,1]

    if node_x < cx:
        flip[0] = -1
    if node_y < cy:
        flip[1] = -1

    return flip

def make_flip(pos, flip):

    x,y = flip
    pos = {key: (x*a,y*b) for key, (a,b) in pos.items()}

    return pos



pos = nx.spring_layout(G)
plt.subplot(121)
nx.draw(G, pos=pos, with_labels=True, node_size = 500,
        seed=seed, node_color = 'skyblue')
plt.title('normal layout')

plt.subplot(122)
flip = find_flip('m', pos)
pos = make_flip(pos, flip)
nx.draw(G, pos=pos, with_labels=True, node_size = 500,
        seed=seed, node_color = 'skyblue')
plt.title('flipped layout')

请注意,此代码仅确保节点位于中心的右上角,而不是距离右上角最近的节点