charts Package#

svg Package#

svg is a namespace package, meant to be shared with other libraries implementing svg functionality.

svg.charts Package#

svg.charts is the package containing the various modules of this library.

bar Module#

class svg.charts.bar.Bar(fields, *args, **kargs)#

Bases: Graph

Create presentation quality SVG bar graphs easily.

Synopsis:

from svg.charts import bar


fields = 'Jan Feb Mar'.split()
data_sales_02 = [12, 45, 21]

bc = bar.VerticalBar(fields, {'width': 300, 'height': 500})

bc.add_data({'data': data_sales_02, 'title': 'Sales 2002'})

print("Content-type: image/svg+xml\r\n\r\n")
print(bc.burn())

Description

This object aims to allow you to easily create high quality SVG bar graphs. You can either use the default style sheet or supply your own. Either way there are many options which can be configured to give you control over how the graph is generated - with or without a key, data elements at each point, title, subtitle etc.

Notes

The default stylesheet handles upto 12 data sets, if you use more you must create your own stylesheet and add the additional settings for the extra data sets. You will know if you go over 12 data sets as they will have no style and be in black.

Examples

See the example usage in tests/samples.py

See also

  • svg.charts.graph

  • svg.charts.line

  • svg.charts.pie

  • svg.charts.plot

  • svg.charts.time_series

bar_gap = True#

gap between bars

data_max()#
data_min()#
data_range()#
get_bar_gap(field_size)#
get_data_labels()#
get_data_values()#
get_field_labels()#
scale_divisions = None#
stack = 'overlap'#

how to stack adjacent dataset series

overlap - overlap bars with transparent colors top - stack bars on top of one another side - stack bars side-by-side

stylesheet_names = ['graph.css', 'bar.css']#
class svg.charts.bar.HorizontalBar(fields, *args, **kargs)#

Bases: Bar

draw_data()#
get_x_labels()#
get_y_labels()#
right_align = True#
right_font = True#
rotate_y_labels = True#
show_x_guidelines = True#
show_y_guidelines = False#
y_label_offset(height)#

Return an offset for drawing the y label. Currently returns 0.

class svg.charts.bar.VerticalBar(fields, *args, **kargs)#

Bases: Bar

draw_data()#
get_x_labels()#
get_y_labels()#
top_align = 1#
top_font = 1#
x_label_offset(width)#

Return an offset for drawing the x label. Currently returns 0.

css Module#

graph Module#

svg.charts.graph

The base module for svg.charts classes.

class svg.charts.graph.DrawHooks#

Bases: object

Mix-in for Graph subclasses providing hooks at various points in the rendering of a Graph.

Use with any Graph subclass like so:

class MyVerticalBar(DrawHooks, VerticalBar):
    def after_draw_data(self):
        self.root.append(...)
after_draw_data()#
before_draw_data()#
draw_data()#
class svg.charts.graph.Graph(config=None)#

Bases: object

Base object for generating SVG Graphs

Synopsis

This class is only used as a superclass of specialized charts. Do not attempt to use this class directly, unless creating a new chart type.

For examples of how to subclass this class, see the existing specific subclasses, such as svn.charts.Pie.

  • svg.charts.bar

  • svg.charts.line

  • svg.charts.pie

  • svg.charts.plot

  • svg.charts.time_series

KEY_BOX_SIZE = 12#
add_data(conf)#

Add data to the graph object. May be called several times to add additional data sets.

conf should be a dictionary including ‘data’ and ‘title’ keys

add_defs(defs)#

Override and place code to add defs here. TODO: what are defs?

add_popup(x, y, label)#

Add pop-up information to a point on the graph.

burn()#

Process the template with the data and config which has been set and return the resulting SVG.

Raises ValueError when no data set has been added to the graph object.

calculate_bottom_margin()#

Calculate the margin in pixels below the plot area, setting border_bottom.

calculate_graph_dimensions()#
calculate_left_margin()#

Calculates the margin to the left of the plot area, setting border_left.

calculate_offsets_bottom()#
calculate_right_margin()#

Calculate the margin in pixels to the right of the plot area, setting border_right.

calculate_top_margin()#

Calculate the margin in pixels above the plot area, setting border_top.

clear_data()#

