Browse Source

Pep8

pull/8/head
Florian Mounier 13 years ago
parent
commit
9b4b240eb3
  1. 23
      docs/conf.py
  2. 34
      setup.py
  3. 43
      svg/charts/bar.py
  4. 26
      svg/charts/css.py
  5. 228
      svg/charts/graph.py
  6. 41
      svg/charts/line.py
  7. 65
      svg/charts/pie.py
  8. 91
      svg/charts/plot.py
  9. 50
      svg/charts/schedule.py
  10. 54
      svg/charts/time_series.py
  11. 40
      svg/charts/util.py
  12. 91
      tests/samples.py
  13. 4
      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 # svg.charts documentation build configuration file, created by
# sphinx-quickstart on Tue May 11 10:51:55 2010. # 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 # Note that not all possible configuration values are present in this
# autogenerated file. # autogenerated file.
@ -11,7 +11,8 @@
# All configuration values have a default; values that are commented out # All configuration values have a default; values that are commented out
# serve to show the default. # serve to show the default.
import sys, os import os
import sys
# Get configuration information from the setup script # Get configuration information from the setup script
sys.path.insert(0, '..') 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. # documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.')) #sys.path.append(os.path.abspath('.'))
# -- General configuration ----------------------------------------------------- # -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions # Add any Sphinx extension module names here, as strings.
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. # They can be extensions coming with Sphinx (named 'sphinx.ext.*')
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo'] # 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. # Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates'] templates_path = ['_templates']
@ -71,7 +74,7 @@ release = version
# for source files. # for source files.
exclude_trees = ['_build'] 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 #default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text. # If true, '()' will be appended to :func: etc. cross-reference text.
@ -92,7 +95,7 @@ pygments_style = 'sphinx'
#modindex_common_prefix = [] #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 # The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'. # Sphinx are currently 'default' and 'sphinxdoc'.
@ -166,7 +169,7 @@ html_static_path = ['_static']
htmlhelp_basename = 'svgchartsdoc' htmlhelp_basename = 'svgchartsdoc'
# -- Options for LaTeX output -------------------------------------------------- # -- Options for LaTeX output -------------------------------------------------
# The paper size ('letter' or 'a4'). # The paper size ('letter' or 'a4').
#latex_paper_size = 'letter' #latex_paper_size = 'letter'
@ -175,7 +178,7 @@ htmlhelp_basename = 'svgchartsdoc'
#latex_font_size = '10pt' #latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples # 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 = [ latex_documents = [
('index', 'svgcharts.tex', u'svg.charts Documentation', ('index', 'svgcharts.tex', u'svg.charts Documentation',
setup_params['author'], 'manual'), setup_params['author'], 'manual'),

34
setup.py

@ -6,10 +6,14 @@ from setuptools import find_packages
from distutils.cmd import Command from distutils.cmd import Command
class DisabledTestCommand(Command): class DisabledTestCommand(Command):
user_options = [] user_options = []
def __init__(self, dist): 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__) _this_dir = os.path.dirname(__file__)
_readme = os.path.join(_this_dir, 'readme.txt') _readme = os.path.join(_this_dir, 'readme.txt')
@ -17,27 +21,27 @@ _long_description = open(_readme).read().strip()
# it seems that dateutil 2.0 only works under Python 3 # it seems that dateutil 2.0 only works under Python 3
dateutil_req = ( dateutil_req = (
['python-dateutil>=1.4,<2.0dev'] if sys.version_info < (3,0) ['python-dateutil>=1.4,<2.0dev'] if sys.version_info < (3, 0)
else ['python-dateutil>=2.0'] ) else ['python-dateutil>=2.0'])
setup_params = dict( setup_params = dict(
name = "svg.charts", name="svg.charts",
use_hg_version=True, use_hg_version=True,
description = "Python SVG Charting Library", description="Python SVG Charting Library",
long_description = _long_description, long_description=_long_description,
author = "Jason R. Coombs", author="Jason R. Coombs",
author_email = "jaraco@jaraco.com", author_email="jaraco@jaraco.com",
url = "http://svg-charts.sourceforge.net", url="http://svg-charts.sourceforge.net",
packages = find_packages(), packages=find_packages(),
zip_safe=True, zip_safe=True,
namespace_packages=['svg'], namespace_packages=['svg'],
include_package_data = True, include_package_data=True,
install_requires=[ install_requires=[
'cssutils>=0.9.8a3', 'cssutils>=0.9.8a3',
'lxml>=2.0', 'lxml>=2.0',
] + dateutil_req, ] + dateutil_req,
license = "MIT", license="MIT",
classifiers = [ classifiers=[
"Development Status :: 5 - Production/Stable", "Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers", "Intended Audience :: Developers",
"Intended Audience :: Science/Research", "Intended Audience :: Science/Research",
@ -46,7 +50,7 @@ setup_params = dict(
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License", "License :: OSI Approved :: MIT License",
], ],
entry_points = { entry_points={
}, },
# Don't use setup.py test - nose doesn't support it # Don't use setup.py test - nose doesn't support it
# see http://code.google.com/p/python-nose/issues/detail?id=219 # see http://code.google.com/p/python-nose/issues/detail?id=219
@ -56,7 +60,7 @@ setup_params = dict(
setup_requires=[ setup_requires=[
'hgtools', 'hgtools',
], ],
use_2to3 = True, use_2to3=True,
) )
if __name__ == '__main__': if __name__ == '__main__':

43
svg/charts/bar.py

@ -5,6 +5,7 @@ from svg.charts.graph import Graph
__all__ = ('VerticalBar', 'HorizontalBar') __all__ = ('VerticalBar', 'HorizontalBar')
class Bar(Graph): class Bar(Graph):
"A superclass for bar-style graphs. Do not instantiate directly." "A superclass for bar-style graphs. Do not instantiate directly."
@ -27,7 +28,8 @@ class Bar(Graph):
# adapted from Plot # adapted from Plot
def get_data_values(self): def get_data_values(self):
min_value, max_value, scale_division = self.data_range() 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: if self.scale_integers:
result = map(int, result) result = map(int, result)
return result return result
@ -60,13 +62,14 @@ class Bar(Graph):
# return max(map(lambda set: max(set['data']), self.data)) # return max(map(lambda set: max(set['data']), self.data))
def data_min(self): 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(chain(*map(lambda set: set['data'], self.data)))
min_value = min(min_value, 0) min_value = min(min_value, 0)
return min_value return min_value
def get_bar_gap(self, field_size): def get_bar_gap(self, field_size):
bar_gap = 10 # default gap bar_gap = 10 # default gap
if field_size < 10: if field_size < 10:
# adjust for narrow fields # adjust for narrow fields
bar_gap = field_size / 2 bar_gap = field_size / 2
@ -74,7 +77,8 @@ class Bar(Graph):
bar_gap = int(self.bar_gap) * bar_gap bar_gap = int(self.bar_gap) * bar_gap
return bar_gap return bar_gap
def float_range(start = 0, stop = None, step = 1):
def float_range(start=0, stop=None, step=1):
"Much like the built-in function range, but accepts floats" "Much like the built-in function range, but accepts floats"
while start < stop: while start < stop:
yield float(start) yield float(start)
@ -147,8 +151,10 @@ class VerticalBar(Bar):
def draw_data(self): def draw_data(self):
min_value = self.data_min() min_value = self.data_min()
unit_size = (float(self.graph_height) - self.font_size*2*self.top_font) unit_size = (
unit_size /= (max(self.get_data_values()) - min(self.get_data_values())) 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()) bar_gap = self.get_bar_gap(self.get_field_width())
@ -156,9 +162,9 @@ class VerticalBar(Bar):
if self.stack == 'side': if self.stack == 'side':
bar_width /= len(self.data) bar_width /= len(self.data)
x_mod = (self.graph_width - bar_gap)/2 x_mod = (self.graph_width - bar_gap) / 2
if self.stack == 'side': if self.stack == 'side':
x_mod -= bar_width/2 x_mod -= bar_width / 2
bottom = self.graph_height bottom = self.graph_height
@ -175,7 +181,7 @@ class VerticalBar(Bar):
length = (abs(value) - max(min_value, 0)) * unit_size length = (abs(value) - max(min_value, 0)) * unit_size
# top is 0 if value is negative # top is 0 if value is negative
top = bottom - ((max(value,0) - min_value) * unit_size) top = bottom - ((max(value, 0) - min_value) * unit_size)
if self.stack == 'side': if self.stack == 'side':
left += bar_width * dataset_count left += bar_width * dataset_count
@ -184,10 +190,12 @@ class VerticalBar(Bar):
'y': str(top), 'y': str(top),
'width': str(bar_width), 'width': str(bar_width),
'height': str(length), 'height': str(length),
'class': 'fill%s' % (dataset_count+1), '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): class HorizontalBar(Bar):
rotate_y_labels = True rotate_y_labels = True
@ -195,7 +203,6 @@ class HorizontalBar(Bar):
show_y_guidelines = False show_y_guidelines = False
right_align = right_font = True right_align = right_font = True
def get_x_labels(self): def get_x_labels(self):
return self.get_data_labels() return self.get_data_labels()
@ -209,7 +216,7 @@ class HorizontalBar(Bar):
min_value = self.data_min() min_value = self.data_min()
unit_size = float(self.graph_width) unit_size = float(self.graph_width)
unit_size -= self.font_size*2*self.right_font unit_size -= self.font_size * 2 * self.right_font
unit_size /= max(self.get_data_values()) - min(self.get_data_values()) unit_size /= max(self.get_data_values()) - min(self.get_data_values())
bar_gap = self.get_bar_gap(self.get_field_height()) bar_gap = self.get_bar_gap(self.get_field_height())
@ -224,7 +231,8 @@ class HorizontalBar(Bar):
for dataset_count, dataset in enumerate(self.data): for dataset_count, dataset in enumerate(self.data):
value = dataset['data'][field_count] 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': if self.stack == 'side':
top += (bar_height * dataset_count) top += (bar_height * dataset_count)
# cases (assume 0 = +ve): # cases (assume 0 = +ve):
@ -241,8 +249,9 @@ class HorizontalBar(Bar):
'y': str(top), 'y': str(top),
'width': str(length), 'width': str(length),
'height': str(bar_height), 'height': str(bar_height),
'class': 'fill%s' % (dataset_count+1), 'class': 'fill%s' % (dataset_count + 1),
}) })
self.make_datapoint_text(left+length+5, top+y_mod, value, self.make_datapoint_text(
"text-anchor: start; ") left + length + 5, top + y_mod, value,
"text-anchor: start; ")

