I want to learn more about igraph libary. I want to make a simple graph with two nodes labeled at different time. In igraph tutorial I have found its possible to label the list at all after I generated the graph. It works with code:
from igraph import *
p = Graph()
p.add_vertices(1)
p.vs["label"] = ["test", "test1"]
layout = p.layout("kk")
plot(p, layout=layout)
but what, if I want to label the graph step by step. That means I first want add some vertices then label it. Then perform some calculation add some other vertices and label that other on after I added it without loosing the first ones. I just tried it with following code, but for some reason it does not work as I want. How can I solve it?
from igraph import *
p = Graph()
p.add_vertices(1)
p.vs["label"] = ["test"]
p.add_vertices(1)
p.vs["label"][1] = "test1"
layout = p.layout("kk")
plot(p, layout=layout)
g.vs["label"][1] = "test1"
essentially boils down to this:
labels = g.vs["label"]
labels[1] = "test1"
Now, g.vs["label"]
extracts the label
attribute of all the vertices, constructs a Python list, fills the attributes into the list and then returns the list to you. If you run type(g.vs["label"])
, you can see that labels
is an ordinary Python list. Since it is not a view into the internal data structure, any modifications that you make to the list will not be reflected in the graph itself.
On the other hand, g.vs[1]["label"] = "test1"
will do something like this:
vertex = g.vs[1]
vertex["label"] = "test1"
and this will work because g.vs[1]
is a Vertex
object (you can check it with type(g.vs[1])
, and using the Vertex
object as a dictionary will update the underlying attributes.
Footnote: in theory, g.vs["label"]
could return some kind of a proxy object that represents the "label"
attribute of each vertex and that writes any changes back to the underlying graph. However, it has not been implemented this way in earlier versions of the igraph Python interface and we cannot change it now without potentially breaking code of people who rely on the fact that g.vs["label"]
returns a copy.