This method removes all data from the object to create a new graph with the same config options.

css_inline = False#
draw_graph()#

The central logic for drawing the graph.

Sets self.graph (the ‘g’ element in the SVG root)

draw_graph_subtitle()#
draw_graph_title()#
draw_legend()#
draw_titles()#

Draws the graph title and subtitle

draw_x_guidelines(label_height, count)#

Draw the X-axis guidelines

draw_x_label(label)#
draw_x_labels()#

Draw the X axis labels

draw_x_title()#
draw_y_guidelines(label_height, count)#

Draw the Y-axis guidelines

draw_y_label(label)#
draw_y_labels()#

Draw the Y axis labels

draw_y_title()#
field_height()#
field_width()#
font_size = 12#
get_field_height()#
get_field_width()#
get_stylesheet()#
get_stylesheet_resources()#

Get the stylesheets for this instance

get_y_offset()#
graph_subtitle = 'Graph Subtitle'#
graph_title = 'Graph Title'#
height = 300#
key = True#
key_font_size = 10#
key_position = 'right'#
keys()#
load_config(config)#
static load_resource_stylesheet(name, subs=None)#
make_datapoint_text(x, y, value, style=None)#

Add text for a datapoint

max_y_label_width_px()#

Calculate the width of the widest Y label. This will be the character height if the Y labels are rotated.

min_scale_value = None#
parse_css()#

Take a .css file (classes only please) and parse it into a dictionary of class/style pairs.

process_data(data)#
static render(tree)#
render_inline_styles()#

Hard-code the styles into the SVG XML if style sheets are not used.

right_align = 0#
right_font = 0#
rotate_x_labels = False#
rotate_y_labels = False#
scale_integers = False#
show_data_values = True#
show_graph_subtitle = False#
show_graph_title = False#
show_x_guidelines = False#
show_x_labels = True#
show_x_title = False#
show_y_guidelines = True#
show_y_labels = True#
show_y_title = False#
stagger_x_labels = False#
stagger_y_labels = False#
start_svg()#

Base SVG Document Creation

step_include_first_x_label = True#
step_include_first_y_label = True#
step_x_labels = 1#
step_y_labels = 1#
stylesheet_names = ['graph.css']#
subtitle_font_size = 14#
title_font_size = 16#
top_align = 0#
top_font = 0#
validate_data(conf)#
width = 500#
x_label_font_size = 12#
x_label_offset(width)#

Return an offset for drawing the x label. Currently returns 0.

x_title = 'X Field names'#
x_title_font_size = 14#
y_label_font_size = 12#
y_label_offset(height)#

Return an offset for drawing the y label. Currently returns 0.

property y_offset#
y_title = 'Y Scale'#
y_title_font_size = 14#
y_title_text_direction = 'bt'#
class svg.charts.graph.class_dict(obj)#

Bases: object

Emulates a dictionary, but retrieves class attributes

keys()#

line Module#

class svg.charts.line.Line(config=None)#

Bases: Graph

Line Graph

area_fill = False#
calc_coords(field, value, width=None, height=None)#
calculate_left_margin()#

Calculates the margin to the left of the plot area, setting border_left.

draw_data()#
get_cumulative_data()#

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.

get_x_labels()#
get_y_label_values()#
get_y_labels()#
max_value()#
min_value()#
right_align = True#
right_font = True#
scale_divisions = None#
show_data_points = True#
show_data_values = True#

Accumulates each data set. (i.e. Each point increased by sum of all previous series at same point).

stacked = False#

Fill in the area under the plot

stylesheet_names = ['graph.css', 'plot.css']#
top_align = True#
top_font = True#

pie Module#

class svg.charts.pie.Pie(config=None)#

Bases: Graph

A presentation-quality SVG pie graph

Synopsis:

from svg.charts.pie import Pie
fields = ['Jan', 'Feb', 'Mar']

data_sales_02 = [12, 45, 21]

graph = Pie(dict(
    height = 500,
    width = 300,
    fields = fields))
graph.add_data({'data': data_sales_02, 'title': 'Sales 2002'})
print "Content-type" image/svg+xml

print graph.burn()

Description

