How to let graph have “correct” indices?

I have an array of pairs which is [[20, 22], [21, 22], [23, 22], [308, 21], [309, 22], [313, 22], [314, 22], [315, 23], [316, 21]],so its default length of es is 9 but default length of ‘vs’ is 317 (because maximum of numbers in array is 316).
So when I want to draw picture of the graph which is generated by this array, it has 317 nodes and it’s wrong:


How to get correct indices for this graph or remove wrong nodes from the picture?
Thank you very much.

How are you constructing the graph? There are two constructors that could take care of the assignment of your numeric identifiers to the name attribute: Graph.TupleList() and Graph.DictList().

Graph.TupleList() can‘t solve my question completely,because it will lose original number of nodes such as:

up_array = [[20, 22], [21, 22], [23, 22], [308, 21, 22], [309, 22], [313, 22], [314, 22], [315, 23, 22], [316, 21, 22]]
for elem in up_array:
    if len(elem) < 2:
        up_array.remove(elem)
graph_up = ig.Graph.TupleList(up_array, directed=True)
# indices of graph_up's vs is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

No it won’t; the original IDs are available in the name vertex attribute:

>>> print(graph_up.vs["name"])
[20, 22, 21, 23, 308, 309, 313, 314, 315, 316]

The vertex IDs in igraph are always in the range [0; num_vertices-1]; this is due to how the underlying C library behaves. However, the name vertex attribute can be filled with the “real” IDs. Furthermore, if you use only strings in the name vertex attribute, then you can use these strings to refer to the vertices directly:

# Preprocessing your input array and converting IDs to strings
up_array = [[20, 22], [21, 22], [23, 22], [308, 21, 22], [309, 22], [313, 22], [314, 22], [315, 23, 22], [316, 21, 22]]
up_array = [item for item in up_array if len(item) == 2]
up_array = [(str(u), str(v)) for u, v in up_array]

# Creating the graph
graph_up = ig.Graph.TupleList(up_array, directed=True)

# Getting the degree of the node with `name` == 309
>>> print(graph_up.degree("309"))
1

# Getting all the names of the vertices
>>> print(graph_up.vs["name"])
['20', '22', '21', '23', '309', '313', '314']

# Creating a reverse mapping from names to IDs
>>> id_map = {v: k for k, v in enumerate(graph_up.vs["name"])}
>>> id_map
{'20': 0, '22': 1, '21': 2, '23': 3, '309': 4, '313': 5, '314': 6}
1 Like