Browse Source

Pep8

pull/8/head
Florian Mounier 13 years ago
parent
commit
9b4b240eb3
  1. 23
      docs/conf.py
  2. 34
      setup.py
  3. 39
      svg/charts/bar.py
  4. 24
      svg/charts/css.py
  5. 224
      svg/charts/graph.py
  6. 39
      svg/charts/line.py
  7. 57
      svg/charts/pie.py
  8. 91
      svg/charts/plot.py
  9. 46
      svg/charts/schedule.py
  10. 50
      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
# 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'),

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

39
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,7 +77,8 @@ class Bar(Graph):
bar_gap = int(self.bar_gap) * 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"
while start < stop:
yield float(start)
@ -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())
@ -156,9 +162,9 @@ class VerticalBar(Bar):
if self.stack == 'side':
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':
x_mod -= bar_width/2
x_mod -= bar_width / 2
bottom = self.graph_height
@ -175,7 +181,7 @@ class VerticalBar(Bar):
length = (abs(value) - max(min_value, 0)) * unit_size
# 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':
left += bar_width * dataset_count
@ -184,10 +190,12 @@ class VerticalBar(Bar):
'y': str(top),
'width': str(bar_width),
'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):
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()
@ -209,7 +216,7 @@ class HorizontalBar(Bar):
min_value = self.data_min()
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())
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):
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):
@ -241,8 +249,9 @@ class HorizontalBar(Bar):
'y': str(top),
'width': str(length),
'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(
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',

