-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleplot.py
427 lines (330 loc) · 13.9 KB
/
simpleplot.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
# -*- coding: latin-1 -*-
"""
simpleplot (September 1st, 2014)
Replace the simpleplot module of CodeSkulptor.
Require matplotlib_
(`Unofficial Windows Binaries`_)
(and must be installed separately).
Piece of SimpleGUICS2Pygame.
https://bitbucket.org/OPiMedia/simpleguics2pygame
GPLv3 --- Copyright (C) 2013, 2014 Olivier Pirson
http://www.opimedia.be/
.. _matplotlib: http://matplotlib.org/
.. _`Unofficial Windows Binaries`: http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib
"""
try:
import matplotlib.pyplot
except Exception as e:
import os
if os.environ.get('READTHEDOCS', None) != 'True':
raise Exception('matplotlib not installed! ' + str(e))
#
# Private global constant
##########################
_COLORS = ('#edc240', '#afd8f8', '#cb4b4b', '#4da74d',
'#9440ed', '#bd9b33', '#8cacc6', '#a23c3c',
'#3d853d', '#7633bd', '#ffe84c', '#d2ffff',
'#f35a5a', '#5cc85c', '#b14cff', '#8e7426',
'#698194', '#792d2d', '#2e642e', '#58268e',
'#ffff59', '#f4ffff', '#ff6969', '#6be96b',
'#cf59ff', '#5e4d19', '#455663', '#511d1d',
'#1e421e', '#3b195e', '#ffff66', '#ffffff')
"""
Color used for each graph.
**(Not available in SimpleGUI of CodeSkulptor.)**
"""
#
# Functions
############
def _block():
"""
If some plot windows are open
then block the program until closing all windows.
**(Not available in SimpleGUI of CodeSkulptor.)**
"""
matplotlib.pyplot.show()
def plot_bars(framename, width, height, xlabel, ylabel, datasets,
legends=None,
_block=False, _filename=None):
"""
Open a window titled `framename`
and plot graphes with `datasets` data
shown as vertical bars.
`xlabel` and `ylabel` are labels of x-axis and y-axis.
`datasets` must be a sequence of data.
Each data must be:
* Sequence (not empty) of pair x, y.
Each point (x, y) is represented by a vertical bar of height y.
* Or dict (not empty) x: y.
Each point (x, y) is represented by a vertical bar of height y.
If `legends` is not None
then it must be a sequence of legend of each graph.
If `_block`
then block the program until closing the window
else continue and close the window when program stop.
**(Option not available in SimpleGUI of CodeSkulptor.)**
If `_filename` is not None
then save the image to this file.
**(Option not available in SimpleGUI of CodeSkulptor.)**
:param framename: str
:param width: int > 0
:param height: int > 0
:param xlabel: str
:param ylabel: str
:param datasets: (list or tuple)
of (((list or tuple) of ([int or float, int or float]
or (int or float, int or float)))
or (dict (int or float): (int or float)))
:param legends: None or ((list or tuple) of same length as datasets)
:param _block: False
:param _filename: None or str
"""
assert isinstance(framename, str), type(framename)
assert isinstance(width, int), type(width)
assert width > 0, width
assert isinstance(height, int), type(height)
assert height > 0, height
assert isinstance(xlabel, str), type(xlabel)
assert isinstance(ylabel, str), type(ylabel)
assert isinstance(datasets, list) or isinstance(datasets, tuple), \
type(datasets)
if __debug__:
for dataset in datasets:
assert isinstance(dataset, list) or isinstance(dataset, tuple) \
or isinstance(dataset, dict), type(datasets)
assert dataset
for x, y in (dataset.items() if isinstance(dataset, dict)
else dataset):
assert isinstance(x, int) or isinstance(x, float), (type(x), x)
assert isinstance(y, int) or isinstance(y, float), (type(y), y)
assert ((legends is None) or isinstance(legends, list)
or isinstance(legends, tuple)), type(legends)
assert (legends is None) or (len(legends) == len(datasets)), legends
assert isinstance(_block, bool), type(_block)
assert (_filename is None) or isinstance(_filename, str), type(_filename)
fig = matplotlib.pyplot.figure()
fig.set_size_inches(width//fig.get_dpi(), height//fig.get_dpi(),
forward=True)
fig.canvas.set_window_title(framename)
matplotlib.pyplot.title(framename)
from os.path import sep
icon_path = __file__.split(sep)[:-1]
try:
icon_path.extend(('_img', 'SimpleGUICS2Pygame_32x32.ico'))
matplotlib.pyplot.get_current_fig_manager().window.wm_iconbitmap(
sep.join(icon_path))
except:
pass
matplotlib.pyplot.xlabel(xlabel)
matplotlib.pyplot.ylabel(ylabel)
matplotlib.pyplot.grid()
bar_width = 0.8/len(datasets)
for i, dataset in enumerate(datasets):
bar_lefts, bar_heights = zip(*(sorted(dataset.items())
if isinstance(dataset, dict)
else dataset))
matplotlib.pyplot.bar([x + bar_width*i for x in bar_lefts],
bar_heights,
width=bar_width,
color=_COLORS[i % len(_COLORS)],
edgecolor=_COLORS[i % len(_COLORS)],
figure=fig,
alpha=0.5)
ymin, ymax = matplotlib.pyplot.ylim()
matplotlib.pyplot.ylim(ymin, ymax + 1)
if legends is not None:
matplotlib.pyplot.legend(legends, loc='upper right')
matplotlib.pyplot.show(block=_block)
if _filename is not None:
matplotlib.pyplot.savefig(_filename)
def plot_lines(framename, width, height, xlabel, ylabel, datasets,
points=False, legends=None,
_block=False, _filename=None):
"""
Open a window titled `framename`
and plot graphes with `datasets` data
shown as connected lines.
`xlabel` and `ylabel` are labels of x-axis and y-axis.
`datasets` must be a sequence of data.
Each data must be:
* Sequence (not empty) of pair x, y.
Each point (x, y) is plotted (in given order)
and connected with line to previous and next points.
* Or dict (not empty) x: y.
Each point (x, y) is plotted (in ascending order of x value)
and connected with line to previous and next points.
If `points`
then each point is highlighted by a small disc
(a small circle in CodeSkulptor).
If `legends` is not None
then it must be a sequence of legend of each graph.
If `_block`
then block the program until closing the window
else continue and close the window when program stop.
**(Option not available in SimpleGUI of CodeSkulptor.)**
If `_filename` is not None
then save the image to this file.
**(Option not available in SimpleGUI of CodeSkulptor.)**
:param framename: str
:param width: int > 0
:param height: int > 0
:param xlabel: str
:param ylabel: str
:param datasets: (list or tuple)
of (((list or tuple) of ([int or float, int or float]
or (int or float, int or float)))
or (dict (int or float): (int or float)))
:param points: bool
:param legends: None or ((list or tuple) of same length as datasets)
:param _block: False
:param _filename: None or str
"""
assert isinstance(framename, str), type(framename)
assert isinstance(width, int), type(width)
assert width > 0, width
assert isinstance(height, int), type(height)
assert height > 0, height
assert isinstance(xlabel, str), type(xlabel)
assert isinstance(ylabel, str), type(ylabel)
assert isinstance(datasets, list) or isinstance(datasets, tuple), \
type(datasets)
if __debug__:
for dataset in datasets:
assert isinstance(dataset, list) or isinstance(dataset, tuple) \
or isinstance(dataset, dict), type(datasets)
assert dataset
for x, y in (dataset.items() if isinstance(dataset, dict)
else dataset):
assert isinstance(x, int) or isinstance(x, float), (type(x), x)
assert isinstance(y, int) or isinstance(y, float), (type(y), y)
assert isinstance(points, bool), type(points)
assert ((legends is None) or isinstance(legends, list)
or isinstance(legends, tuple)), type(legends)
assert (legends is None) or (len(legends) == len(datasets)), legends
assert isinstance(_block, bool), type(_block)
assert (_filename is None) or isinstance(_filename, str), type(_filename)
fig = matplotlib.pyplot.figure()
fig.set_size_inches(width//fig.get_dpi(), height//fig.get_dpi(),
forward=True)
fig.canvas.set_window_title(framename)
matplotlib.pyplot.title(framename)
from os.path import sep
icon_path = __file__.split(sep)[:-1]
try:
icon_path.extend(('_img', 'SimpleGUICS2Pygame_32x32.ico'))
matplotlib.pyplot.get_current_fig_manager().window.wm_iconbitmap(
sep.join(icon_path))
except:
pass
matplotlib.pyplot.xlabel(xlabel)
matplotlib.pyplot.ylabel(ylabel)
matplotlib.pyplot.grid()
for i, dataset in enumerate(datasets):
matplotlib.pyplot.plot(*zip(*(sorted(dataset.items())
if isinstance(dataset, dict)
else dataset)),
color=_COLORS[i % len(_COLORS)],
figure=fig,
marker=('o' if points
else None))
ymin, ymax = matplotlib.pyplot.ylim()
matplotlib.pyplot.ylim(ymin - 1, ymax + 1)
if legends is not None:
matplotlib.pyplot.legend(legends, loc='upper right')
matplotlib.pyplot.show(block=_block)
if _filename is not None:
matplotlib.pyplot.savefig(_filename)
def plot_scatter(framename, width, height, xlabel, ylabel, datasets,
legends=None,
_block=False, _filename=None):
"""
Open a window titled `framename`
and plot graphes with `datasets` data
shown as scattered points.
`xlabel` and `ylabel` are labels of x-axis and y-axis.
`datasets` must be a sequence of data.
Each data must be:
* Sequence (not empty) of pair x, y.
Each point (x, y) is represented by a circle.
* Or dict (not empty) x: y.
Each point (x, y) is represented by a circle.
If `legends` is not None
then it must be a sequence of legend of each graph.
If `_block`
then block the program until closing the window
else continue and close the window when program stop.
**(Option not available in SimpleGUI of CodeSkulptor.)**
If `_filename` is not None
then save the image to this file.
**(Option not available in SimpleGUI of CodeSkulptor.)**
:param framename: str
:param width: int > 0
:param height: int > 0
:param xlabel: str
:param ylabel: str
:param datasets: (list or tuple)
of (((list or tuple) of ([int or float, int or float]
or (int or float, int or float)))
or (dict (int or float): (int or float)))
:param legends: None or ((list or tuple) of same length as datasets)
:param _block: False
:param _filename: None or str
"""
assert isinstance(framename, str), type(framename)
assert isinstance(width, int), type(width)
assert width > 0, width
assert isinstance(height, int), type(height)
assert height > 0, height
assert isinstance(xlabel, str), type(xlabel)
assert isinstance(ylabel, str), type(ylabel)
assert isinstance(datasets, list) or isinstance(datasets, tuple), \
type(datasets)
if __debug__:
for dataset in datasets:
assert isinstance(dataset, list) or isinstance(dataset, tuple) \
or isinstance(dataset, dict), type(datasets)
assert dataset
for x, y in (dataset.items() if isinstance(dataset, dict)
else dataset):
assert isinstance(x, int) or isinstance(x, float), (type(x), x)
assert isinstance(y, int) or isinstance(y, float), (type(y), y)
assert ((legends is None) or isinstance(legends, list)
or isinstance(legends, tuple)), type(legends)
assert (legends is None) or (len(legends) == len(datasets)), legends
assert isinstance(_block, bool), type(_block)
assert (_filename is None) or isinstance(_filename, str), type(_filename)
fig = matplotlib.pyplot.figure()
fig.set_size_inches(width//fig.get_dpi(), height//fig.get_dpi(),
forward=True)
fig.canvas.set_window_title(framename)
matplotlib.pyplot.title(framename)
from os.path import sep
icon_path = __file__.split(sep)[:-1]
try:
icon_path.extend(('_img', 'SimpleGUICS2Pygame_32x32.ico'))
matplotlib.pyplot.get_current_fig_manager().window.wm_iconbitmap(
sep.join(icon_path))
except:
pass
matplotlib.pyplot.xlabel(xlabel)
matplotlib.pyplot.ylabel(ylabel)
matplotlib.pyplot.grid()
xmin = float('inf')
xmax = float('-inf')
for i, dataset in enumerate(datasets):
xs, ys = zip(*(sorted(dataset.items())
if isinstance(dataset, dict)
else dataset))
xmin = min(xmin, min(xs))
xmax = max(xmax, max(xs))
matplotlib.pyplot.scatter(xs,
ys,
color=_COLORS[i % len(_COLORS)],
edgecolor=_COLORS[i % len(_COLORS)],
figure=fig)
matplotlib.pyplot.xlim(xmin, xmax)
if legends is not None:
matplotlib.pyplot.legend(legends, loc='upper right')
matplotlib.pyplot.show(block=_block)
if _filename is not None:
matplotlib.pyplot.savefig(_filename)