We want to create the coordinates for 40 nodes using the sphere layout in igraph, which will then be used on a Pajek file.

## Creating the Coordinates

Load the igraph module and create an empty graph, then add the 40 nodes.

>>> from igraph import * # start an empty graph >>> g=Graph() # now add the nodes >>> g.add_vertices(40) # we can make sure it's all there >>> summary(g) # which returns IGRAPH U--- 40 0 --

Good, so we have a graph with 40 nodes, and no edges.

Now we can get the coordinates by using the “sphere” layout.

>>> coordinates=g.layout('sphere')

This returns the edges with 3 dimensions, and it looks a bit like this.

# these are just the first two... [-0.07200622924396105, 0.30781383453391725, -0.9487179487179487] [-0.44057805038786707, 0.022356017307457007, -0.8974358974358975] ...

Where each line represents a node and the items represent the x, y, and z coordinates.

Now we can change this to a list so we can extract each of them.

>>> coordList=list(coordinates)

We can now call each of them as we need them.

# I'll just print the first two for now. >>> for eachCoord in coordList[:2]: ... xCoord=eachCoord[0] ... yCoord=eachCoord[1] ... zCoord=eachCoord[2] ... print 'x=%f, y=%f, z=%f' % (xCoord,yCoord,zCoord) # which returns x=-0.072006, y=0.307814, z=-0.948718 x=-0.440578, y=0.022356, z=-0.897436

## Sphere layout in Python igraph

for some stupid reason I can’t get igraph to plot a graph that contains the z coordinates, therefore rendering the “spehere” layout a bit useless.

To solve this, I normally omit the z coordinates when I print out each line.

... print 'x=%d, y=%d' % (xCoord,yCoord) # so that it returns x=-0.072006, y=0.307814 x=-0.440578, y=0.022356

## Building the pajek file

I have a dictionary called `nDict’ with the ids and names for each node.

So i can now put that together with the list of coordinates to create the Vertices part of the file…

(I haven’t tested this yet, so I don’t know if it really works.)

# import igraph from igraph import * # open the pajek file for writing file_wPajek=open('location/of/file.txt','w') # create empty graph and add the nodes g=Graph() g.add_vertices(len(nDict)) # get the coordinates then turn to list coords=g.layout('sphere') l_coords=list(coords) # # we can now start building the Pajek file # write the Vertices section s_vStart='*Vertices %d\n'%len(nDict) file_wPajek.write(s_vStart) # now we can loop through the nDict and l_coords for i,j in zip(nDict,l_coords): nID=str(nDict[i]) nName=i xCoord='{:.3f}'.format(j[0]) yCoord='{:.3f}'.format(j[1]) theLine=' '.join([nID,nName,xCoord,yCoord,'\n']) file_wPajek.write(theLine) # close pajek file file_wPajek.close()

DONE!!