更改 networkx 绘图中节点的顺序/位置

3
我有一个Pandas数据帧,并想基于该数据帧绘制一个网络。当前的图表如下: enter image description here 它从右上角开始,向左下角延伸。如果我下次绘制它,它可能会有不同的起始位置,如何避免这种情况?此外,如何将起始节点设置为左上角,结束节点(也可以预先拒绝)始终设置为右下角?
我的代码到目前为止是:
###make the graph based on my dataframe
G3 = nx.from_pandas_edgelist(df2, 'Activity description', 'Activity followed', create_using=nx.DiGraph(), edge_attr='weight')

#plot the figure and decide about the layout
plt.figure(3, figsize=(18,18))
pos = nx.spring_layout(G3, scale=2)

#draw the graph based on the labels
nx.draw(G3, pos, node_size=500, alpha=0.9, labels={node:node for node in G3.nodes()})

#make weights with labels to the edges
edge_labels = nx.get_edge_attributes(G3,'weight')
nx.draw_networkx_edge_labels(G3, pos, edge_labels = edge_labels)
plt.title('Main Processes')

#save and plot the ifgure
plt.savefig('StandardProcessflow.png')
plt.show() 

我使用的包是networkx和matlotlib。


1
部分回答你的问题 - 你可以在 nx.spring_layout 中设置一个 seed,例如 pos=nx.spring_layout(G3, scale=2, seed=42)。看看是否有帮助。 - Itamar Mushkin
“seed=1” 对我来说看起来很合理,它是做什么的?它和 random_state 是相同的方法吗? - PV8
1
是的,就像@vurmux所解释的那样。 - Itamar Mushkin
1个回答

3
你可以使用spring_layoutseed属性来防止图形节点在每次绘制时移动:

seed

(int、RandomState实例或None(可选,默认为None)) - 为确定性节点布局设置随机状态。如果是int,则种子是随机数生成器使用的种子,如果是numpy.random.RandomState实例,则种子是随机数生成器,如果是None,则随机数生成器是由numpy.random使用的RandomState实例。

或者自己指定一个布局,例如:
pos = {
    1: [0, 1],
    2: [2, 4]
    ...
}

您可以同时使用两种方法:

G3 = nx.Graph()
G3.add_weighted_edges_from([
    (1,2,1),
    (2,3,2),
    (3,4,3),
    (3,6,1),
    (4,5,4)
])

pos = nx.spring_layout(G3, scale=2, seed=84)
pos[1] = [-20, 0]
pos[5] = [20, 0]

nx.draw(
    G3,
    pos,
    node_size=500,
    alpha=0.9,
    labels={node:node for node in G3.nodes()}
)

edge_labels = nx.get_edge_attributes(G3,'weight')
nx.draw_networkx_edge_labels(G3, pos, edge_labels = edge_labels)

enter image description here

如果您想在特定位置设置特定节点,则可以使用它。


对于pos [1],我需要写整数,还是也可以写标签?例如pos ['Milkman']。 - PV8
1
你需要在那里编写节点ID。如果你用单词代替它们(我猜的),你应该像你在评论中写的那样写它们。 - vurmux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接