Browse Source

Pep8

pull/8/head
Florian Mounier 13 years ago
parent
commit
9b4b240eb3
  1. 23
      docs/conf.py
  2. 6
      setup.py
  3. 25
      svg/charts/bar.py
  4. 24
      svg/charts/css.py
  5. 120
      svg/charts/graph.py
  6. 15
      svg/charts/line.py
  7. 23
      svg/charts/pie.py
  8. 79
      svg/charts/plot.py
  9. 18
      svg/charts/schedule.py
  10. 50
      svg/charts/time_series.py
  11. 30
      svg/charts/util.py
  12. 15
      tests/samples.py
  13. 2
      tests/test_plot.py
  14. 2
      tests/test_samples.py
  15. 4
      tests/test_time_series.py

23
docs/conf.py

@ -3,7 +3,7 @@
# svg.charts documentation build configuration file, created by
# sphinx-quickstart on Tue May 11 10:51:55 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
# This file is execfile()d with the current directory set to its containing dir
#
# Note that not all possible configuration values are present in this
# autogenerated file.
@ -11,7 +11,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import os
import sys
# Get configuration information from the setup script
sys.path.insert(0, '..')
@ -23,11 +24,13 @@ del sys.path[0]
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
# Add any Sphinx extension module names here, as strings.
# They can be extensions coming with Sphinx (named 'sphinx.ext.*')
# or your custom ones.
extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@ -71,7 +74,7 @@ release = version
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# The reST default role (used for this markup: `text`) to use for all documents
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
@ -92,7 +95,7 @@ pygments_style = 'sphinx'
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
@ -166,7 +169,7 @@ html_static_path = ['_static']
htmlhelp_basename = 'svgchartsdoc'
# -- Options for LaTeX output --------------------------------------------------
# -- Options for LaTeX output -------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
@ -175,7 +178,7 @@ htmlhelp_basename = 'svgchartsdoc'
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
# (source start file, target name, title, author, documentclass [howto/manual])
latex_documents = [
('index', 'svgcharts.tex', u'svg.charts Documentation',
setup_params['author'], 'manual'),

6
setup.py

@ -6,10 +6,14 @@ from setuptools import find_packages
from distutils.cmd import Command
class DisabledTestCommand(Command):
user_options = []
def __init__(self, dist):
raise RuntimeError("test command not supported on svg.charts. Use setup.py nosetests instead")
raise RuntimeError(
"test command not supported on svg.charts."
" Use setup.py nosetests instead")
_this_dir = os.path.dirname(__file__)
_readme = os.path.join(_this_dir, 'readme.txt')

25
svg/charts/bar.py

@ -5,6 +5,7 @@ from svg.charts.graph import Graph
__all__ = ('VerticalBar', 'HorizontalBar')
class Bar(Graph):
"A superclass for bar-style graphs. Do not instantiate directly."
@ -27,7 +28,8 @@ class Bar(Graph):
# adapted from Plot
def get_data_values(self):
min_value, max_value, scale_division = self.data_range()
result = tuple(float_range(min_value, max_value + scale_division, scale_division))
result = tuple(
float_range(min_value, max_value + scale_division, scale_division))
if self.scale_integers:
result = map(int, result)
return result
@ -60,7 +62,8 @@ class Bar(Graph):
# return max(map(lambda set: max(set['data']), self.data))
def data_min(self):
if not getattr(self, 'min_scale_value') is None: return self.min_scale_value
if not getattr(self, 'min_scale_value') is None:
return self.min_scale_value
min_value = min(chain(*map(lambda set: set['data'], self.data)))
min_value = min(min_value, 0)
return min_value
@ -74,6 +77,7 @@ class Bar(Graph):
bar_gap = int(self.bar_gap) * bar_gap
return bar_gap
def float_range(start=0, stop=None, step=1):
"Much like the built-in function range, but accepts floats"
while start < stop:
@ -147,8 +151,10 @@ class VerticalBar(Bar):
def draw_data(self):
min_value = self.data_min()
unit_size = (float(self.graph_height) - self.font_size*2*self.top_font)
unit_size /= (max(self.get_data_values()) - min(self.get_data_values()))
unit_size = (
float(self.graph_height) - self.font_size * 2 * self.top_font)
unit_size /= (
max(self.get_data_values()) - min(self.get_data_values()))
bar_gap = self.get_bar_gap(self.get_field_width())
@ -187,7 +193,9 @@ class VerticalBar(Bar):
'class': 'fill%s' % (dataset_count + 1),
})
self.make_datapoint_text(left + bar_width/2.0, top-6, value)
self.make_datapoint_text(
left + bar_width / 2.0, top - 6, value)
class HorizontalBar(Bar):
rotate_y_labels = True
@ -195,7 +203,6 @@ class HorizontalBar(Bar):
show_y_guidelines = False
right_align = right_font = True
def get_x_labels(self):
return self.get_data_labels()
@ -224,7 +231,8 @@ class HorizontalBar(Bar):
for dataset_count, dataset in enumerate(self.data):
value = dataset['data'][field_count]
top = self.graph_height - (self.get_field_height() * (field_count+1))
top = self.graph_height - (
self.get_field_height() * (field_count + 1))
if self.stack == 'side':
top += (bar_height * dataset_count)
# cases (assume 0 = +ve):
@ -244,5 +252,6 @@ class HorizontalBar(Bar):
'class': 'fill%s' % (dataset_count + 1),
})
self.make_datapoint_text(left+length+5, top+y_mod, value,
self.make_datapoint_text(
left + length + 5, top + y_mod, value,
"text-anchor: start; ")

24
svg/charts/css.py

@ -29,14 +29,17 @@ properties = {
'stop-opacity': '{num}|inherit',
# Interactivity Properties
'pointer-events': 'visiblePainted|visibleFill|visibleStroke|visible|painted|fill|stroke|all|none|inherit',
'pointer-events': ('visiblePainted|visibleFill|visibleStroke'
'|visible|painted|fill|stroke|all|none|inherit'),
# Color and Pointing Properties
'color-interpolation': 'auto|sRGB|linearRGB|inherit',
'color-interpolation-filters': 'auto|sRGB|linearRGB|inherit',
'color-rendering': 'auto|optimizeSpeed|optimizeQuality|inherit',
'shape-rendering': 'auto|optimizeSpeed|crispEdges|geometricPrecision|inherit',
'text-rendering': 'auto|optimizeSpeed|optimizeLegibility|geometricPrecision|inherit',
'shape-rendering': ('auto|optimizeSpeed|crispEdges|'
'geometricPrecision|inherit'),
'text-rendering': ('auto|optimizeSpeed|optimizeLegibility'
'|geometricPrecision|inherit'),
'fill': '{paint}',
'fill-opacity': '{num}|inherit',
'fill-rule': 'nonzero|evenodd|inherit',
@ -45,7 +48,8 @@ properties = {
'marker-end': 'none|inherit|{uri}',
'marker-mid': 'none|inherit|{uri}',
'marker-start': 'none|inherit|{uri}',
'shape-rendering': 'auto|optimizeSpeed|crispEdges|geometricPrecision|inherit',
'shape-rendering': ('auto|optimizeSpeed|crispEdges|'
'geometricPrecision|inherit'),
'stroke': '{paint}',
'stroke-dasharray': 'none|{dasharray}|inherit',
'stroke-dashoffset': '{length}|inherit',
@ -54,12 +58,18 @@ properties = {
'stroke-miterlimit': '{number-ge-one}|inherit',
'stroke-opacity': '{num}|inherit',
'stroke-width': '{length}|inherit',
'text-rendering': 'auto|optimizeSpeed|optimizeLegibility|geometricPrecision|inherit',
'text-rendering': ('auto|optimizeSpeed|optimizeLegibility'
'|geometricPrecision|inherit'),
# Text Properties
'alignment-baseline': 'auto|baseline|before-edge|text-before-edge|middle|central|after-edge|text-after-edge|ideographic|alphabetic|hanging|mathematical|inherit',
'alignment-baseline': ('auto|baseline|before-edge|text-before-edge|'
'middle|central|after-edge|text-after-edge|'
'ideographic|alphabetic|hanging|mathematical'
'|inherit'),
'baseline-shift': 'baseline|sub|super|{percentage}|{length}|inherit',
'dominant-baseline': 'auto|use-script|no-change|reset-size|ideographic|alphabetic|hanging||mathematical|central|middle|text-after-edge|text-before-edge|inherit',
'dominant-baseline': ('auto|use-script|no-change|reset-size|ideographic|'
'alphabetic|hanging||mathematical|central|middle|'
'text-after-edge|text-before-edge|inherit'),
'glyph-orientation-horizontal': '{angle}|inherit',
'glyph-orientation-vertical': 'auto|{angle}|inherit',
'kerning': 'auto|{length}|inherit',

120
svg/charts/graph.py

@ -1,5 +1,5 @@
#!python
# -*- coding: UTF-8 -*-
# -*- coding: utf-8 -*-
"""
svg.charts.graph
@ -14,6 +14,7 @@ import functools
import cssutils
from lxml import etree
from xml import xpath
from svg.charts import css # causes the SVG profile to be loaded
@ -22,12 +23,15 @@ try:
except ImportError:
zlib = None
def sort_multiple(arrays):
"sort multiple lists (of equal size) using the first list for the sort keys"
"sort multiple lists (of equal size) "
"using the first list for the sort keys"
tuples = zip(*arrays)
tuples.sort()
return zip(*tuples)
class Graph(object):
"""
Base object for generating SVG Graphs
@ -67,14 +71,16 @@ class Graph(object):
show_x_title = False
x_title = 'X Field names'
show_y_title = False
y_title_text_direction= 'bt' # 'bt' for bottom to top; 'tb' for top to bottom
# 'bt' for bottom to top; 'tb' for top to bottom
y_title_text_direction = 'bt'
y_title = 'Y Scale'
show_graph_title = False
graph_title = 'Graph Title'
show_graph_subtitle = False
graph_subtitle = 'Graph Subtitle'
key = True
key_position= 'right' # 'bottom' or 'right',
# 'bottom' or 'right',
key_position = 'right'
font_size = 12
title_font_size = 16
@ -124,12 +130,15 @@ class Graph(object):
try:
assert(isinstance(conf['data'], (tuple, list)))
except TypeError, e:
raise TypeError, "conf should be dictionary with 'data' and other items"
raise TypeError(
"conf should be dictionary with 'data' and other items")
except AssertionError:
if not hasattr(conf['data'], '__iter__'):
raise TypeError, "conf['data'] should be tuple or list or iterable"
raise TypeError(
"conf['data'] should be tuple or list or iterable")
def process_data(self, data): pass
def process_data(self, data):
pass
def clear_data(self):
"""
@ -148,9 +157,11 @@ class Graph(object):
Raises ValueError when no data set has
been added to the graph object.
"""
if not self.data: raise ValueError("No data available")
if not self.data:
raise ValueError("No data available")
if hasattr(self, 'calculations'): self.calculations()
if hasattr(self, 'calculations'):
self.calculations()
self.start_svg()
self.calculate_graph_dimensions()
@ -166,9 +177,12 @@ class Graph(object):
def _burn_compressed(self):
if self.compress and not zlib:
self.root.addprevious(etree.Comment('Python zlib not available for SVGZ'))
self.root.addprevious(
etree.Comment('Python zlib not available for SVGZ'))
data = etree.tostring(self.root, pretty_print=True, xml_declaration=True, encoding='utf-8')
data = etree.tostring(
self.root, pretty_print=True,
xml_declaration=True, encoding='utf-8')
if self.compress and zlib:
data = zlib.compress(data)
@ -189,10 +203,14 @@ class Graph(object):
else:
label_lengths = map(len, self.get_y_labels())
max_y_label_len = max(label_lengths)
max_y_label_height_px = 0.6 * max_y_label_len * self.y_label_font_size
if self.show_y_labels: bl += max_y_label_height_px
if self.stagger_y_labels: bl += max_y_label_height_px + 10
if self.show_y_title: bl += self.y_title_font_size + 5
max_y_label_height_px = (0.6 * max_y_label_len *
self.y_label_font_size)
if self.show_y_labels:
bl += max_y_label_height_px
if self.stagger_y_labels:
bl += max_y_label_height_px + 10
if self.show_y_title:
bl += self.y_title_font_size + 5
self.border_left = bl
def max_y_label_width_px(self):
@ -222,9 +240,11 @@ class Graph(object):
border_top.
"""
self.border_top = 5
if self.show_graph_title: self.border_top += self.title_font_size
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle: self.border_top += self.subtitle_font_size
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size
def add_popup(self, x, y, label):
"""
@ -245,7 +265,8 @@ class Graph(object):
})
# add the circle element to the foreground
visibility = "document.getElementById('%s').setAttribute('visibility', %%s)" % id
visibility = ("document.getElementById('%s')."
"setAttribute('visibility', %%s)" % id)
t = etree.SubElement(self.foreground, 'circle', {
'cx': str(x),
'cy': str(y),
@ -271,8 +292,10 @@ class Graph(object):
max_x_label_len = reduce(max, label_lengths)
max_x_label_height_px *= 0.6 * max_x_label_len
bb += max_x_label_height_px
if self.stagger_x_labels: bb += max_x_label_height_px + 10
if self.show_x_title: bb += self.x_title_font_size + 5
if self.stagger_x_labels:
bb += max_x_label_height_px + 10
if self.show_x_title:
bb += self.x_title_font_size + 5
self.border_bottom = bb
def draw_graph(self):
@ -336,7 +359,8 @@ class Graph(object):
'y': str(y),
'class': 'dataPointLabel'})
e.text = str(value)
if style: e.set('style', style)
if style:
e.set('style', style)
def draw_x_labels(self):
"Draw the X axis labels"
@ -388,13 +412,14 @@ class Graph(object):
return 0
def get_field_width(self):
return float(self.graph_width - self.font_size*2*self.right_font) / \
(len(self.get_x_labels()) - self.right_align)
return (float(
self.graph_width - self.font_size * 2 * self.right_font) /
(len(self.get_x_labels()) - self.right_align))
field_width = get_field_width
def get_field_height(self):
return float(self.graph_height - self.font_size*2*self.top_font) / \
(len(self.get_y_labels()) - self.top_align)
return (float(self.graph_height - self.font_size * 2 * self.top_font) /
(len(self.get_y_labels()) - self.top_align))
field_height = get_field_height
def draw_y_labels(self):
@ -414,7 +439,8 @@ class Graph(object):
def get_y_offset(self):
result = self.graph_height + self.y_label_offset(self.field_height())
if not self.rotate_y_labels: result += self.font_size/1.2
if not self.rotate_y_labels:
result += self.font_size / 1.2
return result
y_offset = property(get_y_offset)
@ -449,7 +475,8 @@ class Graph(object):
def draw_x_guidelines(self, label_height, count):
"Draw the X-axis guidelines"
if not self.show_x_guidelines: return
if not self.show_x_guidelines:
return
# skip the first one
for count in range(1, count):
start = label_height * count
@ -460,7 +487,8 @@ class Graph(object):
def draw_y_guidelines(self, label_height, count):
"Draw the Y-axis guidelines"
if not self.show_y_guidelines: return
if not self.show_y_guidelines:
return
for count in range(1, count):
start = self.graph_height - label_height * count
stop = self.graph_width
@ -470,10 +498,14 @@ class Graph(object):
def draw_titles(self):
"Draws the graph title and subtitle"
if self.show_graph_title: self.draw_graph_title()
if self.show_graph_subtitle: self.draw_graph_subtitle()
if self.show_x_title: self.draw_x_title()
if self.show_y_title: self.draw_y_title()
if self.show_graph_title:
self.draw_graph_title()
if self.show_graph_subtitle:
self.draw_graph_subtitle()
if self.show_x_title:
self.draw_x_title()
if self.show_y_title:
self.draw_y_title()
def draw_graph_title(self):
text = etree.SubElement(self.root, 'text', {
@ -483,7 +515,8 @@ class Graph(object):
text.text = self.graph_title
def draw_graph_subtitle(self):
y_subtitle_options = [subtitle_font_size, title_font_size+10]
y_subtitle_options = [self.subtitle_font_size,
self.title_font_size + 10]
y_subtitle = y_subtitle_options[self.show_graph_title]
text = etree.SubElement(self.root, 'text', {
'x': str(self.width / 2),
@ -496,7 +529,8 @@ class Graph(object):
y = self.graph_height + self.border_top + self.x_title_font_size
if self.show_x_labels:
y_size = self.x_label_font_size + 5
if self.stagger_x_labels: y_size*=2
if self.stagger_x_labels:
y_size *= 2
y += y_size
x = self.width / 2
@ -560,16 +594,16 @@ class Graph(object):
x_offset = self.border_left + 20
y_offset = self.border_top + self.graph_height + 5
if self.show_x_labels:
max_x_label_height_px = x_label_font_size
max_x_label_height_px = self.x_label_font_size
if self.rotate_x_labels:
longest_label_length = max(map(len, self.get_x_labels()))
# note: I think 0.6 is the ratio of width to height of characters
# I think 0.6 is the ratio of width to height of characters
max_x_label_height_px *= longest_label_length * 0.6
y_offset += max_x_label_height_px
if self.stagger_x_labels:
y_offset += max_x_label_height_px + 5
if self.show_x_title:
y_offset += x_title_font_size + 5
y_offset += self.x_title_font_size + 5
return x_offset, y_offset
def render_inline_styles(self):
@ -616,7 +650,8 @@ class Graph(object):
'width': str(self.width),
'height': str(self.height),
'viewBox': '0 0 %s %s' % (self.width, self.height),
'{http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/}scriptImplementation': 'Adobe',
'{http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/}'
'scriptImplementation': 'Adobe',
}, nsmap=NSMAP)
if hasattr(self, 'style_sheet_href'):
pi = etree.ProcessingInstruction(
@ -638,10 +673,11 @@ class Graph(object):
self.add_defs(defs)
if not hasattr(self, 'style_sheet_href') and not self.css_inline:
self.root.append(etree.Comment(' include default stylesheet if none specified '))
self.root.append(etree.Comment(
' include default stylesheet if none specified '))
style = etree.SubElement(defs, 'style', type='text/css')
# TODO: the text was previously escaped in a CDATA declaration... how
# to do that with etree?
# TODO: the text was previously escaped in a CDATA declaration...
# how to do that with etree?
style.text = self.get_stylesheet().cssText
self.root.append(etree.Comment('SVG Background'))
@ -679,11 +715,13 @@ class Graph(object):
def get_stylesheet(self):
cssutils.log.setLevel(30) # disable INFO log messages
def merge_sheets(s1, s2):
map(s1.add, s2)
return s1
return reduce(merge_sheets, self.get_stylesheet_resources())
class class_dict(object):
"Emulates a dictionary, but retrieves class attributes"
def __init__(self, obj):

15
svg/charts/line.py

@ -8,6 +8,7 @@ from lxml import etree
from util import flatten, float_range
from svg.charts.graph import Graph
class Line(Graph):
"""Line Graph"""
@ -42,12 +43,13 @@ class Line(Graph):
data = self.get_cumulative_data()
return min(flatten(data))
def get_cumulative_data():
def get_cumulative_data(self):
"""Get the data as it will be charted. The first set will be
the actual first data set. The second will be the sum of the
first and the second, etc."""
sets = map(itemgetter('data'), self.data)
if not sets: return
if not sets:
return
sum = sets.pop(0)
yield sum
while sets:
@ -83,8 +85,10 @@ class Line(Graph):
return map(str, self.get_y_label_values())
def calc_coords(self, field, value, width=None, height=None):
if width is None: width = self.field_width
if height is None: height = self.field_height
if width is None:
width = self.field_width
if height is None:
height = self.field_height
coords = dict(
x=width * field,
y=self.graph_height - value * height,
@ -110,7 +114,8 @@ class Line(Graph):
for line_n, data in reversed(list(enumerate(self.data, 1))):
apath = ''
if not self.stacked: cum_sum = [-min_value]*len(self.fields)
if not self.stacked:
cum_sum = [-min_value] * len(self.fields)
cum_sum = map(add, cum_sum, data['data'])
get_coords = lambda (i, val): self.calc_coords(i,

23
svg/charts/pie.py

@ -3,14 +3,18 @@ import itertools
from lxml import etree
from svg.charts.graph import Graph
def robust_add(a, b):
"Add numbers a and b, treating None as 0"
if a is None: a = 0
if b is None: b = 0
if a is None:
a = 0
if b is None:
b = 0
return a + b
RADIANS = math.pi / 180
class Pie(Graph):
"""
A presentation-quality SVG pie graph
@ -49,7 +53,9 @@ class Pie(Graph):
show_data_labels = False
"If true, display the actual field values in the data labels"
show_actual_values = False
"If true, display the percentage value of each pie wedge in the data labels"
("If true, display the percentage value of"
"each pie wedge in the data labels")
show_percent = True
"If true, display the labels in the key"
@ -141,11 +147,12 @@ class Pie(Graph):
def keys(self):
total = sum(self.data)
percent_scale = 100.0 / total
def key(field, value):
result = [field]
result.append('[%s]' % value)
if self.show_key_percent:
percent = str(round((v/total*100))) + '%'
percent = str(round((value / total * 100))) + '%'
result.append(percent)
return ' '.join(result)
return map(key, self.fields, self.data)
@ -171,7 +178,8 @@ class Pie(Graph):
self.graph.set('transform', transform)
wedge_text_pad = 5
wedge_text_pad = 20 * int(self.show_percent) * int(self.show_data_labels)
wedge_text_pad = (20 * int(self.show_percent) *
int(self.show_data_labels))
total = sum(self.data)
max_value = max(self.data)
@ -260,7 +268,8 @@ class Pie(Graph):
tx = radius + (msr * radius)
ty = radius - (mcr * radius)
if self.expanded or (self.expand_greatest and value == max_value):
if self.expanded or (
self.expand_greatest and value == max_value):
tx += (msr * self.expand_gap)
ty -= (mcr * self.expand_gap)
@ -271,7 +280,7 @@ class Pie(Graph):
'x': str(tx),
'y': str(ty),
'class': 'dataPointLabel',
'style':'stroke: #fff; stroke-width: 2;',
'style': 'stroke: #fff; stroke-width: 2;'
}
)
label_node.text = label

79
svg/charts/plot.py

@ -10,15 +10,18 @@ from svg.charts.graph import Graph
from .util import float_range
def get_pairs(i):
i = iter(i)
while True: yield i.next(), i.next()
while True:
yield i.next(), i.next()
# I'm not sure how this is more beautiful than ugly.
if sys.version >= '3':
def apply(func):
return func()
class Plot(Graph):
"""=== For creating SVG plots of scalar data
@ -105,7 +108,6 @@ class Plot(Graph):
top_align = right_align = top_font = right_font = 1
"""Determines the scaling for the Y axis divisions.
graph.scale_y_divisions = 0.5
@ -143,17 +145,22 @@ class Plot(Graph):
graph.scale_x_divisions = 2
would cause the graph to attempt to generate labels stepped by 2; EG:
would cause the graph to attempt
to generate labels stepped by 2; EG:
0,2,4,6,8..."""
def fget(self):
return getattr(self, '_scale_x_divisions', None)
def fset(self, val):
self._scale_x_divisions = val
return property(**locals())
def validate_data(self, data):
if len(data['data']) % 2 != 0:
raise ValueError("Expecting x,y pairs for data points for %s." % self.__class__.__name__)
raise ValueError(
"Expecting x,y pairs for data points for %s." %
self.__class__.__name__)
def process_data(self, data):
pairs = list(get_pairs(data['data']))
@ -162,28 +169,34 @@ class Plot(Graph):
def calculate_left_margin(self):
super(Plot, self).calculate_left_margin()
label_left = len(str(self.get_x_labels()[0])) / 2 * self.font_size * 0.6
label_left = len(str(
self.get_x_labels()[0])) / 2 * self.font_size * 0.6
self.border_left = max(label_left, self.border_left)
def calculate_right_margin(self):
super(Plot, self).calculate_right_margin()
label_right = len(str(self.get_x_labels()[-1])) / 2 * self.font_size * 0.6
label_right = len(str(
self.get_x_labels()[-1])) / 2 * self.font_size * 0.6
self.border_right = max(label_right, self.border_right)
def data_max(self, axis):
data_index = getattr(self, '%s_data_index' % axis)
max_value = max(chain(*map(lambda set: set['data'][data_index], self.data)))
max_value = max(chain(
*map(lambda set: set['data'][data_index], self.data)))
# above is same as
#max_value = max(map(lambda set: max(set['data'][data_index]), self.data))
#max_value = max(map(lambda set:
# max(set['data'][data_index]), self.data))
spec_max = getattr(self, 'max_%s_value' % axis)
# Python 3 doesn't allow comparing None to int, so use -∞
if spec_max is None: spec_max = float('-Inf')
if spec_max is None:
spec_max = float('-Inf')
max_value = max(max_value, spec_max)
return max_value
def data_min(self, axis):
data_index = getattr(self, '%s_data_index' % axis)
min_value = min(chain(*map(lambda set: set['data'][data_index], self.data)))
min_value = min(chain(
*map(lambda set: set['data'][data_index], self.data)))
spec_min = getattr(self, 'min_%s_value' % axis)
if spec_min is not None:
min_value = min(min_value, spec_min)
@ -191,6 +204,7 @@ class Plot(Graph):
x_data_index = 0
y_data_index = 1
def data_range(self, axis):
side = {'x': 'right', 'y': 'top'}[axis]
@ -201,25 +215,33 @@ class Plot(Graph):
side_pad = range / 20.0 or 10
scale_range = (max_value + side_pad) - min_value
scale_division = getattr(self, 'scale_%s_divisions' % axis) or (scale_range / 10.0)
scale_division = getattr(
self, 'scale_%s_divisions' % axis) or (scale_range / 10.0)
if getattr(self, 'scale_%s_integers' % axis):
scale_division = round(scale_division) or 1
return min_value, max_value, scale_division
def x_range(self): return self.data_range('x')
def y_range(self): return self.data_range('y')
def x_range(self):
return self.data_range('x')
def y_range(self):
return self.data_range('y')
def get_data_values(self, axis):
min_value, max_value, scale_division = self.data_range(axis)
return tuple(float_range(*self.data_range(axis)))
def get_x_values(self): return self.get_data_values('x')
def get_y_values(self): return self.get_data_values('y')
def get_x_values(self):
return self.get_data_values('x')
def get_y_values(self):
return self.get_data_values('y')
def get_x_labels(self):
return map(str, self.get_x_values())
def get_y_labels(self):
return map(str, self.get_y_values())
@ -235,12 +257,15 @@ class Plot(Graph):
graph_size = getattr(self, 'graph_%s' % size)
side_font = getattr(self, '%s_font' % side)
side_align = getattr(self, '%s_align' % side)
result = (float(graph_size) - self.font_size*2*side_font) / \
(len(values) + dx - side_align)
result = ((float(graph_size) - self.font_size * 2 * side_font) /
(len(values) + dx - side_align))
return result
def field_width(self): return self.field_size('x')
def field_height(self): return self.field_size('y')
def field_width(self):
return self.field_size('x')
def field_height(self):
return self.field_size('y')
def draw_data(self):
self.load_transform_parameters()
@ -255,7 +280,8 @@ class Plot(Graph):
if self.area_fill:
graph_height = self.graph_height
path = etree.SubElement(self.graph, 'path', {
'd': 'M%(x_start)f %(graph_height)f %(lpath)s V%(graph_height)f Z' % vars(),
'd': 'M%(x_start)f %(graph_height)f'
' %(lpath)s V%(graph_height)f Z' % vars(),
'class': 'fill%(line)d' % vars()})
if self.draw_lines_between_points:
path = etree.SubElement(self.graph, 'path', {
@ -293,10 +319,10 @@ class Plot(Graph):
"Cache the parameters necessary to transform x & y coordinates"
x_min, x_max, x_div = self.x_range()
y_min, y_max, y_div = self.y_range()
x_step = (float(self.graph_width) - self.font_size*2) / \
(x_max - x_min)
y_step = (float(self.graph_height) - self.font_size*2) / \
(y_max - y_min)
x_step = ((float(self.graph_width) - self.font_size * 2) /
(x_max - x_min))
y_step = ((float(self.graph_height) - self.font_size * 2) /
(y_max - y_min))
self.__transform_parameters = dict(vars())
del self.__transform_parameters['self']
@ -319,8 +345,9 @@ class Plot(Graph):
return x, y
def draw_data_points(self, line, data_points, graph_points):
if not self.show_data_points \
and not self.show_data_values: return
if not self.show_data_points and not self.show_data_values:
return
for ((dx, dy), (gx, gy)) in izip(data_points, graph_points):
if self.show_data_points:
etree.SubElement(self.graph, 'circle', {

18
svg/charts/schedule.py

@ -10,6 +10,7 @@ from util import grouper, date_range, divide_timedelta_float, TimeScale
__all__ = ('Schedule')
class Schedule(Graph):
"""
# === For creating SVG plots of scalar temporal data
@ -138,11 +139,12 @@ class Schedule(Graph):
:title => 'Plays'
)
Note that the data must be in time,value pairs, and that the date format
Note that the data must be in time,value pairs,
and that the date format
may be any date that is parseable by ParseDate.
Also note that, in this example, we're mixing scales; the data from d1
will probably not be discernable if both data sets are plotted on the same
graph, since d1 is too granular.
will probably not be discernable if both data sets are
plotted on the same graph, since d1 is too granular.
"""
# The ruby version does something different here, throwing out
# any previously added data.
@ -244,7 +246,6 @@ class Schedule(Graph):
'class': 'fill%s' % (count + 1),
})
def _x_range(self):
# ruby version uses teh last data supplied
last = -1
@ -257,7 +258,8 @@ class Schedule(Graph):
all_dates.append(self.min_x_value)
min_value = min(all_dates)
range = max_value - min_value
right_pad = divide_timedelta_float(range, 20.0) or relativedelta(days=10)
right_pad = divide_timedelta_float(
range, 20.0) or relativedelta(days=10)
scale_range = (max_value + right_pad) - min_value
#scale_division = self.scale_x_divisions or (scale_range / 10.0)
@ -277,7 +279,9 @@ class Schedule(Graph):
pattern = re.compile('(\d+) ?(\w+)')
m = pattern.match(self.timescale_divisions)
if not m:
raise ValueError, "Invalid timescale_divisions: %s" % self.timescale_divisions
raise (ValueError,
"Invalid timescale_divisions: %s" %
self.timescale_divisions)
magnitude = int(m.group(1))
units = m.group(2)
@ -305,5 +309,5 @@ class Schedule(Graph):
mapping = reverse_mapping(mapping)
mapping = flatten_mapping(mapping)
if not unit_string in mapping:
raise ValueError, "%s doesn't match any supported time/date unit"
raise ValueError("%s doesn't match any supported time/date unit")
return mapping[unit_string]

50
svg/charts/time_series.py

@ -10,6 +10,7 @@ import datetime
fromtimestamp = datetime.datetime.fromtimestamp
from .util import float_range
class Plot(svg.charts.plot.Plot):
"""=== For creating SVG plots of scalar temporal data
@ -19,9 +20,11 @@ class Plot(svg.charts.plot.Plot):
# Data sets are x,y pairs
data1 = ["6/17/72", 11, "1/11/72", 7, "4/13/04 17:31", 11,
"9/11/01", 9, "9/1/85", 2, "9/1/88", 1, "1/15/95", 13]
"9/11/01", 9, "9/1/85", 2,
"9/1/88", 1, "1/15/95", 13]
data2 = ["8/1/73", 18, "3/1/77", 15, "10/1/98", 4,
"5/1/02", 14, "3/1/95", 6, "8/1/91", 12, "12/1/87", 6,
"5/1/02", 14, "3/1/95", 6,
"8/1/91", 12, "12/1/87", 6,
"5/1/84", 17, "10/1/80", 12]
graph = SVG::Graph::TimeSeries.new({
@ -80,9 +83,10 @@ class Plot(svg.charts.plot.Plot):
["01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
# ("14:20",6)
Note that multiple data sets within the same chart can differ in length,
and that the data in the datasets needn't be in order; they will be ordered
by the plot along the X-axis.
Note that multiple data sets within
the same chart can differ in length,
and that the data in the datasets needn't be in order;
they will be ordered by the plot along the X-axis.
The dates must be parseable by ParseDate, but otherwise can be
any order of magnitude (seconds within the hour, or years)
@ -104,12 +108,14 @@ class Plot(svg.charts.plot.Plot):
This software is available under the Ruby license[LICENSE.txt]
"""
popup_format = x_label_format = '%Y-%m-%d %H:%M:%S'
__doc_popup_format_ = "The formatting usped for the popups. See x_label_format"
__doc_x_label_format_ = "The format string used to format the X axis labels. See strftime."
__doc_popup_format_ = ("The formatting usped for the popups."
" See x_label_format")
__doc_x_label_format_ = ("The format string used to format "
"the X axis labels. See strftime.")
timescale_divisions = None
__doc_timescale_divisions_ = """Use this to set the spacing between dates on the axis. The value
must be of the form
__doc_timescale_divisions_ = """Use this to set the spacing
between dates on the axis. The value must be of the form
"\d+ ?(days|weeks|months|years|hours|minutes|seconds)?"
EG:
@ -122,8 +128,8 @@ class Plot(svg.charts.plot.Plot):
def add_data(self, data):
"""Add data to the plot.
d1 = ["12:30", 2] # A data set with 1 point: ("12:30",2)
d2 = ["01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
# ("14:20",6)
d2 = ["01:00",2, "14:20",6] # A data set with 2 points:
# ("01:00",2) and ("14:20",6)
graph.add_data(
:data => d1,
:title => 'One'
@ -133,7 +139,8 @@ class Plot(svg.charts.plot.Plot):
:title => 'Two'
)
Note that the data must be in time,value pairs, and that the date format
Note that the data must be in time,value pairs,
and that the date format
may be any date that is parseable by ParseDate."""
super(Plot, self).add_data(data)
@ -143,8 +150,10 @@ class Plot(svg.charts.plot.Plot):
data['data'][0] = map(self.parse_date, data['data'][0])
_min_x_value = svg.charts.plot.Plot.min_x_value
def get_min_x_value(self):
return self._min_x_value
def set_min_x_value(self, date):
self._min_x_value = self.parse_date(date)
min_x_value = property(get_min_x_value, set_min_x_value)
@ -153,21 +162,28 @@ class Plot(svg.charts.plot.Plot):
return fromtimestamp(x).strftime(self.popup_format)
def get_x_labels(self):
return map(lambda t: fromtimestamp(t).strftime(self.x_label_format), self.get_x_values())
return map(lambda t: fromtimestamp(t).strftime(self.x_label_format),
self.get_x_values())
def get_x_values(self):
result = self.get_x_timescale_division_values()
if result: return result
if result:
return result
return tuple(float_range(*self.x_range()))
def get_x_timescale_division_values(self):
if not self.timescale_divisions: return
if not self.timescale_divisions:
return
min, max, scale_division = self.x_range()
m = re.match('(?P<amount>\d+) ?(?P<division_units>days|weeks|months|years|hours|minutes|seconds)?', self.timescale_divisions)
m = re.match(
'(?P<amount>\d+) ?(?P<division_units>'
'days|weeks|months|years|hours|minutes|seconds)?',
self.timescale_divisions)
# copy amount and division_units into the local namespace
division_units = m.groupdict()['division_units'] or 'days'
amount = int(m.groupdict()['amount'])
if not amount: return
if not amount:
return
delta = relativedelta(**{division_units: amount})
result = tuple(self.get_time_range(min, max, delta))
return result

30
svg/charts/util.py

@ -2,14 +2,18 @@
import itertools
import datetime
# from itertools recipes (python documentation)
def grouper(n, iterable, padvalue=None):
"""
>>> tuple(grouper(3, 'abcdefg', 'x'))
(('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x'))
"""
return itertools.izip(*[itertools.chain(iterable, itertools.repeat(padvalue, n-1))]*n)
return itertools.izip(
*[itertools.chain(iterable,
itertools.repeat(padvalue, n - 1))] * n)
def reverse_mapping(mapping):
"""
@ -21,6 +25,7 @@ def reverse_mapping(mapping):
keys, values = zip(*mapping.items())
return dict(zip(values, keys))
def flatten_mapping(mapping):
"""
For every key that has an __iter__ method, assign the values
@ -30,6 +35,7 @@ def flatten_mapping(mapping):
"""
return dict(flatten_items(mapping.items()))
def flatten_items(items):
for keys, value in items:
if hasattr(keys, '__iter__'):
@ -38,6 +44,7 @@ def flatten_items(items):
else:
yield (keys, value)
def float_range(start=0, stop=None, step=1):
"""
Much like the built-in function range, but accepts floats
@ -49,6 +56,7 @@ def float_range(start=0, stop=None, step=1):
yield start
start += step
def date_range(start=None, stop=None, step=None):
"""
Much like the built-in function range, but works with dates
@ -60,12 +68,15 @@ def date_range(start=None, stop=None, step=None):
>>> datetime.datetime(2005,12,25) in my_range
False
"""
if step is None: step = datetime.timedelta(days=1)
if start is None: start = datetime.datetime.now()
if step is None:
step = datetime.timedelta(days=1)
if start is None:
start = datetime.datetime.now()
while start < stop:
yield start
start += step
# copied from jaraco.datetools
def divide_timedelta_float(td, divisor):
"""
@ -83,11 +94,13 @@ def divide_timedelta_float(td, divisor):
dsm = map(lambda elem: elem / divisor, dsm)
return datetime.timedelta(*dsm)
def get_timedelta_total_microseconds(td):
seconds = td.days * 86400 + td.seconds
microseconds = td.microseconds + seconds * (10 ** 6)
return microseconds
def divide_timedelta(td1, td2):
"""
Get the ratio of two timedeltas
@ -101,6 +114,7 @@ def divide_timedelta(td1, td2):
td2_total = float(get_timedelta_total_microseconds(td2))
return td1_total / td2_total
class TimeScale(object):
"Describes a scale factor based on time instead of a scalar"
def __init__(self, width, range):
@ -111,8 +125,8 @@ class TimeScale(object):
scale = divide_timedelta(delta, self.range)
return scale * self.width
# the following three functions were copied from jaraco.util.iter_
# the following three functions were copied from jaraco.util.iter_
# todo, factor out caching capability
class iterable_test(dict):
"Test objects for iterability, caching the result by type"
@ -120,7 +134,8 @@ class iterable_test(dict):
"""ignore_classes must include basestring, because if a string
is iterable, so is a single character, and the routine runs
into an infinite recursion"""
assert basestring in ignore_classes, 'basestring must be in ignore_classes'
assert (basestring in ignore_classes,
'basestring must be in ignore_classes')
self.ignore_classes = ignore_classes
def __getitem__(self, candidate):
@ -137,6 +152,7 @@ class iterable_test(dict):
self[type(candidate)] = result
return result
def iflatten(subject, test=None):
if test is None:
test = iterable_test()
@ -147,6 +163,7 @@ def iflatten(subject, test=None):
for subelem in iflatten(elem, test):
yield subelem
def flatten(subject, test=None):
"""flatten an iterable with possible nested iterables.
Adapted from
@ -159,4 +176,3 @@ def flatten(subject, test=None):
['ab', 'c']
"""
return list(iflatten(subject, test))

15
tests/samples.py

@ -2,7 +2,8 @@
Samples of the various charts. Run this script to generate the reference
samples.
"""
import sys, os
import os
import sys
from svg.charts.plot import Plot
from svg.charts import bar
@ -11,6 +12,7 @@ from svg.charts import pie
from svg.charts import schedule
from svg.charts import line
def sample_Plot():
g = Plot({
'min_x_value': 0,
@ -25,6 +27,7 @@ def sample_Plot():
g.add_data({'data': [.5, 35, 1, 20, 3, 10.5], 'title': 'series 3'})
return g
def sample_TimeSeries():
g = time_series.Plot({})
@ -33,10 +36,12 @@ def sample_TimeSeries():
g.x_label_format = '%d-%b %H:%M'
#g.max_y_value = 200
g.add_data({'data': ['2005-12-21T00:00:00', 20, '2005-12-22T00:00:00', 21], 'title': 'series 1'})
g.add_data({'data': ['2005-12-21T00:00:00', 20, '2005-12-22T00:00:00', 21],
'title': 'series 1'})
return g
def generate_samples():
yield 'Plot', sample_Plot()
yield 'TimeSeries', sample_TimeSeries()
@ -47,6 +52,7 @@ def generate_samples():
yield 'Schedule', sample_Schedule()
yield 'Line', sample_Line()
class SampleBar:
fields = ['Internet', 'TV', 'Newspaper', 'Magazine', 'Radio']
@ -98,6 +104,7 @@ class SampleBar:
g.add_data(dict(data=[2, 26, 106, 193, 105], title='old'))
return g
def sample_Line():
g = line.Line()
options = dict(
@ -115,6 +122,7 @@ def sample_Line():
g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
return g
def sample_Pie():
g = pie.Pie({})
options = dict(
@ -130,6 +138,7 @@ def sample_Pie():
g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
return g
def sample_Schedule():
title = "Billy's Schedule"
data1 = [
@ -167,6 +176,7 @@ def sample_Schedule():
return g
def save_samples():
root = os.path.dirname(__file__)
for sample_name, sample in generate_samples():
@ -176,4 +186,3 @@ def save_samples():
if __name__ == '__main__':
save_samples()

2
tests/test_plot.py

@ -1,6 +1,6 @@
import unittest
class PlotTester(unittest.TestCase):
def test_index_error_2010_04(self):
"""

2
tests/test_samples.py

@ -1,9 +1,11 @@
import samples
def pytest_generate_tests(metafunc):
if "sample" in metafunc.funcargnames:
for name, chart in samples.generate_samples():
metafunc.addcall(funcargs=dict(sample=chart))
def test_sample(sample):
res = sample.burn()

4
tests/test_time_series.py

@ -1,5 +1,6 @@
from svg.charts import time_series
def test_field_width():
"""
cking reports in a comment on PyPI that the X-axis labels all
@ -12,6 +13,7 @@ def test_field_width():
g.stagger_x_labels = True
g.x_label_format = '%d-%b %H:%M'
g.add_data({'data': ['2005-12-21T00:00:00', 20, '2005-12-22T00:00:00', 21], 'title': 'series 1'})
g.add_data({'data': ['2005-12-21T00:00:00', 20, '2005-12-22T00:00:00', 21],
'title': 'series 1'})
g.burn()
assert g.field_width() > 1

Loading…
Cancel
Save