这是我从here开始的延伸作品。我想设置'm'
中的最后一个元素unique_liss
出现在其余节点的顶部位置,例如this 。但是,生成的大多数图像都是这样的:
这是我的代码:
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')
请注意,此代码仅确保该节点位于中心的右上角,而不是离右上角最近的节点