This object aims to allow you to easily create high quality SVG pie graphs. You can either use the default style sheet or supply your own. Either way there are many options which can be configured to give you control over how the graph is generated - with or without a key, display percent on pie chart, title, subtitle etc.

add_data(data_descriptor)#

Add a data set to the graph

>>> graph.add_data({data:[1,2,3,4]}) 

Note that a ‘title’ key is ignored.

Multiple calls to add_data will sum the elements, and the pie will display the aggregated data. e.g.

>>> graph.add_data({data:[1,2,3,4]}) 
>>> graph.add_data({data:[2,3,5,7]}) 

is the same as:

>>> graph.add_data({data:[3,5,8,11]}) 

If data is added of with differing lengths, the corresponding values will be assumed to be zero.

>>> graph.add_data({data:[1,2,3,4]}) 
>>> graph.add_data({data:[5,7]}) 

is the same as:

>>> graph.add_data({data:[5,7]}) 
>>> graph.add_data({data:[1,2,3,4]}) 

and

>>> graph.add_data({data:[6,9,3,4]}) 
add_defs(defs)#

Add svg definitions

datapoint_font_size = 12#
draw_data()#
draw_graph()#

Here we don’t need the graph (consider refactoring)

expand_gap = 10#
expand_greatest = False#

The amount of space between expanded wedges

expanded = False#

If true, expand the largest pie wedge

get_x_labels()#

Okay. I’ll refactor after this

get_y_labels()#

Definitely consider refactoring

keys()#
round(val, to)#
shadow_offset = 10#
show_actual_values = False#

If true, display the percentage value of each pie wedge in the data labels

show_data_labels = False#

If true, display the actual field values in the data labels

show_key_actual_values = True#

If true, display the percentage value of the wedges in the key

show_key_data_labels = True#

If true, display the actual value of the field in the key

show_key_percent = False#

If true, explode the pie (put space between the wedges)

show_percent = True#

If true, display the labels in the key

show_shadow = True#

Sets the offset of the shadow from the pie chart

show_x_labels = False#
show_y_labels = False#

The font size of the data point labels

stylesheet_names = ['graph.css', 'pie.css']#
svg.charts.pie.robust_add(a, b)#

Add numbers a and b, treating None as 0

plot Module#

plot.py

class svg.charts.plot.Plot(config=None)#

Bases: Graph

An SVG plot of scalar data.

Synopsis:

from svg.charts import plot

# Data sets are x,y pairs
# Note that multiple data sets 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.
projection = [
    6, 11,  0, 5,  18, 7,  1, 11,  13, 9,  1, 2,  19, 0,  3, 13,  7, 9,
]
actual = [
    0, 18,  8, 15,  9, 4,  18, 14,  10, 2,  11, 6,  14, 12,  15, 6,
    4, 17,  2, 12,
]

p = plot.Plot(dict(
    height = 500,
    width = 300,
    key = true,
    scale_x_integers = True,
    scale_y_integerrs = True,
))

p.add_data({
    'data': projection,
    'title': 'Projected',
})

p.add_data({
    'data': actual,
    'title': 'Actual',
})

print(p.burn())

Description

Produces a graph of scalar data.

This object aims to allow you to easily create high quality SVG scalar plots. You can either use the default style sheet or supply your own. Either way there are many options which can be configured to give you control over how the graph is generated - with or without a key, data elements at each point, title, subtitle etc.

Examples

See the examples in tests/samples.py

Notes

The default stylesheet handles upto 10 data sets, if you use more you must create your own stylesheet and add the additional settings for the extra data sets. You will know if you go over 10 data sets as they will have no style and be in black.

Unlike the other types of charts, data sets must contain x,y pairs:

