2012/01/08

[Misc] draw Petersen graph using python

A little taste of python networkx package. The first attempt is to draw a standard Petersen graph. The default layout looks not so perfect so I calculate the positions of the nodes when drawing the graph.

import networkx as nx
import matplotlib.pyplot as plt
import math

def calc_petersen_graph_pos():
    r = 2
    R = 2*r
    pos = {}
    delta = 2*math.pi/5
    curRadius = math.pi/2
    for i in xrange(5):
        pos[i] = (R*math.cos(curRadius), R*math.sin(curRadius))
        pos[i+5] = (r*math.cos(curRadius), r*math.sin(curRadius))
        curRadius += delta
    return pos

if __name__ == "__main__":
    G = nx.petersen_graph()
    plt.figure(figsize=(4,4)) # 400x400 pixel
    nx.draw(G, calc_petersen_graph_pos())
    plt.savefig("petersen.png")

沒有留言: