define vertex in python iGraph by x,y coordinates

I am trying to define a vertex in python using igprah lybrari. When i try to define it as a single integer there is not problem, but if i want to define a vertex as a (x-coordinate,y-coordinate) and add an edge between 2 verteces defined like this then i have an error:

TypeError: only numbers, vertex names or igraph.Vertex objects can be converted to vertex IDs

So i tried to create namedtupel

Coordinates = namedtuple('Coordinates','x,y')
firstVertex = Coordinates(1,2)
secondVertex = Coordinates(3,4)

and then i tried to use implicit conversion during adding the edge between those verteces but it doesnt work.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'Coordinates'

Is there any way how to define vertex with x,y coordinates and use it in igraph lybrary? Or is there a better way how to work with this kind of graphs, where i need to have my verteces defined with coordinates?? Thanks for your help.

Upvotes: 0

Views: 1995

Answers (1)

Tamás
Tamás

Reputation: 48061

igraph supports only integers or strings as vertex IDs. If you need to store any additional data related to a vertex, you must store it as vertex attributes. E.g.:

>>> g = Graph(3)
>>> g.vs[0]["coordinates"] = (1, 2)
>>> g.vs[1]["coordinates"] = (3, 4)

This will assign (1, 2) to the "coordinates" vertex attribute of vertex 0, and (3, 4) to the "coordinates" vertex attribute of vertex 1. Depending on what you want to achieve, it might be better to use two separate vertex attributes (x and y) because these are automatically used as layout coordinates when plotting the graph. E.g.:

>>> g.vs[0]["x"], g.vs[0]["y"] = 1, 2

There is also a shorthand notation for assigning the values of a vertex attribute for all the vertices:

>>> g.vs["x"] = [1, 2, 3]
>>> g.vs["y"] = [2, 4, 6]
>>> g.vs[0]["x"], g.vs[0]["y"]
(1, 2)
>>> g.vs[1]["x"], g.vs[1]["y"]
(2, 4)
>>> g.vs[2]["x"], g.vs[2]["y"]
(3, 6)

Upvotes: 1

Related Questions