[1, 2]     # A data set with 1 point: (1,2)
[1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
add_constant_line(value, label=None, style=None)#
area_fill = False#

Fill the area under the line

calculate_left_margin()#

Calculates the margin to the left of the plot area, setting border_left.

calculate_right_margin()#

Calculate the margin in pixels to the right of the plot area, setting border_right.

data_max(axis)#
data_min(axis)#
data_range(axis)#
draw_data()#
draw_data_points(line, data_points, graph_points)#
draw_lines_between_points = True#

Indicate whether the lines should be drawn between points

field_height()#
field_size(axis)#
field_width()#
format(x, y)#
get_data_values(axis)#
get_graph_points(data_points)#
get_lpath(points)#
get_single_axis_values(axis, dataset)#

Return all the values for a single axis of the data.

get_x_labels()#
get_x_values()#
get_y_labels()#
get_y_values()#
load_transform_parameters()#

Cache the parameters necessary to transform x & y coordinates

max_x_value = None#

Set the maximum value of the X axis

max_y_value = None#

Set the maximum value of the Y axis

min_x_value = None#

Set the minimum value of the X axis

min_y_value = None#

Set the minimum value of the Y axis

process_data(data)#
right_align = 1#
right_font = 1#
property scale_x_divisions#

Determines the scaling for the X axis divisions.

graph.scale_x_divisions = 2

would cause the graph to attempt to generate labels stepped by 2; e.g.: 0,2,4,6,8…

scale_x_integers = False#

Make the X axis labels integers

scale_y_divisions = None#

Determines the scaling for the Y axis divisions:

Plot.scale_y_divisions = 0.5

would cause the graph to attempt to generate labels stepped by 0.5; e.g.: 0, 0.5, 1, 1.5, 2, …

scale_y_integers = False#

Make the Y axis labels integers

show_data_points = True#

Show a small circle on the graph where the line goes from one point to the next.

stacked = False#
stylesheet_names = ['graph.css', 'plot.css']#
top_align = 1#
top_font = 1#
transform_output_coordinates(point)#
validate_data(conf)#
validate_data_flat(series)#
validate_data_pairs(series)#
x_data_index = 0#
x_range()#
y_data_index = 1#
y_range()#

schedule Module#

class svg.charts.schedule.Schedule(config=None)#

Bases: Graph

Represents SVG plots of scalar temporal data

Synopsis:

from svg.charts import schedule

# Data sets are label, start, end triples.
data1 = [
    "Housesitting", "6/17/04", "6/19/04",
    "Summer Session", "6/15/04", "8/15/04",
]

sched = schedule.Schedule(dict(
    width = 640,
    height = 480,
    graph_title = "My Schedule",
    show_graph_title = True,
    no_css = True,
    scale_x_integers = True,
    scale_y_integers = True,
    min_x_value = 0,
    min_y_value = 0,
    show_data_labels = True,
    show_x_guidelines = True,
    show_x_title = True,
    x_title = "Time",
    stagger_x_labels = True,
    stagger_y_labels = True,
    x_label_format = "%m/%d/%y",
))

sched.add_data(dict(
    data = data1,
    title = 'Data',
))

print(sched.burn())

Description

Produces a graph of temporal scalar data.

Examples

See tests/samples.py for an example.

Notes

The default stylesheet handles upto 10 data sets, if you use more you must create your own stylesheet and add the additional settings for the extra data sets. You will know if you go over 10 data sets as they will have no style and be in black.

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)

add_data(data)#

Add data to the plot:

# A data set with 1 point: Lunch from 12:30 to 14:00
d1 = [ "Lunch", "12:30", "14:00" ]

# A data set with 2 points: "Cats" runs from 5/11/03 to 7/15/04, and
#                           "Henry V" runs from 6/12/03 to 8/20/03
d2 = [
    "Cats",    "5/11/03", "7/15/04",
    "Henry V", "6/12/03", "8/20/03",
]

sched.add_data(dict(
    data = d1,
    title = 'Meetings',
))
sched.add_data(dict(
    data = d2,
    title = 'Plays',
))

Note that the data must be in time,value pairs, and that the date format may be any date that is parseable by dateutil. 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.

bar_gap = True#
draw_data()#
format(x, y)#
get_bar_gap(field_size)#
get_min_x_value()#
get_x_labels()#
get_x_values()#
get_y_labels()#
classmethod lookup_relativedelta_parameter(unit_string)#
>>> lrp = Schedule.lookup_relativedelta_parameter
>>> lrp('Years')
'years'
>>> lrp('yr')
'years'
>>> lrp('s')
'seconds'
property min_x_value#
parse_date(date_string)#
popup_format = '%Y-%m-%d %H:%M:%S'#

The formatting used for the popups. See x_label_format

