簡體   English   中英

更改 networkx 圖中節點的順序/位置

[英]Change order/position of nodes in plot of networkx

我有一個熊貓數據框,想根據數據框繪制一個網絡。 當前的情節看起來像: 在此處輸入圖片說明

它從右上角開始,一直到左邊。 如果我下次繪制它,它可以有不同的起始位置,我該如何避免它? 此外,如何將起始節點設置在左上角,而將結束節點(我也可以預先拒絕)設置在右下角?

到目前為止,我的代碼是:

###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

您可以使用spring_layout 種子屬性來防止您的圖形節點移動每次繪制:

種子

(int, RandomState instance or None optional (default=None)) – 為確定性節點布局設置隨機狀態。 如果是 int,seed 是隨機數生成器使用的種子,如果是numpy.random.RandomState實例,seed 是隨機數生成器,如果None ,隨機數生成器是RandomState使用的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)

在此處輸入圖片說明

如果您想在特殊位置設置特定節點,則可以使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM