forked from wfrog/wfrog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyquickchart.py
2028 lines (1690 loc) · 75.2 KB
/
pyquickchart.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
pyquickchart - An incomplete Python wrapper for the QuickChart
replacement for the Google Chart API
Copyright 2019 Mark Blinkhorn
Big chunks stolen from Gerald Kaszuba (PyGoogleChart)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# unnecessary on Python3, but harmless
from __future__ import division
import os
import math
import random
import re
import warnings
import copy
import json
try:
# we're on Python3
from urllib.request import urlopen
from urllib.parse import quote
except ImportError:
# we're on Python2.x
from urllib2 import urlopen
from urllib import quote
# Helper variables and functions
# -----------------------------------------------------------------------------
__version__ = '0.1.0'
__author__ = 'Mark Blinkhorn'
#reo_colour = re.compile('^([A-Fa-f0-9]{2,2}){3,4}$')
#def _check_colour(colour):
# if not reo_colour.match(colour):
# raise InvalidParametersException('Colours need to be in ' \
# 'RRGGBB or RRGGBBAA format. One of your colours has %s' % \
# colour)
#def _reset_warnings():
# """Helper function to reset all warnings. Used by the unit tests."""
# globals()['__warningregistry__'] = None
# Exception Classes
# -----------------------------------------------------------------------------
class PyGoogleChartException(Exception):
pass
class DataOutOfRangeException(PyGoogleChartException):
pass
class UnknownDataTypeException(PyGoogleChartException):
pass
class NoDataGivenException(PyGoogleChartException):
pass
class InvalidParametersException(PyGoogleChartException):
pass
class BadContentTypeException(PyGoogleChartException):
pass
class AbstractClassException(PyGoogleChartException):
pass
class UnknownChartType(PyGoogleChartException):
pass
class UnknownCountryCodeException(PyGoogleChartException):
pass
class IndexOutOfRangeException(PyGoogleChartException):
pass
class JsonPostException(PyGoogleChartException):
print(repr(PyGoogleChartException))
# Data Classes
# -----------------------------------------------------------------------------
"""
class Data(object):
def __init__(self, data):
if type(self) == Data:
raise AbstractClassException('This is an abstract class')
self.data = data
@classmethod
def float_scale_value(cls, value, range):
lower, upper = range
assert(upper > lower)
scaled = (value - lower) * (cls.max_value / (upper - lower))
return scaled
@classmethod
def clip_value(cls, value):
return max(0, min(value, cls.max_value))
@classmethod
def int_scale_value(cls, value, range):
return int(round(cls.float_scale_value(value, range)))
@classmethod
def scale_value(cls, value, range):
scaled = cls.int_scale_value(value, range)
clipped = cls.clip_value(scaled)
Data.check_clip(scaled, clipped)
return clipped
@staticmethod
def check_clip(scaled, clipped):
if clipped != scaled:
warnings.warn('One or more of of your data points has been '
'clipped because it is out of range.')
class SimpleData(Data):
max_value = 61
enc_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
def __repr__(self):
encoded_data = []
for data in self.data:
sub_data = []
for value in data:
if value is None:
sub_data.append('_')
elif value >= 0 and value <= self.max_value:
sub_data.append(SimpleData.enc_map[value])
else:
raise DataOutOfRangeException('cannot encode value: %d'
% value)
encoded_data.append(''.join(sub_data))
return 'chd=s:' + ','.join(encoded_data)
class TextData(Data):
max_value = 100
def __repr__(self):
encoded_data = []
for data in self.data:
sub_data = []
for value in data:
if value is None:
sub_data.append(-1)
elif value >= 0 and value <= self.max_value:
sub_data.append("%.1f" % float(value))
else:
raise DataOutOfRangeException()
encoded_data.append(','.join(sub_data))
return 'chd=t:' + '%7c'.join(encoded_data)
@classmethod
def scale_value(cls, value, range):
# use float values instead of integers because we don't need an encode
# map index
scaled = cls.float_scale_value(value, range)
clipped = cls.clip_value(scaled)
Data.check_clip(scaled, clipped)
return clipped
class ExtendedData(Data):
max_value = 4095
enc_map = \
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.'
def __repr__(self):
encoded_data = []
enc_size = len(ExtendedData.enc_map)
for data in self.data:
sub_data = []
for value in data:
if value is None:
sub_data.append('__')
elif value >= 0 and value <= self.max_value:
first, second = divmod(int(value), enc_size)
sub_data.append('%s%s' % (
ExtendedData.enc_map[first],
ExtendedData.enc_map[second]))
else:
raise DataOutOfRangeException( \
'Item #%i "%s" is out of range' % (data.index(value), \
value))
encoded_data.append(''.join(sub_data))
return 'chd=e:' + ','.join(encoded_data)
class AwesomeData(Data):
max_value = 4095
def __repr__(self):
encoded_data = []
for data in self.data:
sub_data = []
for value in data:
if value is None:
sub_data.append('_')
else:
sub_data.append("%.1f" % float(value))
encoded_data.append(','.join(sub_data))
return 'chd=a:' + '%7c'.join(encoded_data)
# encoded_data.append(''.join(sub_data))
# return 'chd=a:' + ','.join(encoded_data)
# raise DataOutOfRangeException( \
# 'Item #%i "%s" is out of range' % (data.index(value), value))
"""
# Axis Classes
# -----------------------------------------------------------------------------
"""
class Axis(object):
BOTTOM = 'x'
TOP = 't'
LEFT = 'y'
RIGHT = 'r'
TYPES = (BOTTOM, TOP, LEFT, RIGHT)
def __init__(self, axis_index, axis_type, **kw):
assert(axis_type in Axis.TYPES)
self.has_style = False
self.axis_index = axis_index
self.axis_type = axis_type
self.positions = None
def set_index(self, axis_index):
self.axis_index = axis_index
def set_positions(self, positions):
self.positions = positions
def set_style(self, colour, font_size=None, alignment=None):
_check_colour(colour)
self.colour = colour
self.font_size = font_size
self.alignment = alignment
self.has_style = True
def style_to_url(self):
bits = []
bits.append(str(self.axis_index))
bits.append(self.colour)
if self.font_size is not None:
bits.append(str(self.font_size))
if self.alignment is not None:
bits.append(str(self.alignment))
return ','.join(bits)
def positions_to_url(self):
bits = []
bits.append(str(self.axis_index))
bits += [str(a) for a in self.positions]
return ','.join(bits)
class LabelAxis(Axis):
def __init__(self, axis_index, axis_type, values, **kwargs):
Axis.__init__(self, axis_index, axis_type, **kwargs)
self.values = [str(a) for a in values]
def __repr__(self):
return '%i:%%7c%s' % (self.axis_index, '%7c'.join(self.values))
class RangeAxis(Axis):
def __init__(self, axis_index, axis_type, low, high, **kwargs):
Axis.__init__(self, axis_index, axis_type, **kwargs)
self.low = low
self.high = high
def __repr__(self):
return '%i,%s,%s' % (self.axis_index, self.low, self.high)
"""
# Chart Classes
# -----------------------------------------------------------------------------
class Chart(object):
"""Abstract class for all chart types.
width are height specify the dimensions of the image. title sets the title
of the chart. legend requires a list that corresponds to datasets.
"""
#BASE_URL = 'https://chart.googleapis.com/chart'
#BASE_URL = 'https://image-charts.com/chart'
#BASE_URL = 'http://chart.apis.google.com/chart'
BASE_URL = 'http://localhost:8080/chart'
#BASE_URL = 'http://weatherpidev.smbconsult.local:8080/chart'
#BASE_URL = 'https://quickchart.io/chart'
# BACKGROUND = 'bg'
# CHART = 'c'
# ALPHA = 'a'
# VALID_SOLID_FILL_TYPES = (BACKGROUND, CHART, ALPHA)
# SOLID = 's'
# LINEAR_GRADIENT = 'lg'
# LINEAR_STRIPES = 'ls'
def __init__(self, width, height, pixelratio=1, title=None, legend=None, colours=None,
auto_scale=False, x_range=None, y_range=None,
colours_within_series=None):
if type(self) == Chart:
raise AbstractClassException('This is an abstract class')
assert(isinstance(width, int))
assert(isinstance(height, int))
self.width = width
self.height = height
self.Cartesian = False
self.Radial = False
#self.data = []
#self.set_title(title)
#self.set_title_style(None, None)
#self.set_legend(legend)
#self.set_legend_position(None)
#self.set_colours(colours)
#self.set_colours_within_series(colours_within_series)
# Data for scaling.
#self.auto_scale = auto_scale # Whether to automatically scale data
#self.x_range = x_range # (min, max) x-axis range for scaling
#self.y_range = y_range # (min, max) y-axis range for scaling
#self.scaled_data_class = None
#self.scaled_x_range = None
#self.scaled_y_range = None
#self.fill_types = {
# Chart.BACKGROUND: None,
# Chart.CHART: None,
# Chart.ALPHA: None,
#}
#self.fill_area = {
# Chart.BACKGROUND: None,
# Chart.CHART: None,
# Chart.ALPHA: None,
#}
#self.axis = []
#self.markers = []
#self.line_styles = {}
#self.grid = None
#self.title_colour = None
#self.title_font_size = None
self.POSTBody = {
"backgroundColor": "transparent",
"devicePixelRatio": pixelratio,
"width": None,
"height": None,
"format": "png",
"chart": None
}
self.chart={
'type': '',
'options': {
'legend': {
'labels': {},
'display': False
},
'title': {
'display': False
}
},
'data': {
'datasets': []
}
}
Cartesion= {
'scales': {
'xAxes': [
{
'id':'x-axis-0',
'gridLines':{
# 'lineWidth': 1,
# 'zeroLineWidth': 3,
# 'display':False
},
'labels':[],
# 'display':False
'ticks': {
# 'display': True,
'autoSkipPadding': 2,
}
}
],
'yAxes': [
{
'id':'y-axis-0',
'gridLines': {
# 'lineWidth': 1,
# 'zeroLineWidth': 3,
# 'display':False
},
'labels':[],
'ticks': {
# 'display': True,
# 'autoSkipPadding': 2,
}
}
]
}
}
Radial= {
'scale':{
'angleLines': {
# 'display': False
},
'gridLines': {
# 'display': False,
# 'circular': True
},
'pointLabels': {},
'ticks': {
'display': False,
# "fontColor": "#8D7641",
# "fontFamily": "Arial",
# "fontSize": 10,
# "fontStyle": "normal"
}
}
}
# Plugin = {
# 'annotation': {
# 'annotations': [{
# 'type': 'line',
# 'mode': 'vertical',
# 'scaleID': 'x-axis-0',
# 'value': '22',
# 'borderColor': 'red',
# 'borderWidth': 2,
# 'label': {
# 'position':'top',
# 'fontStyle':'normal',
# 'enabled': True,
# 'content': '999'
# }
# }, {
# 'type': 'line',
# 'mode': 'vertical',
# 'scaleID': 'x-axis-0',
# 'value': '08',
# 'borderColor': 'blue',
# 'borderWidth': 2,
# 'label': {
# 'position':'bottom',
# 'fontStyle':'normal',
# 'enabled': True,
# 'content': '666'
# },
# 'type': 'box',
# 'xScaleID': 'x-axis-0',
# 'yScaleID': 'y-axis-0',
# 'xMin': '00',
# 'xMax': '02',
# 'backgroundColor': 'rgba(200, 200, 200, 0.2)',
# 'borderColor': '#ccc',
# }]
# } #,
# 'plugins': {
# 'datalabels': {
# 'display': False,
# 'align': 'bottom',
# 'backgroundColor': '#ccc',
# 'borderRadius': 3
# }
# }
# }
Annotations={
'annotation': {
'annotations': []
}
}
Plugins = {
'plugins': {
'datalabels': {
'display': False
}
}
}
# AnnMax = {
# 'type': 'line',
# 'mode': 'vertical',
# 'scaleID': 'x-axis-idx',
# 'value': 4,
# 'borderColor': 'rgba(128,0,0,0.2)',
# 'borderWidth': 1,
# 'label': {
# 'position':'top',
# 'fontColor': "#fff",
# #'fontSize': 10,
# 'fontStyle':'normal',
# 'backgroundColor': 'rgba(128,0,0,0.4)',
# 'xPadding': 3,
# 'yPadding': 3,
# 'cornerRadius': 3,
# 'enabled': True,
# 'content': '999'
# }
# }
#
# AnnMin = {
# 'type': 'line',
# 'mode': 'vertical',
# 'scaleID': 'x-axis-idx',
# 'value': 10,
# 'borderColor': 'rgba(0,0,128,0.2)',
# 'borderWidth': 1,
# 'label': {
# 'position':'bottom',
# 'fontColor': "#fff",
# 'fontStyle':'normal',
# 'backgroundColor': 'rgba(0,0,128,0.4)',
# 'xPadding': 3,
# 'yPadding': 3,
# 'cornerRadius': 3,
# 'enabled': True,
# 'content': '666'
# }
# }
# AnnBox = {
# 'type': 'box',
# 'xScaleID': 'x-axis-idx',
# 'yScaleID': 'y-axis-0',
# 'xMin': 2,
# 'xMax': 6,
# 'backgroundColor': 'rgba(200, 200, 200, 0.2)',
# 'borderColor': '#ccc'
# }
if type(self) in [SimpleLineChart, SimpleBarChart, HorizontalBarChart, \
StackedHorizontalBarChart, StackedVerticalBarChart, ScatterChart]:
self.Cartesian = True
self.chart['options'].update(Cartesion)
self.chart['options'].update(Annotations)
#self.add_xaxis()
#self.add_yaxis()
# try out modifications
#self.set_axis_gridlines('x',True)
#self.set_axis_gridlines('y',True)
#self.set_axis_gridline_width('x',3)
#self.set_axis_gridline_width('y',3)
#self.set_axis_style('x',10)
#self.set_axis_style('y',10)
#self.chart['options']['scales']['xAxes'][0]['ticks'].update({'fontSize':10})
#self.chart['options']['scales']['yAxes'][0]['ticks'].update({'fontSize':10})
#self.chart['options']['annotation']['annotations'].append(AnnMax)
#self.chart['options']['annotation']['annotations'].append(AnnMin)
#self.chart['options']['annotation']['annotations'].append(AnnBox)
if type(self) in [RadarChart, PolarChart]:
self.Radial = True
self.chart['options'].update(Radial)
# try out modifications
#self.set_axis_style('x',14,'Arial','red')
#self.set_axis_gridlines('grid',True)
#self.set_axis_gridlines('radial',True)
#self.set_axis_gridline_width('grid',3)
#self.set_axis_gridline_width('radial',3)
#self.chart['options'].update({'spanGaps':True})
if type(self) in [SimplePieChart, SimpleDoughnutChart]:
self.chart['options'].update(Plugins)
#self.chart['options'].update({'fontSize':6})
self.chart['type']=self.type_to_url()
#labels=['Jan','Feb', 'Mar','Apr', 'May','Jan','Feb', 'Mar','Apr', 'May']
#self.chart['options']['scales']['xAxes'][0]['labels']=labels
# Inspect chart JSON
# -------------------------------------------------------------------------
def dump_chart(self, data_class=None):
return json.dumps(self.chart, indent=2, sort_keys=True)
# Global options
# -------------------------------------------------------------------------
def set_chartpixelratio(self,ratio):
self.POSTBody.update({'devicePixelRatio':ratio})
def set_chartsize(self, width, height):
self.POSTBody.update({'width':width})
self.POSTBody.update({'height':height})
def set_chartbackground(self,colour):
self.POSTBody.update({'backgroundColor':colour})
# URL Generation
# -------------------------------------------------------------------------
def get_json(self, docroot, data_class=None):
import requests
import uuid
import shutil
# x = {
# "backgroundColor": "transparent",
# "devicePixelRatio": 1,
# "width": self.width,
# "height": self.height,
# "format": "png",
# "chart": json.dumps(self.chart)
# }
x = self.POSTBody
x.update({"width":self.width})
x.update({"height":self.height})
x.update({"chart": json.dumps(self.chart)})
h = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
guid=uuid.uuid1().hex
filename = guid+'.png'
pathname = docroot+'/'+guid+'.png'
# uri = '/img_cache/'+guid+'.png'
try:
chart_data = requests.post(self.BASE_URL, data=x, headers=h, stream=True)
except requests.exceptions.RequestException as e:
raise JsonPostException(e)
# The following code works, but is too slow - keeps timing out. The COPYFILEOBJ method is better
# if chart_data.status_code == 200:
# with open(filename, "wb") as f:
# for chunk in chart_data:
# f.write(chunk)
# f.close()
if chart_data.status_code == 200:
with open(pathname, "wb") as f:
chart_data.raw.decode_content = True
shutil.copyfileobj(chart_data.raw, f)
f.close()
return filename
else:
return str(chart_data.status_code)
# def get_url(self, data_class=None):
#g_url = self.BASE_URL + "?"
#g_url = g_url + "w=%i&h=%i" % (self.width, self.height)
#g_url = g_url + "&devicePixelRatio=1"
#g_url = g_url + "&c=" + self.chart_json()
#return g_url
# return self.BASE_URL + '?' + self.get_url_extension(data_class)# + quote(self.chart_json())
# def get_url_extension(self, data_class=None):
# url_bits = self.get_url_bits(data_class=data_class)
# return '&'.join(url_bits)
# def get_url_bits(self, data_class=None):
# url_bits = []
# required arguments
# url_bits.append("w=%i" % (self.width))
# url_bits.append("h=%i" % (self.height))
# optional arguments
# url_bits.append("devicePixelRatio=1")
# encode the chart dict
# url_bits.append("c=" + quote(json.dumps(self.chart)))
# return url_bits
# # required arguments
# url_bits.append(self.type_to_url())
# url_bits.append('chs=%ix%i' % (self.width, self.height))
# url_bits.append(self.data_to_url(data_class=data_class))
# # optional arguments
# if self.title:
# url_bits.append('chtt=%s' % self.title)
# if self.title_colour and self.title_font_size:
# url_bits.append('chts=%s,%s' % (self.title_colour, \
# self.title_font_size))
# if self.legend:
# url_bits.append('chdl=%s' % '%7c'.join(self.legend))
# if self.legend_position:
# url_bits.append('chdlp=%s' % (self.legend_position))
# if self.colours:
# url_bits.append('chco=%s' % ','.join(self.colours))
# if self.colours_within_series:
# url_bits.append('chco=%s' % '%7c'.join(self.colours_within_series))
# ret = self.fill_to_url()
# if ret:
# url_bits.append(ret)
# ret = self.axis_to_url()
# if ret:
# url_bits.append(ret)
# if self.markers:
# url_bits.append(self.markers_to_url())
# if self.line_styles:
# style = []
# for index in range(max(self.line_styles) + 1):
# if index in self.line_styles:
# values = self.line_styles[index]
# else:
# values = ('1', )
# style.append(','.join(values))
# url_bits.append('chls=%s' % '%7c'.join(style))
# if self.grid:
# url_bits.append('chg=%s' % self.grid)
# return url_bits
def chart_json(self):
y=json.dumps(self.chart)
parsed_json=json.loads(y)
return json.dumps(self.chart)
# Downloading
# -------------------------------------------------------------------------
# def download(self, file_name=False, use_post=True):
# if use_post:
# opener = urlopen(self.BASE_URL, self.get_url_extension().encode('utf-8'))
# else:
# opener = urlopen(self.get_url())
# if opener.headers['content-type'] != 'image/png':
# raise BadContentTypeException('Server responded with a ' \
# 'content-type of %s' % opener.headers['content-type'])
# if file_name:
# open(file_name, 'wb').write(opener.read())
# else:
# return opener.read()
# Generic settings
# -------------------------------------------------------------------------
def set_title(self, title):
""" Enable/Disable the title
title - boolean
"""
self.chart['options']['title'].update({'display':title})
def set_title_text(self, title):
""" Set the title text
title - string/array of strings
array elements are displayed on a new line
"""
self.chart['options']['title'].update({'text':title})
def set_title_position(self, position):
"""Sets title position. Default is 'top'.
bottom - At the bottom of the chart
top - At the top of the chart
right - To the right of the chart
left - To the left of the chart
"""
positions = ['top','left','bottom','right']
assert (position in positions), "Unknown position"
self.chart['options']['title'].update({'position':position})
def set_title_style(self, fontSize=12, fontFamily='Arial', fontColor='#666', fontStyle='bold'):
self.chart['options']['title'].update({'fontSize':fontSize})
self.chart['options']['title'].update({'fontFamily':fontFamily})
self.chart['options']['title'].update({'fontColor':fontColor})
self.chart['options']['title'].update({'fontStyle':fontStyle})
def set_legend(self, legend):
""" Enable/Disable the legend
title - boolean
"""
self.chart['options']['legend'].update({'display':legend})
def set_legend_position(self, legend_position):
"""Sets legend position. Default is 'top'.
bottom - At the bottom of the chart
top - At the top of the chart
right - To the right of the chart
left - To the left of the chart
"""
positions = ['top','left','bottom','right']
assert (legend_position in positions), "Unknown position"
self.chart['options']['legend'].update({'position':legend_position})
def set_legend_style(self, fontSize=12, fontFamily='Arial', fontColor='#666', fontStyle='bold'):
self.chart['options']['legend']['labels'].update({'fontSize':fontSize})
self.chart['options']['legend']['labels'].update({'fontFamily':fontFamily})
self.chart['options']['legend']['labels'].update({'fontColor':fontColor})
self.chart['options']['legend']['labels'].update({'fontStyle':fontStyle})
# Chart colours
# -------------------------------------------------------------------------
# def set_colours(self, colours):
# # colours needs to be a list, tuple or None
# assert(isinstance(colours, list) or isinstance(colours, tuple) or
# colours is None)
# # make sure the colours are in the right format
# if colours:
# for col in colours:
# _check_colour(col)
# self.colours = colours
# def set_colours_within_series(self, colours):
# # colours needs to be a list, tuple or None
# assert(isinstance(colours, list) or isinstance(colours, tuple) or
# colours is None)
# # make sure the colours are in the right format
# if colours:
# for col in colours:
# _check_colour(col)
# self.colours_within_series = colours
# Background/Chart colours
# -------------------------------------------------------------------------
# def fill_solid(self, area, colour):
# assert(area in Chart.VALID_SOLID_FILL_TYPES)
# _check_colour(colour)
# self.fill_area[area] = colour
# self.fill_types[area] = Chart.SOLID
# def _check_fill_linear(self, angle, *args):
# assert(isinstance(args, list) or isinstance(args, tuple))
# assert(angle >= 0 and angle <= 90)
# assert(len(args) % 2 == 0)
# args = list(args) # args is probably a tuple and we need to mutate
# for a in range(int(len(args) / 2)):
# col = args[a * 2]
# offset = args[a * 2 + 1]
# _check_colour(col)
# assert(offset >= 0 and offset <= 1)
# args[a * 2 + 1] = str(args[a * 2 + 1])
# return args
# def fill_linear_gradient(self, area, angle, *args):
# assert(area in Chart.VALID_SOLID_FILL_TYPES)
# args = self._check_fill_linear(angle, *args)
# self.fill_types[area] = Chart.LINEAR_GRADIENT
# self.fill_area[area] = ','.join([str(angle)] + args)
# def fill_linear_stripes(self, area, angle, *args):
# assert(area in Chart.VALID_SOLID_FILL_TYPES)
# args = self._check_fill_linear(angle, *args)
# self.fill_types[area] = Chart.LINEAR_STRIPES
# self.fill_area[area] = ','.join([str(angle)] + args)
# def fill_to_url(self):
# areas = []
# for area in (Chart.BACKGROUND, Chart.CHART, Chart.ALPHA):
# if self.fill_types[area]:
# areas.append('%s,%s,%s' % (area, self.fill_types[area], \
# self.fill_area[area]))
# if areas:
# return 'chf=' + '%7c'.join(areas)
# DataSet
# -------------------------------------------------------------------------
def get_dataset(self, index):
try:
return json.dumps(self.chart['data']['datasets'][index])
except:
return None
def add_dataset(self, index, data, axis=None,mix_type=None):
dataset = {'order':index,
#'cubicInterpolationMode':'default',
#'lineTension':0.4,
#'xAxisID':'x-axis-1',
#'yAxisID':axis,
#'pointStyle':'rectRot',
#'pointRadius':0,
#'borderColor':'#'+config.color,
#'borderWidth':config.thickness,
#'borderDash':dash,
#'backgroundColor':'#'+fillcolour+"AA",
#'fill':fill,
'data':data
}
if axis != None:
axis_type=axis.split('-')[0]
if axis_type == 'x':
dataset.update({'xAxisID':axis})
elif axis_type == 'y':
dataset.update({'yAxisID':axis})
if mix_type != None:
dataset.update({'type':mix_type})
if type(self) in [SimpleLineChart]:
dataset.update({'lineTension':0.4})
try:
self.chart['data']['datasets'].append(dataset)
return len(self.chart['data']['datasets']) - 1
except:
return False
def set_dataset_label(self, index, label):
try:
self.chart['data']['datasets'][index].update({'label':label})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_linestyle(self, index, style):
try:
self.chart['data']['datasets'][index].update({'borderDash':style})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_linewidth(self, index, width):
try:
self.chart['data']['datasets'][index].update({'borderWidth':width})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_linecolour(self, index, colour):
try:
self.chart['data']['datasets'][index].update({'borderColor':colour})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_linetension(self, index, tension=0.4):
try:
self.chart['data']['datasets'][index].update({'lineTension':tension})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_fillcolour(self, index, colour):
try:
self.chart['data']['datasets'][index].update({'backgroundColor':colour})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_fillstyle(self, index, fill):
try:
self.chart['data']['datasets'][index].update({'fill':fill})
except:
raise IndexOutOfRangeException("Index out of range")
def set_dataset_spangaps(self, index, spangaps):
try:
self.chart['data']['datasets'][index].update({'spanGaps':spangaps})
except:
raise IndexOutOfRangeException("Index out of range")