process_data(conf)#
scale_x_divisions = False#
scale_x_integers = False#
set_min_x_value(value)#
stylesheet_names = ['graph.css', 'bar.css']#
timescale_divisions = None#

Use this to set the spacing between dates on the axis. The value must be of the form “d+ ?((year|month|week|day|hour|minute|second)s?)?”

e.g.

graph.timescale_divisions = ‘2 weeks’ graph.timescale_divisions = ‘1 month’ graph.timescale_divisions = ‘3600 seconds’ # easier would be ‘1 hour’

validate_data(conf)#
x_label_format = '%Y-%m-%d %H:%M:%S'#

The format string to be used to format the X axis labels

y_label_offset(height)#

Return an offset for drawing the y label. Currently returns 0.

time_series Module#

class svg.charts.time_series.Plot(config=None)#

Bases: Plot

For creating SVG plots of scalar temporal data

Synopsis:

from svg.charts import time_series

# 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]
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/84", 17,
    "10/1/80", 12]

ts = time_series.Plot(dict(
    width = 640,
    height = 480,
    graph_title = "TS Title",
    show_graph_title = True,
    no_css = True,
    key = True,
    scale_x_integers = True,
    scale_y_integers = True,
    min_x_value = 0,
    min_y_value = 0,
    show_data_labels = True,
    show_x_guidelines = True,
    show_x_title = True,
    x_title = "Time",
    show_y_title = True,
    y_title = "Ice Cream Cones",
    y_title_text_direction = 'bt',
    stagger_x_labels = True,
    x_label_format = "%m/%d/%y",
))

ts.add_data(dict(
    data = projection,
    title = 'Projected',
))

ts.add_data(dict(
    data = actual,
    title = 'Actual',
))

print(ts.burn())

Description

Produces a graph of temporal scalar data.

Examples

See tests/samples.py for an example.

Notes

The default stylesheet handles upto 10 data sets, if you use more you must create your own stylesheet and add the additional settings for the extra data sets. You will know if you go over 10 data sets as they will have no style and be in black.

Unlike the other types of charts, data sets must contain x,y pairs:

# A data set with 1 point: ("12:30", 2)
["12:30", 2]
# A data set with 2 points: ("01:00", 2) and
#                           ("14:20", 6)
["01:00", 2, "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.

The dates must be parseable by ParseDate, but otherwise can be any order of magnitude (seconds within the hour, or years)

add_data(data)#

Add data to the plot:

# A data set with 1 point: ("12:30", 2)
d1 = ["12:30", 2]

# A data set with 2 points: ("01:00", 2) and
#                           ("14:20", 6)
d2 = ["01:00", 2, "14:20", 6]

graph.add_data(
    data = d1,
    title = 'One',
)
graph.add_data(
    data = d2,
    title = 'Two',
)

Note that the data must be in (time, value) pairs, and the date format may be any date that is parseable by dateutil.

format(x, y)#
get_min_x_value()#
get_time_range(start, stop, delta)#
get_x_labels()#
get_x_timescale_division_values()#
get_x_values()#
property min_x_value#
parse_date(date_string)#
popup_format = '%Y-%m-%d %H:%M:%S'#

The formatting usped for the popups. See x_label_format

process_data(data)#
set_min_x_value(date)#
timescale_divisions = None#

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)?”

For example:

ts.timescale_divisions = “2 weeks”

will cause the chart to try to divide the X axis up into segments of two week periods.

x_label_format = '%Y-%m-%d %H:%M:%S'#
svg.charts.time_series.fromtimestamp()#

timestamp[, tz] -> tz’s local time from POSIX timestamp.

util Module#

svg.charts.util.flatten_mapping(mapping)#

For every key that has an __iter__ method, assign the values to a key for each.

>>> flatten_mapping({'ab': 3, ('c','d'): 4}) == {'ab': 3, 'c': 4, 'd': 4}
True
svg.charts.util.float_range(start=0, stop=None, step=1)#

Much like the built-in function range, but accepts floats

>>> tuple(float_range(0, 9, 1.5))
(0.0, 1.5, 3.0, 4.5, 6.0, 7.5)
svg.charts.util.reverse_mapping(mapping)#

For every key, value pair, return the mapping for the equivalent value, key pair

>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True