26
svg/charts/css.py

@ -1,6 +1,6 @@
import cssutils import cssutils
SVG = 'SVG 1.1' # http://www.w3.org/TR/SVG11/styling.html SVG = 'SVG 1.1' # http://www.w3.org/TR/SVG11/styling.html
macros = { macros = {
'paint': 'none|currentColor|{color}', 'paint': 'none|currentColor|{color}',
@ -29,14 +29,17 @@ properties = {
'stop-opacity': '{num}|inherit', 'stop-opacity': '{num}|inherit',
# Interactivity Properties # 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 and Pointing Properties
'color-interpolation': 'auto|sRGB|linearRGB|inherit', 'color-interpolation': 'auto|sRGB|linearRGB|inherit',
'color-interpolation-filters': 'auto|sRGB|linearRGB|inherit', 'color-interpolation-filters': 'auto|sRGB|linearRGB|inherit',
'color-rendering': 'auto|optimizeSpeed|optimizeQuality|inherit', 'color-rendering': 'auto|optimizeSpeed|optimizeQuality|inherit',
'shape-rendering': 'auto|optimizeSpeed|crispEdges|geometricPrecision|inherit', 'shape-rendering': ('auto|optimizeSpeed|crispEdges|'
'text-rendering': 'auto|optimizeSpeed|optimizeLegibility|geometricPrecision|inherit', 'geometricPrecision|inherit'),
'text-rendering': ('auto|optimizeSpeed|optimizeLegibility'
'|geometricPrecision|inherit'),
'fill': '{paint}', 'fill': '{paint}',
'fill-opacity': '{num}|inherit', 'fill-opacity': '{num}|inherit',
'fill-rule': 'nonzero|evenodd|inherit', 'fill-rule': 'nonzero|evenodd|inherit',
@ -45,7 +48,8 @@ properties = {
'marker-end': 'none|inherit|{uri}', 'marker-end': 'none|inherit|{uri}',
'marker-mid': 'none|inherit|{uri}', 'marker-mid': 'none|inherit|{uri}',
'marker-start': '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': '{paint}',
'stroke-dasharray': 'none|{dasharray}|inherit', 'stroke-dasharray': 'none|{dasharray}|inherit',
'stroke-dashoffset': '{length}|inherit', 'stroke-dashoffset': '{length}|inherit',
@ -54,12 +58,18 @@ properties = {
'stroke-miterlimit': '{number-ge-one}|inherit', 'stroke-miterlimit': '{number-ge-one}|inherit',
'stroke-opacity': '{num}|inherit', 'stroke-opacity': '{num}|inherit',
'stroke-width': '{length}|inherit', 'stroke-width': '{length}|inherit',
'text-rendering': 'auto|optimizeSpeed|optimizeLegibility|geometricPrecision|inherit', 'text-rendering': ('auto|optimizeSpeed|optimizeLegibility'
'|geometricPrecision|inherit'),
# Text Properties # 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', '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-horizontal': '{angle}|inherit',
'glyph-orientation-vertical': 'auto|{angle}|inherit', 'glyph-orientation-vertical': 'auto|{angle}|inherit',
'kerning': 'auto|{length}|inherit', 'kerning': 'auto|{length}|inherit',

228
svg/charts/graph.py

@ -1,5 +1,5 @@
#!python #!python
# -*- coding: UTF-8 -*- # -*- coding: utf-8 -*-
""" """
svg.charts.graph svg.charts.graph
@ -14,20 +14,24 @@ import functools
import cssutils import cssutils
from lxml import etree from lxml import etree
from xml import xpath
from svg.charts import css # causes the SVG profile to be loaded from svg.charts import css # causes the SVG profile to be loaded
try: try:
import zlib import zlib
except ImportError: except ImportError:
zlib = None zlib = None
def sort_multiple(arrays): 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 = zip(*arrays)
tuples.sort() tuples.sort()
return zip(*tuples) return zip(*tuples)
class Graph(object): class Graph(object):
""" """
Base object for generating SVG Graphs Base object for generating SVG Graphs
@ -47,46 +51,48 @@ class Graph(object):
* svg.charts.time_series * svg.charts.time_series
""" """
width= 500 width = 500
height= 300 height = 300
show_x_guidelines= False show_x_guidelines = False
show_y_guidelines= True show_y_guidelines = True
show_data_values= True show_data_values = True
min_scale_value= None min_scale_value = None
show_x_labels= True show_x_labels = True
stagger_x_labels= False stagger_x_labels = False
rotate_x_labels= False rotate_x_labels = False
step_x_labels= 1 step_x_labels = 1
step_include_first_x_label= True step_include_first_x_label = True
show_y_labels= True show_y_labels = True
rotate_y_labels= False rotate_y_labels = False
stagger_y_labels= False stagger_y_labels = False
step_include_first_y_label= True step_include_first_y_label = True
step_y_labels= 1 step_y_labels = 1
scale_integers= False scale_integers = False
show_x_title= False show_x_title = False
x_title= 'X Field names' x_title = 'X Field names'
show_y_title= False 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= 'Y Scale' y_title_text_direction = 'bt'
show_graph_title= False y_title = 'Y Scale'
graph_title= 'Graph Title' show_graph_title = False
show_graph_subtitle= False graph_title = 'Graph Title'
graph_subtitle= 'Graph Subtitle' show_graph_subtitle = False
key= True graph_subtitle = 'Graph Subtitle'
key_position= 'right' # 'bottom' or 'right', key = True
# 'bottom' or 'right',
font_size= 12 key_position = 'right'
title_font_size= 16
subtitle_font_size= 14 font_size = 12
x_label_font_size= 12 title_font_size = 16
x_title_font_size= 14 subtitle_font_size = 14
y_label_font_size= 12 x_label_font_size = 12
y_title_font_size= 14 x_title_font_size = 14
key_font_size= 10 y_label_font_size = 12
y_title_font_size = 14
css_inline= False key_font_size = 10
add_popups= False
css_inline = False
add_popups = False
top_align = top_font = right_align = right_font = 0 top_align = top_font = right_align = right_font = 0
@ -94,7 +100,7 @@ class Graph(object):
stylesheet_names = ['graph.css'] stylesheet_names = ['graph.css']
def __init__(self, config = {}): def __init__(self, config={}):
"""Initialize the graph object with the graph settings.""" """Initialize the graph object with the graph settings."""
if self.__class__ is Graph: if self.__class__ is Graph:
raise NotImplementedError("Graph is an abstract base class") raise NotImplementedError("Graph is an abstract base class")
@ -124,12 +130,15 @@ class Graph(object):
try: try:
assert(isinstance(conf['data'], (tuple, list))) assert(isinstance(conf['data'], (tuple, list)))
except TypeError, e: 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: except AssertionError:
if not hasattr(conf['data'], '__iter__'): 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): def clear_data(self):
""" """
@ -148,9 +157,11 @@ class Graph(object):
Raises ValueError when no data set has Raises ValueError when no data set has
been added to the graph object. 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.start_svg()
self.calculate_graph_dimensions() self.calculate_graph_dimensions()
@ -166,9 +177,12 @@ class Graph(object):
def _burn_compressed(self): def _burn_compressed(self):
if self.compress and not zlib: 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: if self.compress and zlib:
data = zlib.compress(data) data = zlib.compress(data)
@ -189,10 +203,14 @@ class Graph(object):
else: else:
label_lengths = map(len, self.get_y_labels()) label_lengths = map(len, self.get_y_labels())
max_y_label_len = max(label_lengths) max_y_label_len = max(label_lengths)
max_y_label_height_px = 0.6 * max_y_label_len * self.y_label_font_size max_y_label_height_px = (0.6 * max_y_label_len *
if self.show_y_labels: bl += max_y_label_height_px self.y_label_font_size)
if self.stagger_y_labels: bl += max_y_label_height_px + 10 if self.show_y_labels:
if self.show_y_title: bl += self.y_title_font_size + 5 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 self.border_left = bl
def max_y_label_width_px(self): def max_y_label_width_px(self):
@ -222,17 +240,19 @@ class Graph(object):
border_top. border_top.
""" """
self.border_top = 5 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 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): def add_popup(self, x, y, label):
""" """
Add pop-up information to a point on the graph. Add pop-up information to a point on the graph.
""" """
txt_width = len(label) * self.font_size * 0.6 + 10 txt_width = len(label) * self.font_size * 0.6 + 10
tx = x + [5,-5][int(x+txt_width > self.width)] tx = x + [5, -5][int(x + txt_width > self.width)]
anchor = ['start', 'end'][x+txt_width > self.width] anchor = ['start', 'end'][x + txt_width > self.width]
style = 'fill: #000; text-anchor: %s;' % anchor style = 'fill: #000; text-anchor: %s;' % anchor
id = 'label-%s' % label id = 'label-%s' % label
t = etree.SubElement(self.foreground, 'text', { t = etree.SubElement(self.foreground, 'text', {
@ -245,7 +265,8 @@ class Graph(object):
}) })
# add the circle element to the foreground # 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', { t = etree.SubElement(self.foreground, 'circle', {
'cx': str(x), 'cx': str(x),
'cy': str(y), 'cy': str(y),
@ -271,8 +292,10 @@ class Graph(object):
max_x_label_len = reduce(max, label_lengths) max_x_label_len = reduce(max, label_lengths)
max_x_label_height_px *= 0.6 * max_x_label_len max_x_label_height_px *= 0.6 * max_x_label_len
bb += max_x_label_height_px bb += max_x_label_height_px
if self.stagger_x_labels: bb += max_x_label_height_px + 10 if self.stagger_x_labels:
if self.show_x_title: bb += self.x_title_font_size + 5 bb += max_x_label_height_px + 10
if self.show_x_title:
bb += self.x_title_font_size + 5
self.border_bottom = bb self.border_bottom = bb
def draw_graph(self): def draw_graph(self):
@ -336,7 +359,8 @@ class Graph(object):
'y': str(y), 'y': str(y),
'class': 'dataPointLabel'}) 'class': 'dataPointLabel'})
e.text = str(value) e.text = str(value)
if style: e.set('style', style) if style:
e.set('style', style)
def draw_x_labels(self): def draw_x_labels(self):
"Draw the X axis labels" "Draw the X axis labels"
@ -374,7 +398,7 @@ class Graph(object):
if self.rotate_x_labels: if self.rotate_x_labels:
transform = 'rotate(90 %d %d) translate(0 -%d)' % \ transform = 'rotate(90 %d %d) translate(0 -%d)' % \
(x, y-self.x_label_font_size, self.x_label_font_size/4) (x, y - self.x_label_font_size, self.x_label_font_size / 4)
text.set('transform', transform) text.set('transform', transform)
text.set('style', 'text-anchor: start') text.set('style', 'text-anchor: start')
else: else:
@ -388,13 +412,14 @@ class Graph(object):
return 0 return 0
def get_field_width(self): def get_field_width(self):
return float(self.graph_width - self.font_size*2*self.right_font) / \ return (float(
(len(self.get_x_labels()) - self.right_align) self.graph_width - self.font_size * 2 * self.right_font) /
(len(self.get_x_labels()) - self.right_align))
field_width = get_field_width field_width = get_field_width
def get_field_height(self): def get_field_height(self):
return float(self.graph_height - self.font_size*2*self.top_font) / \ return (float(self.graph_height - self.font_size * 2 * self.top_font) /
(len(self.get_y_labels()) - self.top_align) (len(self.get_y_labels()) - self.top_align))
field_height = get_field_height field_height = get_field_height
def draw_y_labels(self): def draw_y_labels(self):
@ -414,7 +439,8 @@ class Graph(object):
def get_y_offset(self): def get_y_offset(self):
result = self.graph_height + self.y_label_offset(self.field_height()) 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 return result
y_offset = property(get_y_offset) y_offset = property(get_y_offset)
@ -425,7 +451,7 @@ class Graph(object):
text.text = label text.text = label
y = self.y_offset - (label_height * index) y = self.y_offset - (label_height * index)
x = {True: 0, False:-3}[self.rotate_y_labels] x = {True: 0, False: -3}[self.rotate_y_labels]
if self.stagger_y_labels and (index % 2): if self.stagger_y_labels and (index % 2):
stagger = self.y_label_font_size + 5 stagger = self.y_label_font_size + 5
@ -444,15 +470,16 @@ class Graph(object):
text.set('transform', transform) text.set('transform', transform)
text.set('style', 'text-anchor: middle') text.set('style', 'text-anchor: middle')
else: else:
text.set('y', str(y - self.y_label_font_size/2)) text.set('y', str(y - self.y_label_font_size / 2))
text.set('style', 'text-anchor: end') text.set('style', 'text-anchor: end')
def draw_x_guidelines(self, label_height, count): def draw_x_guidelines(self, label_height, count):
"Draw the X-axis guidelines" "Draw the X-axis guidelines"
if not self.show_x_guidelines: return if not self.show_x_guidelines:
return
# skip the first one # skip the first one
for count in range(1,count): for count in range(1, count):
start = label_height*count start = label_height * count
stop = self.graph_height stop = self.graph_height
path = etree.SubElement(self.graph, 'path', { path = etree.SubElement(self.graph, 'path', {
'd': 'M %(start)s 0 v%(stop)s' % vars(), 'd': 'M %(start)s 0 v%(stop)s' % vars(),
@ -460,9 +487,10 @@ class Graph(object):
def draw_y_guidelines(self, label_height, count): def draw_y_guidelines(self, label_height, count):
"Draw the Y-axis guidelines" "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): for count in range(1, count):
start = self.graph_height - label_height*count start = self.graph_height - label_height * count
stop = self.graph_width stop = self.graph_width
path = etree.SubElement(self.graph, 'path', { path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % vars(), 'd': 'M 0 %(start)s h%(stop)s' % vars(),
@ -470,10 +498,14 @@ class Graph(object):
def draw_titles(self): def draw_titles(self):
"Draws the graph title and subtitle" "Draws the graph title and subtitle"
if self.show_graph_title: self.draw_graph_title() if self.show_graph_title:
if self.show_graph_subtitle: self.draw_graph_subtitle() self.draw_graph_title()
if self.show_x_title: self.draw_x_title() if self.show_graph_subtitle:
if self.show_y_title: self.draw_y_title() 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): def draw_graph_title(self):
text = etree.SubElement(self.root, 'text', { text = etree.SubElement(self.root, 'text', {
@ -483,10 +515,11 @@ class Graph(object):
text.text = self.graph_title text.text = self.graph_title
def draw_graph_subtitle(self): 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] y_subtitle = y_subtitle_options[self.show_graph_title]
text = etree.SubElement(self.root, 'text', { text = etree.SubElement(self.root, 'text', {
'x': str(self.width/2), 'x': str(self.width / 2),
'y': str(y_subtitle), 'y': str(y_subtitle),
'class': 'subTitle', 'class': 'subTitle',
}) })
@ -495,8 +528,9 @@ class Graph(object):
def draw_x_title(self): def draw_x_title(self):
y = self.graph_height + self.border_top + self.x_title_font_size y = self.graph_height + self.border_top + self.x_title_font_size
if self.show_x_labels: if self.show_x_labels:
y_size = self.x_label_font_size+5 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 y += y_size
x = self.width / 2 x = self.width / 2
@ -509,7 +543,7 @@ class Graph(object):
def draw_y_title(self): def draw_y_title(self):
x = self.y_title_font_size x = self.y_title_font_size
if self.y_title_text_direction=='bt': if self.y_title_text_direction == 'bt':
x += 3 x += 3
rotate = -90 rotate = -90
else: else:
@ -560,16 +594,16 @@ class Graph(object):
x_offset = self.border_left + 20 x_offset = self.border_left + 20
y_offset = self.border_top + self.graph_height + 5 y_offset = self.border_top + self.graph_height + 5
if self.show_x_labels: 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: if self.rotate_x_labels:
longest_label_length = max(map(len, self.get_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 max_x_label_height_px *= longest_label_length * 0.6
y_offset += max_x_label_height_px y_offset += max_x_label_height_px
if self.stagger_x_labels: if self.stagger_x_labels:
y_offset += max_x_label_height_px + 5 y_offset += max_x_label_height_px + 5
if self.show_x_title: 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 return x_offset, y_offset
def render_inline_styles(self): def render_inline_styles(self):
@ -612,11 +646,12 @@ class Graph(object):
'xlink': 'http://www.w3.org/1999/xlink', 'xlink': 'http://www.w3.org/1999/xlink',
'a3': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/', 'a3': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/',
} }
self.root = etree.Element(SVG+"svg", attrib={ self.root = etree.Element(SVG + "svg", attrib={
'width': str(self.width), 'width': str(self.width),
'height': str(self.height), 'height': str(self.height),
'viewBox': '0 0 %s %s' % (self.width, 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) }, nsmap=NSMAP)
if hasattr(self, 'style_sheet_href'): if hasattr(self, 'style_sheet_href'):
pi = etree.ProcessingInstruction( pi = etree.ProcessingInstruction(
@ -630,7 +665,7 @@ class Graph(object):
' SVG.Graph by Jason R. Coombs ', ' SVG.Graph by Jason R. Coombs ',
' Based on SVG::Graph by Sean E. Russel ', ' Based on SVG::Graph by Sean E. Russel ',
' Based on Perl SVG:TT:Graph by Leo Lapworth & Stephan Morgan ', ' Based on Perl SVG:TT:Graph by Leo Lapworth & Stephan Morgan ',
' '+'/'*66, ' ' + '/' * 66,
) )
map(self.root.append, map(etree.Comment, comment_strings)) map(self.root.append, map(etree.Comment, comment_strings))
@ -638,10 +673,11 @@ class Graph(object):
self.add_defs(defs) self.add_defs(defs)
if not hasattr(self, 'style_sheet_href') and not self.css_inline: 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') style = etree.SubElement(defs, 'style', type='text/css')
# TODO: the text was previously escaped in a CDATA declaration... how # TODO: the text was previously escaped in a CDATA declaration...
# to do that with etree? # how to do that with etree?
style.text = self.get_stylesheet().cssText style.text = self.get_stylesheet().cssText
self.root.append(etree.Comment('SVG Background')) self.root.append(etree.Comment('SVG Background'))
@ -678,12 +714,14 @@ class Graph(object):
return sheets return sheets
def get_stylesheet(self): def get_stylesheet(self):
cssutils.log.setLevel(30) # disable INFO log messages cssutils.log.setLevel(30) # disable INFO log messages
def merge_sheets(s1, s2): def merge_sheets(s1, s2):
map(s1.add, s2) map(s1.add, s2)
return s1 return s1
return reduce(merge_sheets, self.get_stylesheet_resources()) return reduce(merge_sheets, self.get_stylesheet_resources())
class class_dict(object): class class_dict(object):
"Emulates a dictionary, but retrieves class attributes" "Emulates a dictionary, but retrieves class attributes"
def __init__(self, obj): def __init__(self, obj):

41
svg/charts/line.py

@ -8,6 +8,7 @@ from lxml import etree
from util import flatten, float_range from util import flatten, float_range
from svg.charts.graph import Graph from svg.charts.graph import Graph
class Line(Graph): class Line(Graph):
"""Line Graph""" """Line Graph"""
@ -42,12 +43,13 @@ class Line(Graph):
data = self.get_cumulative_data() data = self.get_cumulative_data()
return min(flatten(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 """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 the actual first data set. The second will be the sum of the
first and the second, etc.""" first and the second, etc."""
sets = map(itemgetter('data'), self.data) sets = map(itemgetter('data'), self.data)
if not sets: return if not sets:
return
sum = sets.pop(0) sum = sets.pop(0)
yield sum yield sum
while sets: while sets:
@ -72,7 +74,7 @@ class Line(Graph):
scale_division = self.scale_divisions or (scale_range / 10.0) scale_division = self.scale_divisions or (scale_range / 10.0)
if self.scale_integers: if self.scale_integers:
scale_division = min(1, round(scale_division)) scale_division = min(1, round(scale_division))
if max_value % scale_division == 0: if max_value % scale_division == 0:
max_value += scale_division max_value += scale_division
@ -82,18 +84,20 @@ class Line(Graph):
def get_y_labels(self): def get_y_labels(self):
return map(str, self.get_y_label_values()) return map(str, self.get_y_label_values())
def calc_coords(self, field, value, width = None, height = None): def calc_coords(self, field, value, width=None, height=None):
if width is None: width = self.field_width if width is None:
if height is None: height = self.field_height width = self.field_width
if height is None:
height = self.field_height
coords = dict( coords = dict(
x = width * field, x=width * field,
y = self.graph_height - value * height, y=self.graph_height - value * height,
) )
return coords return coords
def draw_data(self): def draw_data(self):
min_value = self.min_value() min_value = self.min_value()
field_height = self.graph_height - self.font_size*2*self.top_font field_height = self.graph_height - self.font_size * 2 * self.top_font
y_label_values = self.get_y_label_values() y_label_values = self.get_y_label_values()
y_label_span = max(y_label_values) - min(y_label_values) y_label_span = max(y_label_values) - min(y_label_values)
@ -102,15 +106,16 @@ class Line(Graph):
field_width = self.field_width() field_width = self.field_width()
#line = len(self.data) #line = len(self.data)
prev_sum = [0]*len(self.fields) prev_sum = [0] * len(self.fields)
cum_sum = [-min_value]*len(self.fields) cum_sum = [-min_value] * len(self.fields)
coord_format = lambda c: '%(x)s %(y)s' % c coord_format = lambda c: '%(x)s %(y)s' % c
for line_n, data in reversed(list(enumerate(self.data, 1))): for line_n, data in reversed(list(enumerate(self.data, 1))):
apath = '' 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']) cum_sum = map(add, cum_sum, data['data'])
get_coords = lambda (i, val): self.calc_coords(i, get_coords = lambda (i, val): self.calc_coords(i,
@ -132,7 +137,7 @@ class Line(Graph):
origin = paths[-1] origin = paths[-1]
else: else:
area_path = "V%(graph_height)s" % vars(self) area_path = "V%(graph_height)s" % vars(self)
origin = coord_format(get_coords((0,0))) origin = coord_format(get_coords((0, 0)))
d = ' '.join(( d = ' '.join((
'M', 'M',
@ -160,13 +165,13 @@ class Line(Graph):
self.graph, self.graph,
'circle', 'circle',
{'class': 'dataPoint%(line_n)s' % vars()}, {'class': 'dataPoint%(line_n)s' % vars()},
cx = str(field_width*i), cx=str(field_width * i),
cy = str(self.graph_height - value*field_height), cy=str(self.graph_height - value * field_height),
r = '2.5', r='2.5',
) )
self.make_datapoint_text( self.make_datapoint_text(
field_width*i, field_width * i,
self.graph_height - value*field_height - 6, self.graph_height - value * field_height - 6,
value + min_value value + min_value
) )

65
svg/charts/pie.py

@ -3,13 +3,17 @@ import itertools
from lxml import etree from lxml import etree
from svg.charts.graph import Graph from svg.charts.graph import Graph
def robust_add(a,b):
def robust_add(a, b):
"Add numbers a and b, treating None as 0" "Add numbers a and b, treating None as 0"
if a is None: a = 0 if a is None:
if b is None: b = 0 a = 0
return a+b if b is None:
b = 0
return a + b
RADIANS = math.pi / 180
RADIANS = math.pi/180
class Pie(Graph): class Pie(Graph):
""" """
@ -42,14 +46,16 @@ class Pie(Graph):
""" """
"if true, displays a drop shadow for the chart" "if true, displays a drop shadow for the chart"
show_shadow = True show_shadow = True
"Sets the offset of the shadow from the pie chart" "Sets the offset of the shadow from the pie chart"
shadow_offset = 10 shadow_offset = 10
show_data_labels = False show_data_labels = False
"If true, display the actual field values in the data labels" "If true, display the actual field values in the data labels"
show_actual_values = False 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 show_percent = True
"If true, display the labels in the key" "If true, display the labels in the key"
@ -62,7 +68,7 @@ class Pie(Graph):
"If true, explode the pie (put space between the wedges)" "If true, explode the pie (put space between the wedges)"
expanded = False expanded = False
"If true, expand the largest pie wedge" "If true, expand the largest pie wedge"
expand_greatest = False expand_greatest = False
"The amount of space between expanded wedges" "The amount of space between expanded wedges"
expand_gap = 10 expand_gap = 10
@ -141,11 +147,12 @@ class Pie(Graph):
def keys(self): def keys(self):
total = sum(self.data) total = sum(self.data)
percent_scale = 100.0 / total percent_scale = 100.0 / total
def key(field, value): def key(field, value):
result = [field] result = [field]
result.append('[%s]' % value) result.append('[%s]' % value)
if self.show_key_percent: if self.show_key_percent:
percent = str(round((v/total*100))) + '%' percent = str(round((value / total * 100))) + '%'
result.append(percent) result.append(percent)
return ' '.join(result) return ' '.join(result)
return map(key, self.fields, self.data) return map(key, self.fields, self.data)
@ -171,7 +178,8 @@ class Pie(Graph):
self.graph.set('transform', transform) self.graph.set('transform', transform)
wedge_text_pad = 5 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) total = sum(self.data)
max_value = max(self.data) max_value = max(self.data)
@ -184,12 +192,12 @@ class Pie(Graph):
percent = percent_scale * value percent = percent_scale * value
radians = prev_percent * rad_mult radians = prev_percent * rad_mult
x_start = radius+(math.sin(radians) * radius) x_start = radius + (math.sin(radians) * radius)
y_start = radius-(math.cos(radians) * radius) y_start = radius - (math.cos(radians) * radius)
radians = (prev_percent+percent) * rad_mult radians = (prev_percent + percent) * rad_mult
x_end = radius+(math.sin(radians) * radius) x_end = radius + (math.sin(radians) * radius)
y_end = radius-(math.cos(radians) * radius) y_end = radius - (math.cos(radians) * radius)
percent_greater_fifty = int(percent>=50) percent_greater_fifty = int(percent >= 50)
path = ' '.join(( path = ' '.join((
"M%(radius)s,%(radius)s", "M%(radius)s,%(radius)s",
"L%(x_start)s,%(y_start)s", "L%(x_start)s,%(y_start)s",
@ -204,7 +212,7 @@ class Pie(Graph):
'path', 'path',
{ {
'd': path, 'd': path,
'class': 'fill%s' % (index+1), 'class': 'fill%s' % (index + 1),
} }
) )
@ -258,20 +266,21 @@ class Pie(Graph):
msr = math.sin(radians) msr = math.sin(radians)
mcr = math.cos(radians) mcr = math.cos(radians)
tx = radius + (msr * radius) tx = radius + (msr * radius)
ty = radius -(mcr * radius) ty = radius - (mcr * radius)
if self.expanded or (self.expand_greatest and value == max_value): if self.expanded or (
tx += (msr * self.expand_gap) self.expand_greatest and value == max_value):
ty -= (mcr * self.expand_gap) tx += (msr * self.expand_gap)
ty -= (mcr * self.expand_gap)
label_node = etree.SubElement( label_node = etree.SubElement(
self.foreground, self.foreground,
'text', 'text',
{ {
'x':str(tx), 'x': str(tx),
'y':str(ty), 'y': str(ty),
'class':'dataPointLabel', 'class': 'dataPointLabel',
'style':'stroke: #fff; stroke-width: 2;', 'style': 'stroke: #fff; stroke-width: 2;'
} }
) )
label_node.text = label label_node.text = label
@ -280,8 +289,8 @@ class Pie(Graph):
self.foreground, self.foreground,
'text', 'text',
{ {
'x':str(tx), 'x': str(tx),
'y':str(ty), 'y': str(ty),
'class': 'dataPointLabel', 'class': 'dataPointLabel',
} }
) )
@ -290,4 +299,4 @@ class Pie(Graph):
prev_percent += percent prev_percent += percent
def round(self, val, to): def round(self, val, to):
return round(val,to) return round(val, to)

91
svg/charts/plot.py

@ -10,15 +10,18 @@ from svg.charts.graph import Graph
from .util import float_range from .util import float_range
def get_pairs(i): def get_pairs(i):
i = iter(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. # I'm not sure how this is more beautiful than ugly.
if sys.version >= '3': if sys.version >= '3':
def apply(func): def apply(func):
return func() return func()
class Plot(Graph): class Plot(Graph):
"""=== For creating SVG plots of scalar data """=== For creating SVG plots of scalar data
@ -105,7 +108,6 @@ class Plot(Graph):
top_align = right_align = top_font = right_font = 1 top_align = right_align = top_font = right_font = 1
"""Determines the scaling for the Y axis divisions. """Determines the scaling for the Y axis divisions.
graph.scale_y_divisions = 0.5 graph.scale_y_divisions = 0.5
@ -143,17 +145,22 @@ class Plot(Graph):
graph.scale_x_divisions = 2 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...""" 0,2,4,6,8..."""
def fget(self): def fget(self):
return getattr(self, '_scale_x_divisions', None) return getattr(self, '_scale_x_divisions', None)
def fset(self, val): def fset(self, val):
self._scale_x_divisions = val self._scale_x_divisions = val
return property(**locals()) return property(**locals())
def validate_data(self, data): def validate_data(self, data):
if len(data['data']) % 2 != 0: 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): def process_data(self, data):
pairs = list(get_pairs(data['data'])) pairs = list(get_pairs(data['data']))
@ -162,28 +169,34 @@ class Plot(Graph):
def calculate_left_margin(self): def calculate_left_margin(self):
super(Plot, self).calculate_left_margin() 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) self.border_left = max(label_left, self.border_left)
def calculate_right_margin(self): def calculate_right_margin(self):
super(Plot, self).calculate_right_margin() 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) self.border_right = max(label_right, self.border_right)
def data_max(self, axis): def data_max(self, axis):
data_index = getattr(self, '%s_data_index' % 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 # 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) spec_max = getattr(self, 'max_%s_value' % axis)
# Python 3 doesn't allow comparing None to int, so use -∞ # 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) max_value = max(max_value, spec_max)
return max_value return max_value
def data_min(self, axis): def data_min(self, axis):
data_index = getattr(self, '%s_data_index' % 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) spec_min = getattr(self, 'min_%s_value' % axis)
if spec_min is not None: if spec_min is not None:
min_value = min(min_value, spec_min) min_value = min(min_value, spec_min)
@ -191,6 +204,7 @@ class Plot(Graph):
x_data_index = 0 x_data_index = 0
y_data_index = 1 y_data_index = 1
def data_range(self, axis): def data_range(self, axis):
side = {'x': 'right', 'y': 'top'}[axis] side = {'x': 'right', 'y': 'top'}[axis]
@ -201,25 +215,33 @@ class Plot(Graph):
side_pad = range / 20.0 or 10 side_pad = range / 20.0 or 10
scale_range = (max_value + side_pad) - min_value 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): if getattr(self, 'scale_%s_integers' % axis):
scale_division = round(scale_division) or 1 scale_division = round(scale_division) or 1
return min_value, max_value, scale_division return min_value, max_value, scale_division
def x_range(self): return self.data_range('x') def x_range(self):
def y_range(self): return self.data_range('y') return self.data_range('x')
def y_range(self):
return self.data_range('y')
def get_data_values(self, axis): def get_data_values(self, axis):
min_value, max_value, scale_division = self.data_range(axis) min_value, max_value, scale_division = self.data_range(axis)
return tuple(float_range(*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_x_values(self):
def get_y_values(self): return self.get_data_values('y') return self.get_data_values('x')
def get_y_values(self):
return self.get_data_values('y')
def get_x_labels(self): def get_x_labels(self):
return map(str, self.get_x_values()) return map(str, self.get_x_values())
def get_y_labels(self): def get_y_labels(self):
return map(str, self.get_y_values()) return map(str, self.get_y_values())
@ -235,12 +257,15 @@ class Plot(Graph):
graph_size = getattr(self, 'graph_%s' % size) graph_size = getattr(self, 'graph_%s' % size)
side_font = getattr(self, '%s_font' % side) side_font = getattr(self, '%s_font' % side)
side_align = getattr(self, '%s_align' % side) side_align = getattr(self, '%s_align' % side)
result = (float(graph_size) - self.font_size*2*side_font) / \ result = ((float(graph_size) - self.font_size * 2 * side_font) /
(len(values) + dx - side_align) (len(values) + dx - side_align))
return result return result
def field_width(self): return self.field_size('x') def field_width(self):
def field_height(self): return self.field_size('y') return self.field_size('x')
def field_height(self):
return self.field_size('y')
def draw_data(self): def draw_data(self):
self.load_transform_parameters() self.load_transform_parameters()
@ -255,7 +280,8 @@ class Plot(Graph):
if self.area_fill: if self.area_fill:
graph_height = self.graph_height graph_height = self.graph_height
path = etree.SubElement(self.graph, 'path', { 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()}) 'class': 'fill%(line)d' % vars()})
if self.draw_lines_between_points: if self.draw_lines_between_points:
path = etree.SubElement(self.graph, 'path', { path = etree.SubElement(self.graph, 'path', {
@ -265,7 +291,7 @@ class Plot(Graph):
self._draw_constant_lines() self._draw_constant_lines()
del self.__transform_parameters del self.__transform_parameters
def add_constant_line(self, value, label = None, style = None): def add_constant_line(self, value, label=None, style=None):
self.constant_lines = getattr(self, 'constant_lines', []) self.constant_lines = getattr(self, 'constant_lines', [])
self.constant_lines.append((value, label, style)) self.constant_lines.append((value, label, style))
@ -293,10 +319,10 @@ class Plot(Graph):
"Cache the parameters necessary to transform x & y coordinates" "Cache the parameters necessary to transform x & y coordinates"
x_min, x_max, x_div = self.x_range() x_min, x_max, x_div = self.x_range()
y_min, y_max, y_div = self.y_range() y_min, y_max, y_div = self.y_range()
x_step = (float(self.graph_width) - self.font_size*2) / \ x_step = ((float(self.graph_width) - self.font_size * 2) /
(x_max - x_min) (x_max - x_min))
y_step = (float(self.graph_height) - self.font_size*2) / \ y_step = ((float(self.graph_height) - self.font_size * 2) /
(y_max - y_min) (y_max - y_min))
self.__transform_parameters = dict(vars()) self.__transform_parameters = dict(vars())
del self.__transform_parameters['self'] del self.__transform_parameters['self']
@ -307,7 +333,7 @@ class Plot(Graph):
points = map(lambda p: "%f %f" % p, points) points = map(lambda p: "%f %f" % p, points)
return 'L' + ' '.join(points) return 'L' + ' '.join(points)
def transform_output_coordinates(self, (x,y)): def transform_output_coordinates(self, (x, y)):
x_min = self.__transform_parameters['x_min'] x_min = self.__transform_parameters['x_min']
x_step = self.__transform_parameters['x_step'] x_step = self.__transform_parameters['x_step']
y_min = self.__transform_parameters['y_min'] y_min = self.__transform_parameters['y_min']
@ -316,12 +342,13 @@ class Plot(Graph):
#vars().update(self.__transform_parameters) #vars().update(self.__transform_parameters)
x = (x - x_min) * x_step x = (x - x_min) * x_step
y = self.graph_height - (y - y_min) * y_step y = self.graph_height - (y - y_min) * y_step
return x,y return x, y
def draw_data_points(self, line, data_points, graph_points): def draw_data_points(self, line, data_points, graph_points):
if not self.show_data_points \ if not self.show_data_points and not self.show_data_values:
and not self.show_data_values: return return
for ((dx,dy),(gx,gy)) in izip(data_points, graph_points):
for ((dx, dy), (gx, gy)) in izip(data_points, graph_points):
if self.show_data_points: if self.show_data_points:
etree.SubElement(self.graph, 'circle', { etree.SubElement(self.graph, 'circle', {
'cx': str(gx), 'cx': str(gx),
@ -330,7 +357,7 @@ class Plot(Graph):
'class': 'dataPoint%(line)s' % vars()}) 'class': 'dataPoint%(line)s' % vars()})
if self.show_data_values: if self.show_data_values:
self.add_popup(gx, gy, self.format(dx, dy)) self.add_popup(gx, gy, self.format(dx, dy))
self.make_datapoint_text(gx, gy-6, dy) self.make_datapoint_text(gx, gy - 6, dy)
def format(self, x, y): def format(self, x, y):
return '(%0.2f, %0.2f)' % (x,y) return '(%0.2f, %0.2f)' % (x, y)

50
svg/charts/schedule.py

@ -10,6 +10,7 @@ from util import grouper, date_range, divide_timedelta_float, TimeScale
__all__ = ('Schedule') __all__ = ('Schedule')
class Schedule(Graph): class Schedule(Graph):
""" """
# === For creating SVG plots of scalar temporal data # === For creating SVG plots of scalar temporal data
@ -138,11 +139,12 @@ class Schedule(Graph):
:title => 'Plays' :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. may be any date that is parseable by ParseDate.
Also note that, in this example, we're mixing scales; the data from d1 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 will probably not be discernable if both data sets are
graph, since d1 is too granular. plotted on the same graph, since d1 is too granular.
""" """
# The ruby version does something different here, throwing out # The ruby version does something different here, throwing out
# any previously added data. # any previously added data.
@ -151,7 +153,7 @@ class Schedule(Graph):
# copied from Bar # copied from Bar
# TODO, refactor this into a common base class (or mix-in) # TODO, refactor this into a common base class (or mix-in)
def get_bar_gap(self, field_size): def get_bar_gap(self, field_size):
bar_gap = 10 # default gap bar_gap = 10 # default gap
if field_size < 10: if field_size < 10:
# adjust for narrow fields # adjust for narrow fields
bar_gap = field_size / 2 bar_gap = field_size / 2
@ -219,9 +221,9 @@ class Schedule(Graph):
subbar_height = self.get_field_height() - bar_gap subbar_height = self.get_field_height() - bar_gap
y_mod = (subbar_height / 2) + (self.font_size / 2) y_mod = (subbar_height / 2) + (self.font_size / 2)
x_min,x_max,div = self._x_range() x_min, x_max, div = self._x_range()
x_range = x_max - x_min x_range = x_max - x_min
width = (float(self.graph_width) - self.font_size*2) width = (float(self.graph_width) - self.font_size * 2)
# time_scale # time_scale
#scale /= x_range #scale /= x_range
scale = TimeScale(width, x_range) scale = TimeScale(width, x_range)
@ -231,20 +233,19 @@ class Schedule(Graph):
data = self.data[last]['data'] data = self.data[last]['data']
for index, (x_start, x_end, label) in enumerate(data): for index, (x_start, x_end, label) in enumerate(data):
count = index + 1 # index is 0-based, count is 1-based count = index + 1 # index is 0-based, count is 1-based
y = self.graph_height - (self.get_field_height()*count) y = self.graph_height - (self.get_field_height() * count)
bar_width = scale*(x_end-x_start) bar_width = scale * (x_end - x_start)
bar_start = scale*(x_start-x_min) bar_start = scale * (x_start - x_min)
etree.SubElement(self.graph, 'rect', { etree.SubElement(self.graph, 'rect', {
'x': str(bar_start), 'x': str(bar_start),
'y': str(y), 'y': str(y),
'width': str(bar_width), 'width': str(bar_width),
'height': str(subbar_height), 'height': str(subbar_height),
'class': 'fill%s' % (count+1), 'class': 'fill%s' % (count + 1),
}) })
def _x_range(self): def _x_range(self):
# ruby version uses teh last data supplied # ruby version uses teh last data supplied
last = -1 last = -1
@ -257,7 +258,8 @@ class Schedule(Graph):
all_dates.append(self.min_x_value) all_dates.append(self.min_x_value)
min_value = min(all_dates) min_value = min(all_dates)
range = max_value - min_value 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_range = (max_value + right_pad) - min_value
#scale_division = self.scale_x_divisions or (scale_range / 10.0) #scale_division = self.scale_x_divisions or (scale_range / 10.0)
@ -277,14 +279,16 @@ class Schedule(Graph):
pattern = re.compile('(\d+) ?(\w+)') pattern = re.compile('(\d+) ?(\w+)')
m = pattern.match(self.timescale_divisions) m = pattern.match(self.timescale_divisions)
if not m: 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)) magnitude = int(m.group(1))
units = m.group(2) units = m.group(2)
parameter = self.lookup_relativedelta_parameter(units) parameter = self.lookup_relativedelta_parameter(units)
delta = relativedelta(**{parameter:magnitude}) delta = relativedelta(**{parameter: magnitude})
scale_division = delta scale_division = delta
@ -294,16 +298,16 @@ class Schedule(Graph):
from util import reverse_mapping, flatten_mapping from util import reverse_mapping, flatten_mapping
unit_string = unit_string.lower() unit_string = unit_string.lower()
mapping = dict( mapping = dict(
years = ('years', 'year', 'yrs', 'yr'), years=('years', 'year', 'yrs', 'yr'),
months = ('months', 'month', 'mo'), months=('months', 'month', 'mo'),
weeks = ('weeks', 'week', 'wks' ,'wk'), weeks=('weeks', 'week', 'wks', 'wk'),
days = ('days', 'day'), days=('days', 'day'),
hours = ('hours', 'hour', 'hr', 'hrs', 'h'), hours=('hours', 'hour', 'hr', 'hrs', 'h'),
minutes = ('minutes', 'minute', 'min', 'mins', 'm'), minutes=('minutes', 'minute', 'min', 'mins', 'm'),
seconds = ('seconds', 'second', 'sec', 'secs', 's'), seconds=('seconds', 'second', 'sec', 'secs', 's'),
) )
mapping = reverse_mapping(mapping) mapping = reverse_mapping(mapping)
mapping = flatten_mapping(mapping) mapping = flatten_mapping(mapping)
if not unit_string in 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] return mapping[unit_string]

54
svg/charts/time_series.py

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

40
svg/charts/util.py

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

91
tests/samples.py

@ -2,7 +2,8 @@
Samples of the various charts. Run this script to generate the reference Samples of the various charts. Run this script to generate the reference
samples. samples.
""" """
import sys, os import os
import sys
from svg.charts.plot import Plot from svg.charts.plot import Plot
from svg.charts import bar from svg.charts import bar
@ -11,6 +12,7 @@ from svg.charts import pie
from svg.charts import schedule from svg.charts import schedule
from svg.charts import line from svg.charts import line
def sample_Plot(): def sample_Plot():
g = Plot({ g = Plot({
'min_x_value': 0, 'min_x_value': 0,
@ -21,10 +23,11 @@ def sample_Plot():
'show_x_guidelines': True 'show_x_guidelines': True
}) })
g.add_data({'data': [1, 25, 2, 30, 3, 45], 'title': 'series 1'}) g.add_data({'data': [1, 25, 2, 30, 3, 45], 'title': 'series 1'})
g.add_data({'data': [1,30, 2, 31, 3, 40], 'title': 'series 2'}) g.add_data({'data': [1, 30, 2, 31, 3, 40], 'title': 'series 2'})
g.add_data({'data': [.5,35, 1, 20, 3, 10.5], 'title': 'series 3'}) g.add_data({'data': [.5, 35, 1, 20, 3, 10.5], 'title': 'series 3'})
return g return g
def sample_TimeSeries(): def sample_TimeSeries():
g = time_series.Plot({}) g = time_series.Plot({})
@ -33,10 +36,12 @@ def sample_TimeSeries():
g.x_label_format = '%d-%b %H:%M' g.x_label_format = '%d-%b %H:%M'
#g.max_y_value = 200 #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 return g
def generate_samples(): def generate_samples():
yield 'Plot', sample_Plot() yield 'Plot', sample_Plot()
yield 'TimeSeries', sample_TimeSeries() yield 'TimeSeries', sample_TimeSeries()
@ -47,6 +52,7 @@ def generate_samples():
yield 'Schedule', sample_Schedule() yield 'Schedule', sample_Schedule()
yield 'Line', sample_Line() yield 'Line', sample_Line()
class SampleBar: class SampleBar:
fields = ['Internet', 'TV', 'Newspaper', 'Magazine', 'Radio'] fields = ['Internet', 'TV', 'Newspaper', 'Magazine', 'Radio']
@ -57,7 +63,7 @@ class SampleBar:
g.stack = 'side' g.stack = 'side'
g.scale_integers = True g.scale_integers = True
g.width, g.height = 640,480 g.width, g.height = 640, 480
g.graph_title = 'Question 7' g.graph_title = 'Question 7'
g.show_graph_title = True g.show_graph_title = True
@ -72,7 +78,7 @@ class SampleBar:
g.stack = 'side' g.stack = 'side'
g.scale_integers = True g.scale_integers = True
g.width, g.height = 640,480 g.width, g.height = 640, 480
g.graph_title = 'Question 7' g.graph_title = 'Question 7'
g.show_graph_title = True g.show_graph_title = True
@ -94,27 +100,29 @@ class SampleBar:
no_css=False,) no_css=False,)
g.__dict__.update(options) g.__dict__.update(options)
g.add_data(dict(data=[2,22,98,143,82], title='intermediate')) g.add_data(dict(data=[2, 22, 98, 143, 82], title='intermediate'))
g.add_data(dict(data=[2,26,106,193,105], title='old')) g.add_data(dict(data=[2, 26, 106, 193, 105], title='old'))
return g return g
def sample_Line(): def sample_Line():
g = line.Line() g = line.Line()
options = dict( options = dict(
scale_integers = True, scale_integers=True,
area_fill = True, area_fill=True,
width = 640, width=640,
height = 480, height=480,
fields = SampleBar.fields, fields=SampleBar.fields,
graph_title = 'Question 7', graph_title='Question 7',
show_graph_title = True, show_graph_title=True,
no_css = False, no_css=False,
) )
g.__dict__.update(options) g.__dict__.update(options)
g.add_data({'data': [-2, 3, 1, 3, 1], 'title': 'Female'}) g.add_data({'data': [-2, 3, 1, 3, 1], 'title': 'Female'})
g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'}) g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
return g return g
def sample_Pie(): def sample_Pie():
g = pie.Pie({}) g = pie.Pie({})
options = dict( options = dict(
@ -122,14 +130,15 @@ def sample_Pie():
height=480, height=480,
fields=SampleBar.fields, fields=SampleBar.fields,
graph_title='Question 7', graph_title='Question 7',
expand_greatest = True, expand_greatest=True,
show_data_labels = True, show_data_labels=True,
) )
g.__dict__.update(options) g.__dict__.update(options)
g.add_data({'data': [-2, 3, 1, 3, 1], 'title': 'Female'}) g.add_data({'data': [-2, 3, 1, 3, 1], 'title': 'Female'})
g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'}) g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
return g return g
def sample_Schedule(): def sample_Schedule():
title = "Billy's Schedule" title = "Billy's Schedule"
data1 = [ data1 = [
@ -140,40 +149,40 @@ def sample_Schedule():
] ]
g = schedule.Schedule(dict( g = schedule.Schedule(dict(
width = 640, width=640,
height = 480, height=480,
graph_title = title, graph_title=title,
show_graph_title = True, show_graph_title=True,
key = False, key=False,
scale_x_integers = True, scale_x_integers=True,
scale_y_integers = True, scale_y_integers=True,
show_data_labels = True, show_data_labels=True,
show_y_guidelines = False, show_y_guidelines=False,
show_x_guidelines = True, show_x_guidelines=True,
# show_x_title = True, # not yet implemented # show_x_title=True, # not yet implemented
x_title = "Time", x_title="Time",
show_y_title = False, show_y_title=False,
rotate_x_labels = True, rotate_x_labels=True,
rotate_y_labels = False, rotate_y_labels=False,
x_label_format = "%m/%d", x_label_format="%m/%d",
timescale_divisions = "1 week", timescale_divisions="1 week",
add_popups = True, add_popups=True,
popup_format = "%m/%d/%y", popup_format="%m/%d/%y",
area_fill = True, area_fill=True,
min_y_value = 0, min_y_value=0,
)) ))
g.add_data(dict(data=data1, title="Data")) g.add_data(dict(data=data1, title="Data"))
return g return g
def save_samples(): def save_samples():
root = os.path.dirname(__file__) root = os.path.dirname(__file__)
for sample_name, sample in generate_samples(): for sample_name, sample in generate_samples():
res = sample.burn() res = sample.burn()
with open(os.path.join(root, sample_name+'.py.svg'), 'w') as f: with open(os.path.join(root, sample_name + '.py.svg'), 'w') as f:
f.write(res) f.write(res)
if __name__ == '__main__': if __name__ == '__main__':
save_samples() save_samples()

4
tests/test_plot.py

@ -1,6 +1,6 @@
import unittest import unittest
class PlotTester(unittest.TestCase): class PlotTester(unittest.TestCase):
def test_index_error_2010_04(self): def test_index_error_2010_04(self):
""" """
@ -12,7 +12,7 @@ class PlotTester(unittest.TestCase):
Credit to Jean for the test code as well. Credit to Jean for the test code as well.
""" """
from svg.charts.plot import Plot from svg.charts.plot import Plot
g = Plot(dict(scale_y_integers = True)) g = Plot(dict(scale_y_integers=True))
g.add_data(dict(data=[1, 0, 2, 1], title='foo')) g.add_data(dict(data=[1, 0, 2, 1], title='foo'))
res = g.burn() res = g.burn()

2
tests/test_samples.py

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

4
tests/test_time_series.py

@ -1,5 +1,6 @@
from svg.charts import time_series from svg.charts import time_series
def test_field_width(): def test_field_width():
""" """
cking reports in a comment on PyPI that the X-axis labels all 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.stagger_x_labels = True
g.x_label_format = '%d-%b %H:%M' 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() g.burn()
assert g.field_width() > 1 assert g.field_width() > 1

Loading…
Cancel
Save