/
plotter.py
712 lines (560 loc) · 21.1 KB
/
plotter.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
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import os
import shutil
import subprocess
from contextlib import contextmanager
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from compas_plotters.core.drawing import create_axes_xy
from compas_plotters.core.drawing import draw_xpoints_xy
from compas_plotters.core.drawing import draw_xlines_xy
from compas_plotters.core.drawing import draw_xpolylines_xy
from compas_plotters.core.drawing import draw_xpolygons_xy
from compas_plotters.core.drawing import draw_xarrows_xy
__all__ = ['Plotter']
class Plotter(object):
"""Definition of a plotter object based on matplotlib.
Parameters
----------
figsize : tuple, optional
The size of the plot in inches (width, length). Default is ``(16.0, 12.0)``.
Other Parameters
----------------
dpi : float, optional
The resolution of the plot.
Default is ``100.0``.
tight : bool, optional
Produce a plot with limited padding between the plot and the edge of the figure.
Default is ``True``.
fontsize : int, optional
The size of the font used in labels. Default is ``10``.
axes : matplotlib.axes.Axes, optional
An instance of ``matplotlib`` ``Axes``.
For example to share the axes of a figure between different plotters.
Default is ``None`` in which case the plotter will make its own axes.
Attributes
----------
defaults : dict
Dictionary containing default attributes for vertices and edges.
* point.radius : ``0.1``
* point.facecolor : ``'#ffffff'``
* point.edgecolor : ``'#000000'``
* point.edgewidth : ``0.5``
* point.textcolor : ``'#000000'``
* point.fontsize : ``10``
* line.width : ``1.0``
* line.color : ``'#000000'``
* line.textcolor : ``'#000000'``
* line.fontsize : ``10``
* polygon.facecolor : ``'#ffffff'``
* polygon.edgecolor : ``'#000000'``
* polygon.edgewidth : ``0.1``
* polygon.textcolor : ``'#000000'``
* polygon.fontsize : ``10``
Notes
-----
For more info, see [1]_.
References
----------
.. [1] Hunter, J. D., 2007. *Matplotlib: A 2D graphics environment*.
Computing In Science & Engineering (9) 3, p.90-95.
Available at: http://ieeexplore.ieee.org/document/4160265/citations.
Examples
--------
.. plot::
:include-source:
import compas
from compas.datastructures import Mesh
from compas_plotters import Plotter
mesh = Mesh.from_obj(compas.get('faces.obj'))
plotter = Plotter(figsize=(10, 7))
points = []
for key in mesh.vertices():
points.append({
'pos' : mesh.vertex_coordinates(key),
'radius' : 0.1,
'facecolor': '#ffffff'
})
lines = []
for u, v in mesh.edges():
lines.append({
'start': mesh.vertex_coordinates(u),
'end' : mesh.vertex_coordinates(v),
'width': 1.0
})
plotter.draw_points(points)
plotter.draw_lines(lines)
plotter.show()
"""
def __init__(self, figsize=(16.0, 12.0), dpi=100.0, tight=True, axes=None, **kwargs):
"""Initialises a plotter object"""
self._axes = None
self.axes = axes
self.tight = tight
# use descriptors for these
# to help the user set these attributes in the right format
# figure attributes
self.figure_size = figsize
self.figure_dpi = dpi
self.figure_bgcolor = '#ffffff'
# axes attributes
self.axes_xlabel = None
self.axes_ylabel = None
# drawing defaults
# z-order
# color
# size/thickness
self.defaults = {
'point.radius' : 0.1,
'point.facecolor' : '#ffffff',
'point.edgecolor' : '#000000',
'point.edgewidth' : 0.5,
'point.textcolor' : '#000000',
'point.fontsize' : kwargs.get('fontsize', 10),
'line.width' : 1.0,
'line.color' : '#000000',
'line.textcolor': '#000000',
'line.fontsize' : kwargs.get('fontsize', 10),
'polygon.facecolor' : '#ffffff',
'polygon.edgecolor' : '#000000',
'polygon.edgewidth' : 0.1,
'polygon.textcolor' : '#000000',
'polygon.fontsize' : kwargs.get('fontsize', 10),
}
@property
def axes(self):
"""Returns the axes subplot matplotlib object.
Returns
-------
Axes
The matplotlib axes object.
Notes
-----
For more info, see the documentation of the Axes class ([1]_) and the
axis and tick API ([2]_).
References
----------
.. [1] https://matplotlib.org/api/axes_api.html
.. [2] https://matplotlib.org/api/axis_api.html
"""
if self._axes is None:
self._axes = create_axes_xy(
figsize=self.figure_size,
dpi=self.figure_dpi,
xlabel=self.axes_xlabel,
ylabel=self.axes_ylabel
)
return self._axes
@axes.setter
def axes(self, axes):
self._axes = axes
@property
def figure(self):
"""Returns the matplotlib figure instance.
Returns
-------
Figure
The matplotlib figure instance.
Notes
-----
For more info, see the figure API ([1]_).
References
----------
.. [1] https://matplotlib.org/2.0.2/api/figure_api.html
"""
return self.axes.get_figure()
@property
def canvas(self):
"""Returns the canvas of the figure instance.
"""
return self.figure.canvas
@property
def bgcolor(self):
"""Returns the background color.
Returns
-------
str
The color as a string (hex colors).
"""
return self.figure.get_facecolor()
@bgcolor.setter
def bgcolor(self, value):
"""Sets the background color.
Parameters
----------
value : str, tuple
The color specififcation for the figure background.
Colors should be specified in the form of a string (hex colors) or
as a tuple of normalized RGB components.
"""
self.figure.set_facecolor(value)
@property
def title(self):
"""Returns the title of the plot.
Returns
-------
str
The title of the plot.
"""
return self.figure.canvas.get_window_title()
@title.setter
def title(self, value):
"""Sets the title of the plot.
Parameters
----------
value : str
The title of the plot.
"""
self.figure.canvas.set_window_title(value)
def register_listener(self, listener):
"""Register a listener for pick events.
Parameters
----------
listener : callable
The handler for pick events.
Returns
-------
None
Notes
-----
For more information, see the docs of ``mpl_connect`` ([1]_), and on event
handling and picking ([2]_).
References
----------
.. [1] https://matplotlib.org/api/backend_bases_api.html#matplotlib.backend_bases.FigureCanvasBase.mpl_connect
.. [2] https://matplotlib.org/users/event_handling.html
Examples
--------
.. code-block:: python
#
"""
self.figure.canvas.mpl_connect('pick_event', listener)
def clear_collection(self, collection):
"""Clears a matplotlib collection object.
Parameters
----------
collection : object
The matplotlib collection object.
Notes
-----
For more info, see [1]_ and [2]_.
References
----------
.. [1] https://matplotlib.org/2.0.2/api/collections_api.html
.. [2] https://matplotlib.org/2.0.2/api/collections_api.html#matplotlib.collections.Collection.remove
"""
collection.remove()
def show(self, autoscale=True):
"""Displays the plot.
"""
if autoscale:
self.axes.autoscale()
if self.tight:
plt.tight_layout()
plt.show()
def top(self):
"""Bring the plotting window to the top.
Warning
-------
This seems to work only for some back-ends.
Notes
-----
For more info, see this SO post [1]_.
References
----------
.. [1] https://stackoverflow.com/questions/20025077/how-do-i-display-a-matplotlib-figure-window-on-top-of-all-other-windows-in-spyde
"""
self.figure.canvas.manager.show()
def save(self, filepath, **kwargs):
"""Saves the plot to a file.
Parameters
----------
filepath : str
Full path of the file.
Notes
-----
For an overview of all configuration options, see [1]_.
References
----------
.. [1] https://matplotlib.org/2.0.2/api/pyplot_api.html#matplotlib.pyplot.savefig
"""
self.axes.autoscale()
plt.savefig(filepath, **kwargs)
@contextmanager
def gifified(self, func, tempfolder, outfile, pattern='image_{}.png'):
"""Create a context for making animated gifs using a callback for updating the plot.
Parameters
----------
func : callable
The callback function used to update the plot.
tempfolder : str
The path to a folder for storing temporary image frames.
outfile : str
Path to the file where the resultshould be saved.
pattern : str, optional
Pattern for the filename of the intermediate frames.
The pattern should contain a replacement placeholder for the number
of the frame. Default is ``'image_{}.png'``.
Examples
--------
.. code-block:: python
#
"""
images = []
def gifify(f):
def wrapper(*args, **kwargs):
f(*args, **kwargs)
image = os.path.join(tempfolder, pattern.format(len(images)))
images.append(image)
self.save(image)
return wrapper
if not os.path.exists(tempfolder) or not os.path.isdir(tempfolder):
os.makedirs(tempfolder)
for file in os.listdir(tempfolder):
filepath = os.path.join(tempfolder, file)
try:
if os.path.isfile(filepath):
os.remove(filepath)
except Exception as e:
print(e)
image = os.path.join(tempfolder, pattern.format(len(images)))
images.append(image)
self.save(image)
#
yield gifify(func)
#
self.save_gif(outfile, images)
shutil.rmtree(tempfolder)
print('done gififying!')
def save_gif(self, filepath, images, delay=10, loop=0):
"""Save a series of images as an animated gif.
Parameters
----------
filepath : str
The full path to the output file.
images : list
A list of paths to input files.
delay : int, optional
The delay between frames in milliseconds. Default is ``10``.
loop : int, optional
The number of loops. Default is ``0``.
Returns
-------
None
Warning
-------
This function assumes ImageMagick is installed on your system, and on
*convert* being on your system path.
Examples
--------
.. code-block:: python
#
"""
command = ['convert', '-delay', '{}'.format(delay), '-loop', '{}'.format(loop), '-layers', 'optimize']
subprocess.call(command + images + [filepath])
def draw_points(self, points):
"""Draws points on a 2D plot.
Parameters
----------
points : list of dict
List of dictionaries containing the point properties.
Each point is represented by a circle with a given radius.
The following properties of the circle can be specified in the point dict.
* pos (list): XY(Z) coordinates
* radius (float, optional): the radius of the circle. Default is 0.1.
* text (str, optional): the text of the label. Default is None.
* facecolor (rgb or hex color, optional): The color of the face of the circle. Default is white.
* edgecolor (rgb or hex color, optional): The color of the edge of the cicrle. Default is black.
* edgewidth (float, optional): The width of the edge of the circle. Default is 1.0.
* textcolor (rgb or hex color, optional): Color of the text label. Default is black.
* fontsize (int, optional): Font size of the text label. Default is 12.
Returns
-------
object
The matplotlib point collection object.
Notes
-----
...
See Also
--------
:func:`compas_plotters.core.draw_xpoints_xy`
Examples
--------
>>>
"""
return draw_xpoints_xy(points, self.axes)
def draw_lines(self, lines):
"""Draws lines on a 2D plot.
Parameters
----------
lines : list of dict
List of dictionaries containing the line properties.
The following properties of a line can be specified in the dict.
* start (list): XY(Z) coordinates of the start point.
* end (list): XY(Z) coordinatesof the end point.
* width (float, optional): The width of the line. Default is ``1.0``.
* color (rgb tuple or hex string, optional): The color of the line. Default is black.
* text (str, optional): The text of the label. Default is ``None``.
* textcolor (rgb tuple or hex string, optional): Color of the label text. Default is black.
* fontsize (int, optional): The size of the font of the label text. Default is ```12``.
Returns
-------
object
The matplotlib line collection object.
See Also
--------
:func:`compas_plotters.core.draw_xlines_xy`
"""
return draw_xlines_xy(lines, self.axes)
def draw_polylines(self, polylines):
"""Draw polylines on a 2D plot.
Parameters
----------
polylines : list of dict
A list of dictionaries containing the polyline properties.
The following properties are supported:
* points (list): XY(Z) coordinates of the polygon vertices.
* text (str, optional): The text of the label. Default is ``None``.
* textcolor (rgb tuple or hex string, optional): Color of the label text. Default is black.
* fontsize (int, optional): The size of the font of the label text. Default is ```12``.
* facecolor (rgb tuple or hex string, optional): Color of the polygon face. Default is white.
* edgecolor (rgb tuple or hex string, optional): Color of the edge of the polygon. Default is black.
* edgewidth (float): Width of the polygon edge. Default is ``1.0``.
Returns
-------
object
The matplotlib polyline collection object.
"""
return draw_xpolylines_xy(polylines, self.axes)
def draw_polygons(self, polygons):
"""Draws polygons on a 2D plot.
Parameters
----------
polygons : list of dict
List of dictionaries containing the polygon properties.
The following properties can be specified in the dict.
* points (list): XY(Z) coordinates of the polygon vertices.
* text (str, optional): The text of the label. Default is ``None``.
* textcolor (rgb tuple or hex string, optional): Color of the label text. Default is black.
* fontsize (int, optional): The size of the font of the label text. Default is ```12``.
* facecolor (rgb tuple or hex string, optional): Color of the polygon face. Default is white.
* edgecolor (rgb tuple or hex string, optional): Color of the edge of the polygon. Default is black.
* edgewidth (float): Width of the polygon edge. Default is ``1.0``.
Returns
-------
object
The matplotlib polygon collection object.
"""
return draw_xpolygons_xy(polygons, self.axes)
def draw_arrows(self, arrows):
"""Draws arrows on a 2D plot.
Parameters
----------
arrows : list of dict
List of dictionaries containing the arrow properties.
The following properties of an arrow can be specified in the dict.
* start (list): XY(Z) coordinates of the starting point.
* end (list): XY(Z) coordinates of the end point.
* text (str, optional): The text of the label. Default is ``None``.
* textcolor (rgb tuple or hex string, optional): Color of the label text. Default is black.
* fontsize (int, optional): The size of the font of the label text. Default is ```6``.
* color (rgb tuple or hex string, optional): Color of the arrow. Default is black.
* width (float): Width of the arrow. Default is ``1.0``.
Returns
-------
object
The matplotlib arrow collection object.
See Also
--------
:func:`compas_plotters.core.draw_xarrows_xy`
"""
return draw_xarrows_xy(arrows, self.axes)
def update(self, pause=0.0001):
"""Updates and pauses the plot.
Parameters
----------
pause : float
Ammount of time to pause the plot in seconds.
"""
self.axes.autoscale()
if self.tight:
plt.tight_layout()
plt.pause(pause)
def update_pointcollection(self, collection, centers, radius=1.0):
"""Updates the location and radii of a point collection.
Parameters
----------
collection : object
The point collection to update.
centers : list
List of tuples or lists with XY(Z) location for the points in the collection.
radius : float or list, optional
The radii of the points. If a floar is given it will be used for all points.
"""
try:
len(radius)
except Exception:
radius = [radius] * len(centers)
data = zip(centers, radius)
circles = [Circle(c[0:2], r) for c, r in data]
collection.set_paths(circles)
def update_linecollection(self, collection, segments):
"""Updates a line collection.
Parameters
----------
collection : object
The line collection to update.
segments : list
List of tuples or lists with XY(Z) location for the start and end
points in each line in the collection.
"""
collection.set_segments([(start[0:2], end[0:2]) for start, end in segments])
def update_polygoncollection(self, collection, polygons):
raise NotImplementedError
# ==============================================================================
# Main
# ==============================================================================
if __name__ == "__main__":
import compas
from compas.datastructures import Mesh
from compas.geometry import smooth_centroid
mesh = Mesh.from_obj(compas.get('faces.obj'))
fixed = [key for key in mesh.vertices() if mesh.vertex_degree(key) == 2]
points = []
for key in mesh.vertices():
points.append({
'pos': mesh.vertex_coordinates(key),
'radius': 0.1,
'facecolor': '#ff0000' if mesh.vertex_degree(key) == 2 else '#ffffff'
})
lines = []
for u, v in mesh.edges():
lines.append({
'start': mesh.vertex_coordinates(u),
'end': mesh.vertex_coordinates(v),
'width': 1.0
})
plotter = Plotter(figsize=(10, 6))
plotter.draw_arrows(lines)
# pcoll = plotter.draw_points(points)
# lcoll = plotter.draw_lines(lines)
# def callback(k, args):
# plotter.update_pointcollection(pcoll, vertices, 0.1)
# segments = []
# for u, v in mesh.edges():
# a = vertices[u][0:2]
# b = vertices[v][0:2]
# segments.append([a, b])
# plotter.update_linecollection(lcoll, segments)
# plotter.update(pause=0.001)
# vertices = [mesh.vertex_coordinates(key) for key in mesh.vertices()]
# adjacency = [mesh.vertex_neighbors(key) for key in mesh.vertices()]
# smooth_centroid(vertices,
# adjacency,
# fixed=fixed,
# kmax=100,
# callback=callback)
plotter.show()