""" svg_graph.py Create an SVG version of a graph, e.g. Boston Chicago New York with python code like this. from svg_graph import SvgGraph SvgGraph()\ .line(30, 40, 80, 95) \ .line(80, 95, 200, 250) \ .dot(30, 40) \ .dot(80, 95) \ .dot(200, 250) \ .text("Boston", 35, 35) \ .text("Chicago", 85, 90) \ .text("New York", 205, 245) \ .write("svgtest") Jim Mahoney | MIT License | Dec 2010 """ svg_header = """ """ svg_footer = """ """ class SvgGraph(object): def __init__(self, scale=1.0): self.scale = scale self.xml = "" def write(self, filename="graph"): """ Write the given xml to a file; default name is 'graph.svg'. """ if not filename.endswith('.svg'): filename += '.svg' svg_file = open(filename, 'w') svg_file.write(self.header()) svg_file.write(self.xml) svg_file.write(self.footer()) svg_file.close() def window_coords(self, *xy): return map(lambda z: self.scale * z, xy) def header(self): return svg_header def footer(self): return svg_footer def line(self, x1, y1, x2, y2, color='grey', width=1): (x1, y1, x2, y2) = self.window_coords(x1, y1, x2, y2) self.xml += (""" \n""") % \ (x1, y1, x2, y2, color, width) return self def dot(self, x, y, color='red', radius=5): (x, y) = self.window_coords(x, y) self.xml += (""" \n""") % \ (x, y, radius, color) return self def text(self, string, x, y): (x, y) = self.window_coords(x, y) self.xml += (""" %s\n""") % \ (x, y, string) return self