# Spectral Graph Coordinates in Python

### Spectral coordinates are a natural way to draw a graph because they are determined by the properties of the graph, not arbitrary aesthetic choices. Read on to learn more.

Join the DZone community and get the full member experience.

Join For Freea graph doesn’t have any geometric structure unless we add it. the vertices don’t come with any position in space. the same graph can look very different when arranged different ways.

spectral coordinates are a natural way to draw a graph because they are determined by the properties of the graph, not arbitrary aesthetic choices. construct the
laplacian matrix
and let
*
x
*
and
*
y
*
be the eigenvectors associated with the second and third eigenvalues. (the smallest eigenvalue is always zero and has an eigenvector of all 1’s. the second and third eigenvalues and eigenvectors are the first to contain information about a graph.) the spectral coordinates of the
*
i
*
th node are the
*
i
*
th components of
*
x
*
and
*
y
*
.

we illustrate this with a graph constructed from a dodecahedron, a regular solid with twelve vertices. you can make a dodecahedron from a soccer ball by connecting the centers of all the white hexagons. here’s one i made from zometool pieces for a previous post :

although we’re thinking of this graph as sitting in three dimensions, the nodes being the corners of pentagons etc., the graph simply says which vertices are connected to each other. but, from this information, we can construct the graph laplacian and use it to assign plane coordinates to each point. and fortunately, this produces a nice picture:

here’s how that image was created using python’s networkx library.

```
import networkx as nx
import matplotlib.pyplot as plt
from scipy.linalg import eigh
# read in graph and compute the laplacian l ...
# laplacian matrices are real and symmetric, so we can use eigh,
# the variation on eig specialized for hermetian matrices.
w, v = eigh(l) # w = eigenvalues, v = eigenvectors
x = v[:,1]
y = v[:,2]
spectral_coordinates = {i : (x[i], y[i]) for i in range(n)}
g = nx.graph()
g.add_edges_from(graph)
nx.draw(g, pos=spectral_coordinates)
plt.show()
```

**
update
**
: after posting this i discovered that networkx has a method
```
draw_spectral
```

that will compute the spectral coordinates for you.

**
related
**
:

Published at DZone with permission of John Cook, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments