简体   繁体   中英

Draw nodes following a specific order on Networkx in Python?

I didn't find any answer to the question I asked, maybe because I didn't use the correct words to express it, so I'll try asking her hoping someone can help me, thanks in advance. I'm trying to draw graphs using the NetworkX library, version 2.5, with Python 3.9, running on Debian. My graph consists in a node "s", a node "t", multiple nodes t_i, 1 <= i <= n, and multiple nodes v_j, 1 <= j <= m. There are edges connecting "s" and t_i nodes, between some t_i and v_j nodes, and between v_j and "t" nodes.

Is it possible to draw it like in the picture below (includes edges of course)? I didn't find a way to order how the nodes are displayed...

在此处输入图像描述

Thanks a lot !

You can use the multipartite_layout for your desired positioning. You need to specify in a node attribute (see level below) to which group the node should belong and then retrieve a layout in the given levels. Adding edges will not change the position of the nodes, so I did not added them to the following minimal example:

import networkx as nx
import matplotlib.pylab as pl

G = nx.Graph()

G.add_node("s", level=0)
G.add_node("t_1", level=1)
G.add_node("t_2", level=1)
G.add_node("v_1", level=2)
G.add_node("v_2", level=2)
G.add_node("v_3", level=2)
G.add_node("t", level=3)

pos = nx.multipartite_layout(G, subset_key="level")

nx.draw(G, pos, with_labels=True)
pl.show()

Result

在此处输入图像描述

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