"""
svg_graph.py
Create an SVG version of a graph, e.g.
"""
def demo():
g = SvgGraph(100)
vertices = (('A', 1.0, 1.0), ('B', 2.12, 1.0), ('C', 3.25, 1.0),
('D', 3.1, 2.5), ('E', 2.1, 2.5), ('F', 1.2, 2.5))
for a in vertices:
g.add_dot(a[1], a[2])
for b in vertices:
if a[0] < b[0]:
g.add_line(a[1], a[2], b[1], b[2])
g.make_svg('sample')
svg_header = """
"""
class SvgGraph(object):
def __init__(self, scale=1.0):
self.scale = scale
self.xml = ""
def add_line(self, *args):
self.xml += self.line(*args)
def add_dot(self, *args):
self.xml += self.dot(*args)
def add_text(self, *args):
self.xml += self.text(*args)
def make_svg(self, filename="graph"):
xml = self.header() + self.xml + self.footer()
self.write(xml, filename)
def write(self, xml, 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(xml)
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)
return (""" \n""") % \
(x1, y1, x2, y2, color, width)
def dot(self, x, y, color='red', radius=5):
(x, y) = self.window_coords(x, y)
return (""" \n""") % \
(x, y, radius, color)
def text(self, string, x, y):
(x, y) = self.window_coords(x, y)
return (""" %s\n""") % \
(x, y, string)