summaryrefslogtreecommitdiff
path: root/pngchart.py
blob: 5428718a88a0f1ed47e19c9046d09d213c7c408d (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from pngcanvas import PNGCanvas

try:
    from itertools import izip as zip
except ImportError:
    pass

class SimpleLineChart(object):
    def __init__(self, width, height, colours=None, legend=None):
        self.canvas = PNGCanvas(width, height)

        self.width = width
        self.height = height

        self.colours = colours
        self.legend = legend

        self.series = []

    def add_data(self, series):
        self.series.append(series)

    def render(self):
        max_width = max(map(len, self.series))
        max_height = max(map(max, self.series))
        x_scale = float(self.width) / max_width
        y_scale = float(self.height) / max_height

        data = zip(self.series, self.colours or [], self.legend or [])
        for series, colour, legend in data:
            colour = int(colour, 16)
            self.canvas.color = (
                colour>>16 & 0xff,
                colour>>8 & 0xff,
                colour & 0xff,
                0xff,
            )
            last = None
            for x, y in enumerate(series):
                if y is not None:
                    y = self.height - y * y_scale
                    if last is not None:
                        x *= x_scale
                        self.canvas.line(x - x_scale, last, x, y)
                last = y

    def download(self, filename):
        self.render()

        f = open(filename, 'wb')
        f.write(self.canvas.dump())
        f.close()