forked from mrooney/cairoplot
-
Notifications
You must be signed in to change notification settings - Fork 19
/
cairoplot.py
executable file
·2304 lines (2018 loc) · 102 KB
/
cairoplot.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
# -*- coding: utf-8 -*-
# CairoPlot.py
#
# Copyright (c) 2008 Rodrigo Moreira Araújo
#
# Author: Rodrigo Moreiro Araujo <alf.rodrigo@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2 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 Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#Contributor: João S. O. Bueno
#TODO: review BarPlot Code
#TODO: x_label colision problem on Horizontal Bar Plot
#TODO: y_label's eat too much space on HBP
__version__ = 1.1
import cairo
import math
import random
from Series import Serie, Group, Data
HORZ = 0
VERT = 1
NORM = 2
COLORS = {"red" : (1.0,0.0,0.0,1.0), "lime" : (0.0,1.0,0.0,1.0), "blue" : (0.0,0.0,1.0,1.0),
"maroon" : (0.5,0.0,0.0,1.0), "green" : (0.0,0.5,0.0,1.0), "navy" : (0.0,0.0,0.5,1.0),
"yellow" : (1.0,1.0,0.0,1.0), "magenta" : (1.0,0.0,1.0,1.0), "cyan" : (0.0,1.0,1.0,1.0),
"orange" : (1.0,0.5,0.0,1.0), "white" : (1.0,1.0,1.0,1.0), "black" : (0.0,0.0,0.0,1.0),
"gray" : (0.5,0.5,0.5,1.0), "light_gray" : (0.9,0.9,0.9,1.0),
"transparent" : (0.0,0.0,0.0,0.0)}
THEMES = {"black_red" : [(0.0,0.0,0.0,1.0), (1.0,0.0,0.0,1.0)],
"red_green_blue" : [(1.0,0.0,0.0,1.0), (0.0,1.0,0.0,1.0), (0.0,0.0,1.0,1.0)],
"red_orange_yellow" : [(1.0,0.2,0.0,1.0), (1.0,0.7,0.0,1.0), (1.0,1.0,0.0,1.0)],
"yellow_orange_red" : [(1.0,1.0,0.0,1.0), (1.0,0.7,0.0,1.0), (1.0,0.2,0.0,1.0)],
"rainbow" : [(1.0,0.0,0.0,1.0), (1.0,0.5,0.0,1.0), (1.0,1.0,0.0,1.0), (0.0,1.0,0.0,1.0), (0.0,0.0,1.0,1.0), (0.3, 0.0, 0.5,1.0), (0.5, 0.0, 1.0, 1.0)]}
def colors_from_theme( theme, series_length, mode = 'solid' ):
colors = []
if theme not in THEMES.keys() :
raise Exception, "Theme not defined"
color_steps = THEMES[theme]
n_colors = len(color_steps)
if series_length <= n_colors:
colors = [color + tuple([mode]) for color in color_steps[0:n_colors]]
else:
iterations = [(series_length - n_colors)/(n_colors - 1) for i in color_steps[:-1]]
over_iterations = (series_length - n_colors) % (n_colors - 1)
for i in range(n_colors - 1):
if over_iterations <= 0:
break
iterations[i] += 1
over_iterations -= 1
for index,color in enumerate(color_steps[:-1]):
colors.append(color + tuple([mode]))
if iterations[index] == 0:
continue
next_color = color_steps[index+1]
color_step = ((next_color[0] - color[0])/(iterations[index] + 1),
(next_color[1] - color[1])/(iterations[index] + 1),
(next_color[2] - color[2])/(iterations[index] + 1),
(next_color[3] - color[3])/(iterations[index] + 1))
for i in range( iterations[index] ):
colors.append((color[0] + color_step[0]*(i+1),
color[1] + color_step[1]*(i+1),
color[2] + color_step[2]*(i+1),
color[3] + color_step[3]*(i+1),
mode))
colors.append(color_steps[-1] + tuple([mode]))
return colors
def other_direction(direction):
"explicit is better than implicit"
if direction == HORZ:
return VERT
else:
return HORZ
#Class definition
class Plot(object):
def __init__(self,
surface=None,
data=None,
width=640,
height=480,
background=None,
border = 0,
x_labels = None,
y_labels = None,
series_colors = None):
random.seed(2)
self.create_surface(surface, width, height)
self.dimensions = {}
self.dimensions[HORZ] = width
self.dimensions[VERT] = height
self.context = cairo.Context(self.surface)
self.labels={}
self.labels[HORZ] = x_labels
self.labels[VERT] = y_labels
self.load_series(data, x_labels, y_labels, series_colors)
self.font_size = 10
self.set_background (background)
self.border = border
self.borders = {}
self.line_color = (0.5, 0.5, 0.5)
self.line_width = 0.5
self.label_color = (0.0, 0.0, 0.0)
self.grid_color = (0.8, 0.8, 0.8)
def create_surface(self, surface, width=None, height=None):
self.filename = None
if isinstance(surface, cairo.Surface):
self.surface = surface
return
if not type(surface) in (str, unicode):
raise TypeError("Surface should be either a Cairo surface or a filename, not %s" % surface)
sufix = surface.rsplit(".")[-1].lower()
self.filename = surface
if sufix == "png":
self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
elif sufix == "ps":
self.surface = cairo.PSSurface(surface, width, height)
elif sufix == "pdf":
self.surface = cairo.PSSurface(surface, width, height)
else:
if sufix != "svg":
self.filename += ".svg"
self.surface = cairo.SVGSurface(self.filename, width, height)
def commit(self):
try:
self.context.show_page()
if self.filename and self.filename.endswith(".png"):
self.surface.write_to_png(self.filename)
else:
self.surface.finish()
except cairo.Error:
pass
def load_series (self, data, x_labels=None, y_labels=None, series_colors=None):
#FIXME: implement Series class for holding series data,
# labels and presentation properties
#data can be a list, a list of lists or a dictionary with
#each item as a labeled data series.
#we should (for the time being) create a list of lists
#and set labels for teh series rom teh values provided.
self.series_labels = []
self.serie = None
# The pretty way...
#if not isinstance(data, Serie):
# # Not an instance of Series
# self.serie = Serie(data)
#else:
# self.serie = data
#
#self.series_labels = self.serie.get_names()
#TODO: In the next version remove this...
# The ugly way, just to keep the retrocompatibility...
if callable(data) or type(data) is list and callable(data[0]): # Lambda or List of lambdas
self.serie = data
self.series_labels = None
elif isinstance(data, Serie): # Instance of Serie
self.serie = data
self.series_labels = data.get_names()
else: # Anything else
self.serie = Serie(data)
self.series_labels = self.serie.get_names()
#TODO: Remove old code
##dictionary
#if hasattr(data, "keys"):
# self.series_labels = data.keys()
# for key in self.series_labels:
# self.data.append(data[key])
##lists of lists:
#elif max([hasattr(item,'__delitem__') for item in data]) :
# self.data = data
# self.series_labels = range(len(data))
##list
#else:
# self.data = [data]
# self.series_labels = None
#TODO: allow user passed series_widths
self.series_widths = [1.0 for group in self.serie]
self.process_colors( series_colors )
def process_colors( self, series_colors, length = None, mode = 'solid' ):
#series_colors might be None, a theme, a string of colors names or a string of color tuples
if length is None :
length = len( self.serie )
#no colors passed
if not series_colors:
#Randomize colors
self.series_colors = [ [random.random() for i in range(3)] + [1.0, mode] for series in range( length ) ]
else:
#Just theme pattern
if not hasattr( series_colors, "__iter__" ):
theme = series_colors
self.series_colors = colors_from_theme( theme.lower(), length )
#Theme pattern and mode
elif not hasattr(series_colors, '__delitem__') and not hasattr( series_colors[0], "__iter__" ):
theme = series_colors[0]
mode = series_colors[1]
self.series_colors = colors_from_theme( theme.lower(), length, mode )
#List
else:
self.series_colors = series_colors
for index, color in enumerate( self.series_colors ):
#element is a color name
if not hasattr(color, "__iter__"):
self.series_colors[index] = COLORS[color.lower()] + tuple([mode])
#element is rgb tuple instead of rgba
elif len( color ) == 3 :
self.series_colors[index] += (1.0,mode)
#element has 4 elements, might be rgba tuple or rgb tuple with mode
elif len( color ) == 4 :
#last element is mode
if not hasattr(color[3], "__iter__"):
self.series_colors[index] += tuple([color[3]])
self.series_colors[index][3] = 1.0
#last element is alpha
else:
self.series_colors[index] += tuple([mode])
def get_width(self):
return self.surface.get_width()
def get_height(self):
return self.surface.get_height()
def set_background(self, background):
if background is None:
self.background = (0.0,0.0,0.0,0.0)
elif type(background) in (cairo.LinearGradient, tuple):
self.background = background
elif not hasattr(background,"__iter__"):
colors = background.split(" ")
if len(colors) == 1 and colors[0] in COLORS:
self.background = COLORS[background]
elif len(colors) > 1:
self.background = cairo.LinearGradient(self.dimensions[HORZ] / 2, 0, self.dimensions[HORZ] / 2, self.dimensions[VERT])
for index,color in enumerate(colors):
self.background.add_color_stop_rgba(float(index)/(len(colors)-1),*COLORS[color])
else:
raise TypeError ("Background should be either cairo.LinearGradient or a 3-tuple, not %s" % type(background))
def render_background(self):
if isinstance(self.background, cairo.LinearGradient):
self.context.set_source(self.background)
else:
self.context.set_source_rgba(*self.background)
self.context.rectangle(0,0, self.dimensions[HORZ], self.dimensions[VERT])
self.context.fill()
def render_bounding_box(self):
self.context.set_source_rgba(*self.line_color)
self.context.set_line_width(self.line_width)
self.context.rectangle(self.border, self.border,
self.dimensions[HORZ] - 2 * self.border,
self.dimensions[VERT] - 2 * self.border)
self.context.stroke()
def render(self):
pass
class ScatterPlot( Plot ):
def __init__(self,
surface=None,
data=None,
errorx=None,
errory=None,
width=640,
height=480,
background=None,
border=0,
axis = False,
dash = False,
discrete = False,
dots = 0,
grid = False,
series_legend = False,
x_labels = None,
y_labels = None,
x_bounds = None,
y_bounds = None,
z_bounds = None,
x_title = None,
y_title = None,
series_colors = None,
circle_colors = None ):
self.bounds = {}
self.bounds[HORZ] = x_bounds
self.bounds[VERT] = y_bounds
self.bounds[NORM] = z_bounds
self.titles = {}
self.titles[HORZ] = x_title
self.titles[VERT] = y_title
self.max_value = {}
self.axis = axis
self.discrete = discrete
self.dots = dots
self.grid = grid
self.series_legend = series_legend
self.variable_radius = False
self.x_label_angle = math.pi / 2.5
self.circle_colors = circle_colors
Plot.__init__(self, surface, data, width, height, background, border, x_labels, y_labels, series_colors)
self.dash = None
if dash:
if hasattr(dash, "keys"):
self.dash = [dash[key] for key in self.series_labels]
elif max([hasattr(item,'__delitem__') for item in data]) :
self.dash = dash
else:
self.dash = [dash]
self.load_errors(errorx, errory)
def convert_list_to_tuple(self, data):
#Data must be converted from lists of coordinates to a single
# list of tuples
out_data = zip(*data)
if len(data) == 3:
self.variable_radius = True
return out_data
def load_series(self, data, x_labels = None, y_labels = None, series_colors=None):
#Dictionary with lists
if hasattr(data, "keys") :
if hasattr( data.values()[0][0], "__delitem__" ) :
for key in data.keys() :
data[key] = self.convert_list_to_tuple(data[key])
elif len(data.values()[0][0]) == 3:
self.variable_radius = True
#List
elif hasattr(data[0], "__delitem__") :
#List of lists
if hasattr(data[0][0], "__delitem__") :
for index,value in enumerate(data) :
data[index] = self.convert_list_to_tuple(value)
#List
elif type(data[0][0]) != type((0,0)):
data = self.convert_list_to_tuple(data)
#Three dimensional data
elif len(data[0][0]) == 3:
self.variable_radius = True
#List with three dimensional tuples
elif len(data[0]) == 3:
self.variable_radius = True
Plot.load_series(self, data, x_labels, y_labels, series_colors)
self.calc_boundaries()
self.calc_labels()
def load_errors(self, errorx, errory):
self.errors = None
if errorx == None and errory == None:
return
self.errors = {}
self.errors[HORZ] = None
self.errors[VERT] = None
#asimetric errors
if errorx and hasattr(errorx[0], "__delitem__"):
self.errors[HORZ] = errorx
#simetric errors
elif errorx:
self.errors[HORZ] = [errorx]
#asimetric errors
if errory and hasattr(errory[0], "__delitem__"):
self.errors[VERT] = errory
#simetric errors
elif errory:
self.errors[VERT] = [errory]
def calc_labels(self):
if not self.labels[HORZ]:
amplitude = self.bounds[HORZ][1] - self.bounds[HORZ][0]
if amplitude % 10: #if horizontal labels need floating points
self.labels[HORZ] = ["%.2lf" % (float(self.bounds[HORZ][0] + (amplitude * i / 10.0))) for i in range(11) ]
else:
self.labels[HORZ] = ["%d" % (int(self.bounds[HORZ][0] + (amplitude * i / 10.0))) for i in range(11) ]
if not self.labels[VERT]:
amplitude = self.bounds[VERT][1] - self.bounds[VERT][0]
if amplitude % 10: #if vertical labels need floating points
self.labels[VERT] = ["%.2lf" % (float(self.bounds[VERT][0] + (amplitude * i / 10.0))) for i in range(11) ]
else:
self.labels[VERT] = ["%d" % (int(self.bounds[VERT][0] + (amplitude * i / 10.0))) for i in range(11) ]
def calc_extents(self, direction):
self.context.set_font_size(self.font_size * 0.8)
self.max_value[direction] = max(self.context.text_extents(item)[2] for item in self.labels[direction])
self.borders[other_direction(direction)] = self.max_value[direction] + self.border + 20
def calc_boundaries(self):
#HORZ = 0, VERT = 1, NORM = 2
min_data_value = [0,0,0]
max_data_value = [0,0,0]
for group in self.serie:
if type(group[0].content) in (int, float, long):
group = [Data((index, item.content)) for index,item in enumerate(group)]
for point in group:
for index, item in enumerate(point.content):
if item > max_data_value[index]:
max_data_value[index] = item
elif item < min_data_value[index]:
min_data_value[index] = item
if not self.bounds[HORZ]:
self.bounds[HORZ] = (min_data_value[HORZ], max_data_value[HORZ])
if not self.bounds[VERT]:
self.bounds[VERT] = (min_data_value[VERT], max_data_value[VERT])
if not self.bounds[NORM]:
self.bounds[NORM] = (min_data_value[NORM], max_data_value[NORM])
def calc_all_extents(self):
self.calc_extents(HORZ)
self.calc_extents(VERT)
self.plot_height = self.dimensions[VERT] - 2 * self.borders[VERT]
self.plot_width = self.dimensions[HORZ] - 2* self.borders[HORZ]
self.plot_top = self.dimensions[VERT] - self.borders[VERT]
def calc_steps(self):
#Calculates all the x, y, z and color steps
series_amplitude = [self.bounds[index][1] - self.bounds[index][0] for index in range(3)]
if series_amplitude[HORZ]:
self.horizontal_step = float (self.plot_width) / series_amplitude[HORZ]
else:
self.horizontal_step = 0.00
if series_amplitude[VERT]:
self.vertical_step = float (self.plot_height) / series_amplitude[VERT]
else:
self.vertical_step = 0.00
if series_amplitude[NORM]:
if self.variable_radius:
self.z_step = float (self.bounds[NORM][1]) / series_amplitude[NORM]
if self.circle_colors:
self.circle_color_step = tuple([float(self.circle_colors[1][i]-self.circle_colors[0][i])/series_amplitude[NORM] for i in range(4)])
else:
self.z_step = 0.00
self.circle_color_step = ( 0.0, 0.0, 0.0, 0.0 )
def get_circle_color(self, value):
return tuple( [self.circle_colors[0][i] + value*self.circle_color_step[i] for i in range(4)] )
def render(self):
self.calc_all_extents()
self.calc_steps()
self.render_background()
self.render_bounding_box()
if self.axis:
self.render_axis()
if self.grid:
self.render_grid()
self.render_labels()
self.render_plot()
if self.errors:
self.render_errors()
if self.series_legend and self.series_labels:
self.render_legend()
def render_axis(self):
#Draws both the axis lines and their titles
cr = self.context
cr.set_source_rgba(*self.line_color)
cr.move_to(self.borders[HORZ], self.dimensions[VERT] - self.borders[VERT])
cr.line_to(self.borders[HORZ], self.borders[VERT])
cr.stroke()
cr.move_to(self.borders[HORZ], self.dimensions[VERT] - self.borders[VERT])
cr.line_to(self.dimensions[HORZ] - self.borders[HORZ], self.dimensions[VERT] - self.borders[VERT])
cr.stroke()
cr.set_source_rgba(*self.label_color)
self.context.set_font_size( 1.2 * self.font_size )
if self.titles[HORZ]:
title_width,title_height = cr.text_extents(self.titles[HORZ])[2:4]
cr.move_to( self.dimensions[HORZ]/2 - title_width/2, self.borders[VERT] - title_height/2 )
cr.show_text( self.titles[HORZ] )
if self.titles[VERT]:
title_width,title_height = cr.text_extents(self.titles[VERT])[2:4]
cr.move_to( self.dimensions[HORZ] - self.borders[HORZ] + title_height/2, self.dimensions[VERT]/2 - title_width/2)
cr.rotate( math.pi/2 )
cr.show_text( self.titles[VERT] )
cr.rotate( -math.pi/2 )
def render_grid(self):
cr = self.context
horizontal_step = float( self.plot_height ) / ( len( self.labels[VERT] ) - 1 )
vertical_step = float( self.plot_width ) / ( len( self.labels[HORZ] ) - 1 )
x = self.borders[HORZ] + vertical_step
y = self.plot_top - horizontal_step
for label in self.labels[HORZ][:-1]:
cr.set_source_rgba(*self.grid_color)
cr.move_to(x, self.dimensions[VERT] - self.borders[VERT])
cr.line_to(x, self.borders[VERT])
cr.stroke()
x += vertical_step
for label in self.labels[VERT][:-1]:
cr.set_source_rgba(*self.grid_color)
cr.move_to(self.borders[HORZ], y)
cr.line_to(self.dimensions[HORZ] - self.borders[HORZ], y)
cr.stroke()
y -= horizontal_step
def render_labels(self):
self.context.set_font_size(self.font_size * 0.8)
self.render_horz_labels()
self.render_vert_labels()
def render_horz_labels(self):
cr = self.context
step = float( self.plot_width ) / ( len( self.labels[HORZ] ) - 1 )
x = self.borders[HORZ]
for item in self.labels[HORZ]:
cr.set_source_rgba(*self.label_color)
width = cr.text_extents(item)[2]
cr.move_to(x, self.dimensions[VERT] - self.borders[VERT] + 5)
cr.rotate(self.x_label_angle)
cr.show_text(item)
cr.rotate(-self.x_label_angle)
x += step
def render_vert_labels(self):
cr = self.context
step = ( self.plot_height ) / ( len( self.labels[VERT] ) - 1 )
y = self.plot_top
for item in self.labels[VERT]:
cr.set_source_rgba(*self.label_color)
width = cr.text_extents(item)[2]
cr.move_to(self.borders[HORZ] - width - 5,y)
cr.show_text(item)
y -= step
def render_legend(self):
cr = self.context
cr.set_font_size(self.font_size)
cr.set_line_width(self.line_width)
widest_word = max(self.series_labels, key = lambda item: self.context.text_extents(item)[2])
tallest_word = max(self.series_labels, key = lambda item: self.context.text_extents(item)[3])
max_width = self.context.text_extents(widest_word)[2]
max_height = self.context.text_extents(tallest_word)[3] * 1.1
color_box_height = max_height / 2
color_box_width = color_box_height * 2
#Draw a bounding box
bounding_box_width = max_width + color_box_width + 15
bounding_box_height = (len(self.series_labels)+0.5) * max_height
cr.set_source_rgba(1,1,1)
cr.rectangle(self.dimensions[HORZ] - self.borders[HORZ] - bounding_box_width, self.borders[VERT],
bounding_box_width, bounding_box_height)
cr.fill()
cr.set_source_rgba(*self.line_color)
cr.set_line_width(self.line_width)
cr.rectangle(self.dimensions[HORZ] - self.borders[HORZ] - bounding_box_width, self.borders[VERT],
bounding_box_width, bounding_box_height)
cr.stroke()
for idx,key in enumerate(self.series_labels):
#Draw color box
cr.set_source_rgba(*self.series_colors[idx][:4])
cr.rectangle(self.dimensions[HORZ] - self.borders[HORZ] - max_width - color_box_width - 10,
self.borders[VERT] + color_box_height + (idx*max_height) ,
color_box_width, color_box_height)
cr.fill()
cr.set_source_rgba(0, 0, 0)
cr.rectangle(self.dimensions[HORZ] - self.borders[HORZ] - max_width - color_box_width - 10,
self.borders[VERT] + color_box_height + (idx*max_height),
color_box_width, color_box_height)
cr.stroke()
#Draw series labels
cr.set_source_rgba(0, 0, 0)
cr.move_to(self.dimensions[HORZ] - self.borders[HORZ] - max_width - 5, self.borders[VERT] + ((idx+1)*max_height))
cr.show_text(key)
def render_errors(self):
cr = self.context
cr.rectangle(self.borders[HORZ], self.borders[VERT], self.plot_width, self.plot_height)
cr.clip()
radius = self.dots
x0 = self.borders[HORZ] - self.bounds[HORZ][0]*self.horizontal_step
y0 = self.borders[VERT] - self.bounds[VERT][0]*self.vertical_step
for index, group in enumerate(self.serie):
cr.set_source_rgba(*self.series_colors[index][:4])
for number, data in enumerate(group):
x = x0 + self.horizontal_step * data.content[0]
y = self.dimensions[VERT] - y0 - self.vertical_step * data.content[1]
if self.errors[HORZ]:
cr.move_to(x, y)
x1 = x - self.horizontal_step * self.errors[HORZ][0][number]
cr.line_to(x1, y)
cr.line_to(x1, y - radius)
cr.line_to(x1, y + radius)
cr.stroke()
if self.errors[HORZ] and len(self.errors[HORZ]) == 2:
cr.move_to(x, y)
x1 = x + self.horizontal_step * self.errors[HORZ][1][number]
cr.line_to(x1, y)
cr.line_to(x1, y - radius)
cr.line_to(x1, y + radius)
cr.stroke()
if self.errors[VERT]:
cr.move_to(x, y)
y1 = y + self.vertical_step * self.errors[VERT][0][number]
cr.line_to(x, y1)
cr.line_to(x - radius, y1)
cr.line_to(x + radius, y1)
cr.stroke()
if self.errors[VERT] and len(self.errors[VERT]) == 2:
cr.move_to(x, y)
y1 = y - self.vertical_step * self.errors[VERT][1][number]
cr.line_to(x, y1)
cr.line_to(x - radius, y1)
cr.line_to(x + radius, y1)
cr.stroke()
def render_plot(self):
cr = self.context
if self.discrete:
cr.rectangle(self.borders[HORZ], self.borders[VERT], self.plot_width, self.plot_height)
cr.clip()
x0 = self.borders[HORZ] - self.bounds[HORZ][0]*self.horizontal_step
y0 = self.borders[VERT] - self.bounds[VERT][0]*self.vertical_step
radius = self.dots
for number, group in enumerate (self.serie):
cr.set_source_rgba(*self.series_colors[number][:4])
for data in group :
if self.variable_radius:
radius = data.content[2]*self.z_step
if self.circle_colors:
cr.set_source_rgba( *self.get_circle_color( data.content[2]) )
x = x0 + self.horizontal_step*data.content[0]
y = y0 + self.vertical_step*data.content[1]
cr.arc(x, self.dimensions[VERT] - y, radius, 0, 2*math.pi)
cr.fill()
else:
cr.rectangle(self.borders[HORZ], self.borders[VERT], self.plot_width, self.plot_height)
cr.clip()
x0 = self.borders[HORZ] - self.bounds[HORZ][0]*self.horizontal_step
y0 = self.borders[VERT] - self.bounds[VERT][0]*self.vertical_step
radius = self.dots
for number, group in enumerate (self.serie):
last_data = None
cr.set_source_rgba(*self.series_colors[number][:4])
for data in group :
x = x0 + self.horizontal_step*data.content[0]
y = y0 + self.vertical_step*data.content[1]
if self.dots:
if self.variable_radius:
radius = data.content[2]*self.z_step
cr.arc(x, self.dimensions[VERT] - y, radius, 0, 2*math.pi)
cr.fill()
if last_data :
old_x = x0 + self.horizontal_step*last_data.content[0]
old_y = y0 + self.vertical_step*last_data.content[1]
cr.move_to( old_x, self.dimensions[VERT] - old_y )
cr.line_to( x, self.dimensions[VERT] - y)
cr.set_line_width(self.series_widths[number])
# Display line as dash line
if self.dash and self.dash[number]:
s = self.series_widths[number]
cr.set_dash([s*3, s*3], 0)
cr.stroke()
cr.set_dash([])
last_data = data
class DotLinePlot(ScatterPlot):
def __init__(self,
surface=None,
data=None,
width=640,
height=480,
background=None,
border=0,
axis = False,
dash = False,
dots = 0,
grid = False,
series_legend = False,
x_labels = None,
y_labels = None,
x_bounds = None,
y_bounds = None,
x_title = None,
y_title = None,
series_colors = None):
ScatterPlot.__init__(self, surface, data, None, None, width, height, background, border,
axis, dash, False, dots, grid, series_legend, x_labels, y_labels,
x_bounds, y_bounds, None, x_title, y_title, series_colors, None )
def load_series(self, data, x_labels = None, y_labels = None, series_colors=None):
Plot.load_series(self, data, x_labels, y_labels, series_colors)
for group in self.serie :
for index,data in enumerate(group):
group[index].content = (index, data.content)
self.calc_boundaries()
self.calc_labels()
class FunctionPlot(ScatterPlot):
def __init__(self,
surface=None,
data=None,
width=640,
height=480,
background=None,
border=0,
axis = False,
discrete = False,
dots = 0,
grid = False,
series_legend = False,
x_labels = None,
y_labels = None,
x_bounds = None,
y_bounds = None,
x_title = None,
y_title = None,
series_colors = None,
step = 1):
self.function = data
self.step = step
self.discrete = discrete
data, x_bounds = self.load_series_from_function( self.function, x_bounds )
ScatterPlot.__init__(self, surface, data, None, None, width, height, background, border,
axis, False, discrete, dots, grid, series_legend, x_labels, y_labels,
x_bounds, y_bounds, None, x_title, y_title, series_colors, None )
def load_series(self, data, x_labels = None, y_labels = None, series_colors=None):
Plot.load_series(self, data, x_labels, y_labels, series_colors)
for group_id, group in enumerate(self.serie) :
for index,data in enumerate(group):
group[index].content = (self.bounds[HORZ][0] + self.step*index, data.content)
self.calc_boundaries()
self.calc_labels()
def load_series_from_function( self, function, x_bounds ):
#TODO: Add the possibility for the user to define multiple functions with different discretization parameters
#This function converts a function, a list of functions or a dictionary
#of functions into its corresponding array of data
serie = Serie()
#if no bounds are provided
if x_bounds == None:
x_bounds = (0,10)
#TODO: Finish the dict translation
if hasattr(function, "keys"): #dictionary:
data = {}
for key in function.keys():
data[ key ] = []
i = x_bounds[0]
while i <= x_bounds[1] :
data[ key ].append( function[ key ](i) )
i += self.step
elif hasattr(function, "__delitem__"): #list of functions
for index,f in enumerate( function ) :
group = Group()
#data.append( [] )
i = x_bounds[0]
while i <= x_bounds[1] :
group.add_data(f(i))
#data[ index ].append( f(i) )
i += self.step
serie.add_group(group)
else: #function
group = Group()
i = x_bounds[0]
while i <= x_bounds[1] :
group.add_data(function(i))
i += self.step
serie.add_group(group)
return serie, x_bounds
def calc_labels(self):
if not self.labels[HORZ]:
self.labels[HORZ] = []
i = self.bounds[HORZ][0]
while i<=self.bounds[HORZ][1]:
self.labels[HORZ].append(str(i))
i += float(self.bounds[HORZ][1] - self.bounds[HORZ][0])/10
ScatterPlot.calc_labels(self)
def render_plot(self):
if not self.discrete:
ScatterPlot.render_plot(self)
else:
last = None
cr = self.context
for number, group in enumerate (self.serie):
cr.set_source_rgba(*self.series_colors[number][:4])
x0 = self.borders[HORZ] - self.bounds[HORZ][0]*self.horizontal_step
y0 = self.borders[VERT] - self.bounds[VERT][0]*self.vertical_step
for data in group:
x = x0 + self.horizontal_step * data.content[0]
y = y0 + self.vertical_step * data.content[1]
cr.move_to(x, self.dimensions[VERT] - y)
cr.line_to(x, self.plot_top)
cr.set_line_width(self.series_widths[number])
cr.stroke()
if self.dots:
cr.new_path()
cr.arc(x, self.dimensions[VERT] - y, 3, 0, 2.1 * math.pi)
cr.close_path()
cr.fill()
class BarPlot(Plot):
def __init__(self,
surface = None,
data = None,
width = 640,
height = 480,
background = "white light_gray",
border = 0,
display_values = False,
grid = False,
rounded_corners = False,
stack = False,
three_dimension = False,
x_labels = None,
y_labels = None,
x_bounds = None,
y_bounds = None,
series_colors = None,
main_dir = None):
self.bounds = {}
self.bounds[HORZ] = x_bounds
self.bounds[VERT] = y_bounds
self.display_values = display_values
self.grid = grid
self.rounded_corners = rounded_corners
self.stack = stack
self.three_dimension = three_dimension
self.x_label_angle = math.pi / 2.5
self.main_dir = main_dir
self.max_value = {}
self.plot_dimensions = {}
self.steps = {}
self.value_label_color = (0.5,0.5,0.5,1.0)
Plot.__init__(self, surface, data, width, height, background, border, x_labels, y_labels, series_colors)
def load_series(self, data, x_labels = None, y_labels = None, series_colors = None):
Plot.load_series(self, data, x_labels, y_labels, series_colors)
self.calc_boundaries()
def process_colors(self, series_colors):
#Data for a BarPlot might be a List or a List of Lists.
#On the first case, colors must be generated for all bars,
#On the second, colors must be generated for each of the inner lists.
if hasattr(self.data[0], '__getitem__'):
length = max(len(series) for series in self.data)
else:
length = len( self.data )
Plot.process_colors( self, series_colors, length, 'linear')
def calc_boundaries(self):
if not self.bounds[self.main_dir]:
if self.stack:
max_data_value = max(sum(serie) for serie in self.data)
else:
max_data_value = max(max(serie) for serie in self.data)
self.bounds[self.main_dir] = (0, max_data_value)
if not self.bounds[other_direction(self.main_dir)]:
self.bounds[other_direction(self.main_dir)] = (0, len(self.data))
def calc_extents(self, direction):
self.max_value[direction] = 0
if self.labels[direction]:
widest_word = max(self.labels[direction], key = lambda item: self.context.text_extents(item)[2])
self.max_value[direction] = self.context.text_extents(widest_word)[3 - direction]
self.borders[other_direction(direction)] = (2-direction)*self.max_value[direction] + self.border + direction*(5)
else:
self.borders[other_direction(direction)] = self.border
def calc_horz_extents(self):
self.calc_extents(HORZ)
def calc_vert_extents(self):
self.calc_extents(VERT)
def calc_all_extents(self):
self.calc_horz_extents()
self.calc_vert_extents()
other_dir = other_direction(self.main_dir)
self.value_label = 0
if self.display_values:
if self.stack:
self.value_label = self.context.text_extents(str(max(sum(serie) for serie in self.data)))[2 + self.main_dir]
else:
self.value_label = self.context.text_extents(str(max(max(serie) for serie in self.data)))[2 + self.main_dir]
if self.labels[self.main_dir]:
self.plot_dimensions[self.main_dir] = self.dimensions[self.main_dir] - 2*self.borders[self.main_dir] - self.value_label
else:
self.plot_dimensions[self.main_dir] = self.dimensions[self.main_dir] - self.borders[self.main_dir] - 1.2*self.border - self.value_label
self.plot_dimensions[other_dir] = self.dimensions[other_dir] - self.borders[other_dir] - self.border
self.plot_top = self.dimensions[VERT] - self.borders[VERT]
def calc_steps(self):
other_dir = other_direction(self.main_dir)
self.series_amplitude = self.bounds[self.main_dir][1] - self.bounds[self.main_dir][0]
if self.series_amplitude:
self.steps[self.main_dir] = float(self.plot_dimensions[self.main_dir])/self.series_amplitude
else:
self.steps[self.main_dir] = 0.00
series_length = len(self.data)
self.steps[other_dir] = float(self.plot_dimensions[other_dir])/(series_length + 0.1*(series_length + 1))
self.space = 0.1*self.steps[other_dir]
def render(self):
self.calc_all_extents()
self.calc_steps()
self.render_background()
self.render_bounding_box()
if self.grid:
self.render_grid()
if self.three_dimension:
self.render_ground()
if self.display_values:
self.render_values()
self.render_labels()
self.render_plot()
if self.series_labels:
self.render_legend()
def draw_3d_rectangle_front(self, x0, y0, x1, y1, shift):
self.context.rectangle(x0-shift, y0+shift, x1-x0, y1-y0)
def draw_3d_rectangle_side(self, x0, y0, x1, y1, shift):
self.context.move_to(x1-shift,y0+shift)
self.context.line_to(x1, y0)
self.context.line_to(x1, y1)
self.context.line_to(x1-shift, y1+shift)
self.context.line_to(x1-shift, y0+shift)
self.context.close_path()
def draw_3d_rectangle_top(self, x0, y0, x1, y1, shift):
self.context.move_to(x0-shift,y0+shift)
self.context.line_to(x0, y0)
self.context.line_to(x1, y0)
self.context.line_to(x1-shift, y0+shift)
self.context.line_to(x0-shift, y0+shift)
self.context.close_path()
def draw_round_rectangle(self, x0, y0, x1, y1):