224
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
@ -47,46 +51,48 @@ class Graph(object):
* svg.charts.time_series
"""
width= 500
height= 300
show_x_guidelines= False
show_y_guidelines= True
show_data_values= True
min_scale_value= None
show_x_labels= True
stagger_x_labels= False
rotate_x_labels= False
step_x_labels= 1
step_include_first_x_label= True
show_y_labels= True
rotate_y_labels= False
stagger_y_labels= False
step_include_first_y_label= True
step_y_labels= 1
scale_integers= False
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
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',
font_size= 12
title_font_size= 16
subtitle_font_size= 14
x_label_font_size= 12
x_title_font_size= 14
y_label_font_size= 12
y_title_font_size= 14
key_font_size= 10
css_inline= False
add_popups= False
width = 500
height = 300
show_x_guidelines = False
show_y_guidelines = True
show_data_values = True
min_scale_value = None
show_x_labels = True
stagger_x_labels = False
rotate_x_labels = False
step_x_labels = 1
step_include_first_x_label = True
show_y_labels = True
rotate_y_labels = False
stagger_y_labels = False
step_include_first_y_label = True
step_y_labels = 1
scale_integers = False
show_x_title = False
x_title = 'X Field names'
show_y_title = False
# '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
# 'bottom' or 'right',
key_position = 'right'
font_size = 12
title_font_size = 16
subtitle_font_size = 14
x_label_font_size = 12
x_title_font_size = 14
y_label_font_size = 12
y_title_font_size = 14
key_font_size = 10
css_inline = False
add_popups = False
top_align = top_font = right_align = right_font = 0
@ -94,7 +100,7 @@ class Graph(object):
stylesheet_names = ['graph.css']
def __init__(self, config = {}):
def __init__(self, config={}):
"""Initialize the graph object with the graph settings."""
if self.__class__ is Graph:
raise NotImplementedError("Graph is an abstract base class")
@ -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,17 +240,19 @@ 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):
"""
Add pop-up information to a point on the graph.
"""
txt_width = len(label) * self.font_size * 0.6 + 10
tx = x + [5,-5][int(x+txt_width > self.width)]
anchor = ['start', 'end'][x+txt_width > self.width]
tx = x + [5, -5][int(x + txt_width > self.width)]
anchor = ['start', 'end'][x + txt_width > self.width]
style = 'fill: #000; text-anchor: %s;' % anchor
id = 'label-%s' % label
t = etree.SubElement(self.foreground, 'text', {
@ -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"
@ -374,7 +398,7 @@ class Graph(object):
if self.rotate_x_labels:
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('style', 'text-anchor: start')
else:
@ -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)
@ -425,7 +451,7 @@ class Graph(object):
text.text = label
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):
stagger = self.y_label_font_size + 5
@ -444,15 +470,16 @@ class Graph(object):
text.set('transform', transform)
text.set('style', 'text-anchor: middle')
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')
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
for count in range(1, count):
start = label_height * count
stop = self.graph_height
path = etree.SubElement(self.graph, 'path', {
'd': 'M %(start)s 0 v%(stop)s' % vars(),
@ -460,9 +487,10 @@ 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
start = self.graph_height - label_height * count
stop = self.graph_width
path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % vars(),
@ -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,10 +515,11 @@ 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),
'x': str(self.width / 2),
'y': str(y_subtitle),
'class': 'subTitle',
})
@ -495,8 +528,9 @@ class Graph(object):
def draw_x_title(self):
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
y_size = self.x_label_font_size + 5
if self.stagger_x_labels:
y_size *= 2
y += y_size
x = self.width / 2
@ -509,7 +543,7 @@ class Graph(object):
def draw_y_title(self):
x = self.y_title_font_size
if self.y_title_text_direction=='bt':
if self.y_title_text_direction == 'bt':
x += 3
rotate = -90
else:
@ -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):
@ -612,11 +646,12 @@ class Graph(object):
'xlink': 'http://www.w3.org/1999/xlink',
'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),
'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(
@ -630,7 +665,7 @@ class Graph(object):
' SVG.Graph by Jason R. Coombs ',
' Based on SVG::Graph by Sean E. Russel ',
' Based on Perl SVG:TT:Graph by Leo Lapworth & Stephan Morgan ',
' '+'/'*66,
' ' + '/' * 66,
)
map(self.root.append, map(etree.Comment, comment_strings))
@ -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):

39
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:
@ -82,18 +84,20 @@ class Line(Graph):
def get_y_labels(self):
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
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
coords = dict(
x = width * field,
y = self.graph_height - value * height,
x=width * field,
y=self.graph_height - value * height,
)
return coords
def draw_data(self):
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_span = max(y_label_values) - min(y_label_values)
@ -102,15 +106,16 @@ class Line(Graph):
field_width = self.field_width()
#line = len(self.data)
prev_sum = [0]*len(self.fields)
cum_sum = [-min_value]*len(self.fields)
prev_sum = [0] * len(self.fields)
cum_sum = [-min_value] * len(self.fields)
coord_format = lambda c: '%(x)s %(y)s' % c
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,
@ -132,7 +137,7 @@ class Line(Graph):
origin = paths[-1]
else:
area_path = "V%(graph_height)s" % vars(self)
origin = coord_format(get_coords((0,0)))
origin = coord_format(get_coords((0, 0)))
d = ' '.join((
'M',
@ -160,13 +165,13 @@ class Line(Graph):
self.graph,
'circle',
{'class': 'dataPoint%(line_n)s' % vars()},
cx = str(field_width*i),
cy = str(self.graph_height - value*field_height),
r = '2.5',
cx=str(field_width * i),
cy=str(self.graph_height - value * field_height),
r='2.5',
)
self.make_datapoint_text(
field_width*i,
self.graph_height - value*field_height - 6,
field_width * i,
self.graph_height - value * field_height - 6,
value + min_value
)

57
svg/charts/pie.py

@ -3,13 +3,17 @@ import itertools
from lxml import etree
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"
if a is None: a = 0
if b is None: b = 0
return a+b
if a is None:
a = 0
if b is None:
b = 0
return a + b
RADIANS = math.pi / 180
RADIANS = math.pi/180
class 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)
@ -184,12 +192,12 @@ class Pie(Graph):
percent = percent_scale * value
radians = prev_percent * rad_mult
x_start = radius+(math.sin(radians) * radius)
y_start = radius-(math.cos(radians) * radius)
radians = (prev_percent+percent) * rad_mult
x_end = radius+(math.sin(radians) * radius)
y_end = radius-(math.cos(radians) * radius)
percent_greater_fifty = int(percent>=50)
x_start = radius + (math.sin(radians) * radius)
y_start = radius - (math.cos(radians) * radius)
radians = (prev_percent + percent) * rad_mult
x_end = radius + (math.sin(radians) * radius)
y_end = radius - (math.cos(radians) * radius)
percent_greater_fifty = int(percent >= 50)
path = ' '.join((
"M%(radius)s,%(radius)s",
"L%(x_start)s,%(y_start)s",
@ -204,7 +212,7 @@ class Pie(Graph):
'path',
{
'd': path,
'class': 'fill%s' % (index+1),
'class': 'fill%s' % (index + 1),
}
)
@ -258,9 +266,10 @@ class Pie(Graph):
msr = math.sin(radians)
mcr = math.cos(radians)
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 (
self.expand_greatest and value == max_value):
tx += (msr * self.expand_gap)
ty -= (mcr * self.expand_gap)
@ -268,10 +277,10 @@ class Pie(Graph):
self.foreground,
'text',
{
'x':str(tx),
'y':str(ty),
'class':'dataPointLabel',
'style':'stroke: #fff; stroke-width: 2;',
'x': str(tx),
'y': str(ty),
'class': 'dataPointLabel',
'style': 'stroke: #fff; stroke-width: 2;'
}
)
label_node.text = label
@ -280,8 +289,8 @@ class Pie(Graph):
self.foreground,
'text',
{
'x':str(tx),
'y':str(ty),
'x': str(tx),
'y': str(ty),
'class': 'dataPointLabel',
}
)
@ -290,4 +299,4 @@ class Pie(Graph):
prev_percent += percent
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
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', {
@ -265,7 +291,7 @@ class Plot(Graph):
self._draw_constant_lines()
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.append((value, label, style))
@ -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']
@ -307,7 +333,7 @@ class Plot(Graph):
points = map(lambda p: "%f %f" % p, 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_step = self.__transform_parameters['x_step']
y_min = self.__transform_parameters['y_min']
@ -316,12 +342,13 @@ class Plot(Graph):
#vars().update(self.__transform_parameters)
x = (x - x_min) * x_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):
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 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', {
'cx': str(gx),
@ -330,7 +357,7 @@ class Plot(Graph):
'class': 'dataPoint%(line)s' % vars()})
if self.show_data_values:
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):
return '(%0.2f, %0.2f)' % (x,y)
return '(%0.2f, %0.2f)' % (x, y)

46
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.
@ -219,9 +221,9 @@ class Schedule(Graph):
subbar_height = self.get_field_height() - bar_gap
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
width = (float(self.graph_width) - self.font_size*2)
width = (float(self.graph_width) - self.font_size * 2)
# time_scale
#scale /= x_range
scale = TimeScale(width, x_range)
@ -232,19 +234,18 @@ class Schedule(Graph):
for index, (x_start, x_end, label) in enumerate(data):
count = index + 1 # index is 0-based, count is 1-based
y = self.graph_height - (self.get_field_height()*count)
bar_width = scale*(x_end-x_start)
bar_start = scale*(x_start-x_min)
y = self.graph_height - (self.get_field_height() * count)
bar_width = scale * (x_end - x_start)
bar_start = scale * (x_start - x_min)
etree.SubElement(self.graph, 'rect', {
'x': str(bar_start),
'y': str(y),
'width': str(bar_width),
'height': str(subbar_height),
'class': 'fill%s' % (count+1),
'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,14 +279,16 @@ 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)
parameter = self.lookup_relativedelta_parameter(units)
delta = relativedelta(**{parameter:magnitude})
delta = relativedelta(**{parameter: magnitude})
scale_division = delta
@ -294,16 +298,16 @@ class Schedule(Graph):
from util import reverse_mapping, flatten_mapping
unit_string = unit_string.lower()
mapping = dict(
years = ('years', 'year', 'yrs', 'yr'),
months = ('months', 'month', 'mo'),
weeks = ('weeks', 'week', 'wks' ,'wk'),
days = ('days', 'day'),
hours = ('hours', 'hour', 'hr', 'hrs', 'h'),
minutes = ('minutes', 'minute', 'min', 'mins', 'm'),
seconds = ('seconds', 'second', 'sec', 'secs', 's'),
years=('years', 'year', 'yrs', 'yr'),
months=('months', 'month', 'mo'),
weeks=('weeks', 'week', 'wks', 'wk'),
days=('days', 'day'),
hours=('hours', 'hour', 'hr', 'hrs', 'h'),
minutes=('minutes', 'minute', 'min', 'mins', 'm'),
seconds=('seconds', 'second', 'sec', 'secs', 's'),
)
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

40
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):
"""
@ -80,14 +91,16 @@ def divide_timedelta_float(td, divisor):
"""
# td is comprised of 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)
def get_timedelta_total_microseconds(td):
seconds = td.days*86400 + td.seconds
microseconds = td.microseconds + seconds*(10**6)
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
@ -99,7 +112,8 @@ def divide_timedelta(td1, td2):
td1_total = float(get_timedelta_total_microseconds(td1))
td2_total = float(get_timedelta_total_microseconds(td2))
return td1_total/td2_total
return td1_total / td2_total
class TimeScale(object):
"Describes a scale factor based on time instead of a scalar"
@ -109,10 +123,10 @@ class TimeScale(object):
def __mul__(self, delta):
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
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))

91
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,
@ -21,10 +23,11 @@ def sample_Plot():
'show_x_guidelines': True
})
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': [.5,35, 1, 20, 3, 10.5], 'title': 'series 3'})
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'})
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']
@ -57,7 +63,7 @@ class SampleBar:
g.stack = 'side'
g.scale_integers = True
g.width, g.height = 640,480
g.width, g.height = 640, 480
g.graph_title = 'Question 7'
g.show_graph_title = True
@ -72,7 +78,7 @@ class SampleBar:
g.stack = 'side'
g.scale_integers = True
g.width, g.height = 640,480
g.width, g.height = 640, 480
g.graph_title = 'Question 7'
g.show_graph_title = True
@ -94,27 +100,29 @@ class SampleBar:
no_css=False,)
g.__dict__.update(options)
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, 22, 98, 143, 82], title='intermediate'))
g.add_data(dict(data=[2, 26, 106, 193, 105], title='old'))
return g
def sample_Line():
g = line.Line()
options = dict(
scale_integers = True,
area_fill = True,
width = 640,
height = 480,
fields = SampleBar.fields,
graph_title = 'Question 7',
show_graph_title = True,
no_css = False,
scale_integers=True,
area_fill=True,
width=640,
height=480,
fields=SampleBar.fields,
graph_title='Question 7',
show_graph_title=True,
no_css=False,
)
g.__dict__.update(options)
g.add_data({'data': [-2, 3, 1, 3, 1], 'title': 'Female'})
g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
return g
def sample_Pie():
g = pie.Pie({})
options = dict(
@ -122,14 +130,15 @@ def sample_Pie():
height=480,
fields=SampleBar.fields,
graph_title='Question 7',
expand_greatest = True,
show_data_labels = True,
expand_greatest=True,
show_data_labels=True,
)
g.__dict__.update(options)
g.add_data({'data': [-2, 3, 1, 3, 1], 'title': 'Female'})
g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
return g
def sample_Schedule():
title = "Billy's Schedule"
data1 = [
@ -140,40 +149,40 @@ def sample_Schedule():
]
g = schedule.Schedule(dict(
width = 640,
height = 480,
graph_title = title,
show_graph_title = True,
key = False,
scale_x_integers = True,
scale_y_integers = True,
show_data_labels = True,
show_y_guidelines = False,
show_x_guidelines = True,
# show_x_title = True, # not yet implemented
x_title = "Time",
show_y_title = False,
rotate_x_labels = True,
rotate_y_labels = False,
x_label_format = "%m/%d",
timescale_divisions = "1 week",
add_popups = True,
popup_format = "%m/%d/%y",
area_fill = True,
min_y_value = 0,
width=640,
height=480,
graph_title=title,
show_graph_title=True,
key=False,
scale_x_integers=True,
scale_y_integers=True,
show_data_labels=True,
show_y_guidelines=False,
show_x_guidelines=True,
# show_x_title=True, # not yet implemented
x_title="Time",
show_y_title=False,
rotate_x_labels=True,
rotate_y_labels=False,
x_label_format="%m/%d",
timescale_divisions="1 week",
add_popups=True,
popup_format="%m/%d/%y",
area_fill=True,
min_y_value=0,
))
g.add_data(dict(data=data1, title="Data"))
return g
def save_samples():
root = os.path.dirname(__file__)
for sample_name, sample in generate_samples():
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)
if __name__ == '__main__':
save_samples()

4
tests/test_plot.py

@ -1,6 +1,6 @@
import unittest
class PlotTester(unittest.TestCase):
def test_index_error_2010_04(self):
"""
@ -12,7 +12,7 @@ class PlotTester(unittest.TestCase):
Credit to Jean for the test code as well.
"""
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'))
res = g.burn()

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