update width-calculation for bar-charts
[mygpo.git] / mygpo / publisher / templatetags / pcharts.py
blob4c1259b80d2a9a191882585aeeff336227ceb321
1 from django import template
2 from django.utils.safestring import mark_safe
3 from django.utils.translation import ugettext as _
4 from mygpo.publisher.utils import colour_repr
5 from mygpo.utils import format_time
6 import hashlib
7 import math
9 register = template.Library()
11 @register.filter
12 def bar_chart(parts):
14 maxv = max([ int(x['y']) for x in parts ])
15 bar_width = 15
16 bar_space = 15
17 group_space = 20
19 parts = [
20 'cht=bvg', # Vertical bar chart with grouped bars.
21 'chs=%dx100' % ((bar_space + group_space) * (len(parts) + 1)),
22 'chl=%s' % '|'.join([x['x'] for x in parts]),
23 'chd=t:%s' % ','.join([ repr(int(x['y'])) for x in parts ]),
24 'chxt=x,y', # visible axes
25 'chbh=%d,%d,%d' % (bar_width, bar_space, group_space),
26 'chds=0,%d' % maxv, # avis scaling from 0 to max
27 'chxr=1,0,%d' % maxv, # labeling for axis 1 (y) from 0 to max
30 s = '<img src="http://chart.apis.google.com/chart?%s"' % '&'.join(parts)
32 return mark_safe(s)
34 @register.filter
35 def episode_heatmap_visualization(heatmap_data, step_length):
36 """
37 display a visual heatmap using the Google Charts API
39 heatmap_data is expected as an array of numbers of users that have
40 played this part part of the episode. the length of the parts is
41 indicated by step_length; the duration of the whole episode is
42 therefore approximated by len(heatmap_data) * step_length
43 """
44 label_steps = 2
45 # red yellow green
46 colours = ( (210, 54, 28), (239, 236, 22), (15, 212, 18) )
48 max_val = max(heatmap_data)
49 axis_pos = []
50 axis_label = []
51 part_colours = []
52 duration = len(heatmap_data) * step_length
54 n=0
55 for part in heatmap_data:
56 if n % label_steps == 0:
57 axis_pos.append(n*step_length)
58 axis_label.append(format_time(n*step_length))
59 rgb = colour_repr(part, max_val, colours)
60 part_colours.append('%02x%02x%02x' % rgb)
61 n += 1
63 parts = [
64 'cht=bhs', #bar chart
65 'chco=%s' % ','.join(part_colours), #colors
66 'chs=760x50', #width corresponds to length, arbitrary height
67 'chds=0,%s' % duration, #axis scaling from 0 to maximum duration
68 'chd=t:%s' % '|'.join([repr(step_length)] * len(heatmap_data)), # all block have the same width
69 'chxt=x', #visible axes
70 'chxr=0,0,%s' % duration, #axis range for axis 0 (x): 0 - duration
71 'chxl=0:|%s' % '|'.join(axis_label), #axis labels
72 'chxp=0,%s' % ','.join([repr(x) for x in axis_pos]), #axis label positions
75 s = '<img src="http://chart.apis.google.com/chart?%s"' % '&'.join(parts)
77 return mark_safe(s)