Skip to content

Commit 2c65359

Browse files
author
Brian Luft
committed
adds add_time_series convenience method for passing series with datetimes
1 parent d3af64e commit 2c65359

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

pyflot/__init__.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from functools import partial
33
import inspect
44
import json
5+
import time
56

67

78
def update(d, u):
@@ -100,4 +101,19 @@ def add_series(self, series, label=None, **kwargs):
100101
new_series.update({line_type: kwargs[line_type]})
101102
self._series.append(new_series)
102103

104+
def add_time_series(self, series, label=None, **kwargs):
105+
"""
106+
A specialized form of ``add_series`` for adding time-series data.
107+
108+
Flot requires times to be specified in Javascript timestamp format.
109+
This convenience function lets you pass datetime instances and handles
110+
the conversion. It also sets the correct option to indicate to ``flot``
111+
that the graph should be treated as a time series
112+
"""
113+
_series = [(time.mktime(ts.timetuple()) * 1000, val) \
114+
for ts, val in series]
115+
self._options['xaxis'] = {'mode': 'time'}
116+
return self.add_series(_series, label, **kwargs)
117+
118+
103119

tests/__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from datetime import date, timedelta
12
import json
23
import unittest
34

@@ -79,6 +80,25 @@ def test_series_with_label_json(self):
7980
self.flot.add_series(S1, 'label1')
8081
self.assertEqual(json.dumps([series]), self.flot.series_json)
8182

83+
def test_add_time_series(self):
84+
"""
85+
make sure adding time series works properly:
86+
87+
* conversion to JS timestamp
88+
* time series mode added to options
89+
"""
90+
time_series = [(date(2010, 3, 14) - timedelta(days=i), i) \
91+
for i in range(5)]
92+
self.flot.add_time_series(time_series)
93+
self.assertEqual(self.flot._series[0]['data'],
94+
[(1268553600000.0, 0),
95+
(1268467200000.0, 1),
96+
(1268380800000.0, 2),
97+
(1268294400000.0, 3),
98+
(1268208000000.0, 4)])
99+
self.assertEqual(self.flot._options['xaxis'],
100+
{'mode': 'time'})
101+
82102
def test_empty_options_json(self):
83103
"make sure conversion to JSON works for default options"
84104
self.assertEqual("{}", self.flot.options_json)

0 commit comments

Comments
 (0)