简体   繁体   中英

Change order/position of nodes in plot of networkx

I am having a pandas dataframe and want to plot a network based on the dataframe. The current plot looks like: 在此处输入图片说明

It starts in the right above corner and goes to the left one. If i plot it the next time, it can have a different starting position, how can I avoid it? And furthermore how can I set the starting node into the left above corner and the end node (which i can also decline upfront) set always in the right down corner?

My code until now is:

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

packages I use is networkx and matlotlib

You can use seed attribute of spring_layout to prevent your graph nodes from moving each draw:

seed

(int, RandomState instance or None optional (default=None)) – Set the random state for deterministic node layouts. If int, seed is the seed used by the random number generator, if numpy.random.RandomState instance, seed is the random number generator, if None , the random number generator is the RandomState instance used by numpy.random.

Or specify a layout by yourself, like:

pos = {
    1: [0, 1],
    2: [2, 4]
    ...
}

You can combine both methods:

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)

在此处输入图片说明

You can use it if you want to set particular nodes in special places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM