forked from pyvista/pyvista
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotting.py
3252 lines (2680 loc) · 114 KB
/
plotting.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
"""
pyvista plotting module
"""
import collections
import ctypes
import logging
import os
import time
from threading import Thread
from subprocess import PIPE, Popen
import imageio
import numpy as np
import vtk
from vtk.util import numpy_support as VN
import pyvista
from pyvista.export import export_plotter_vtkjs
from pyvista.utilities import (get_scalar, is_pyvista_obj, numpy_to_texture, wrap,
_raise_not_matching, convert_array)
_ALL_PLOTTERS = {}
def close_all():
"""Close all open/active plotters"""
for key, p in _ALL_PLOTTERS.items():
p.close()
_ALL_PLOTTERS.clear()
return True
MAX_N_COLOR_BARS = 10
PV_BACKGROUND = [82/255., 87/255., 110/255.]
FONT_KEYS = {'arial': vtk.VTK_ARIAL,
'courier': vtk.VTK_COURIER,
'times': vtk.VTK_TIMES}
log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
rcParams = {
'background' : [0.3, 0.3, 0.3],
'camera' : {
'position' : [1, 1, 1],
'viewup' : [0, 0, 1],
},
'window_size' : [1024, 768],
'font' : {
'family' : 'courier',
'size' : 12,
'title_size': None,
'label_size' : None,
'color' : [1, 1, 1],
'fmt' : None,
},
'cmap' : 'jet',
'color' : 'white',
'nan_color' : 'darkgray',
'edge_color' : 'black',
'outline_color' : 'white',
'colorbar_orientation' : 'horizontal',
'colorbar_horizontal' : {
'width' : 0.60,
'height' : 0.08,
'position_x' : 0.35,
'position_y' : 0.02,
},
'colorbar_vertical' : {
'width' : 0.1,
'height' : 0.8,
'position_x' : 0.85,
'position_y' : 0.1,
},
'show_scalar_bar' : True,
'show_edges' : False,
'lighting' : True,
'interactive' : False,
'render_points_as_spheres' : False,
'use_panel' : True,
'transparent_background' : False
}
DEFAULT_THEME = dict(rcParams)
def set_plot_theme(theme):
"""Set the plotting parameters to a predefined theme"""
if theme.lower() in ['paraview', 'pv']:
rcParams['background'] = PV_BACKGROUND
rcParams['cmap'] = 'coolwarm'
rcParams['font']['family'] = 'arial'
rcParams['font']['label_size'] = 16
rcParams['show_edges'] = False
elif theme.lower() in ['document', 'doc', 'paper', 'report']:
rcParams['background'] = 'white'
rcParams['cmap'] = 'viridis'
rcParams['font']['size'] = 18
rcParams['font']['title_size'] = 18
rcParams['font']['label_size'] = 18
rcParams['font']['color'] = 'black'
rcParams['show_edges'] = False
rcParams['color'] = 'tan'
rcParams['outline_color'] = 'black'
elif theme.lower() in ['night', 'dark']:
rcParams['background'] = 'black'
rcParams['cmap'] = 'viridis'
rcParams['font']['color'] = 'white'
rcParams['show_edges'] = False
rcParams['color'] = 'tan'
rcParams['outline_color'] = 'white'
rcParams['edge_color'] = 'white'
elif theme.lower() in ['default']:
for k,v in DEFAULT_THEME.items():
rcParams[k] = v
def run_from_ipython():
""" returns True when run from IPython """
try:
py = __IPYTHON__
return True
except NameError:
return False
def opacity_transfer_function(key, n_colors):
"""Get the opacity transfer function results: range from 0 to 255
"""
transfer_func = {
'linear': np.linspace(0, 255, n_colors, dtype=np.uint8),
'linear_r': np.linspace(0, 255, n_colors, dtype=np.uint8)[::-1],
'geom': np.geomspace(1e-6, 255, n_colors, dtype=np.uint8),
'geom_r': np.geomspace(255, 1e-6, n_colors, dtype=np.uint8),
}
try:
return transfer_func[key]
except KeyError:
raise KeyError('opactiy transfer function ({}) unknown.'.format(key))
def plot(var_item, off_screen=None, full_screen=False,
screenshot=None, interactive=True, cpos=None,
window_size=None, show_bounds=False, show_axes=True,
notebook=None, background=None, text='', return_img=False,
eye_dome_lighting=False, use_panel=None, **kwargs):
"""Convenience plotting function for a vtk or numpy object.
Parameters
----------
item : vtk or numpy object
VTK object or numpy array to be plotted.
off_screen : bool
Plots off screen when True. Helpful for saving screenshots
without a window popping up.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores window_size.
Default False.
screenshot : str or bool, optional
Saves screenshot to file when enabled. See:
help(pyvistanterface.Plotter.screenshot). Default disabled.
When True, takes screenshot and returns numpy array of image.
window_size : list, optional
Window size in pixels. Defaults to [1024, 768]
show_bounds : bool, optional
Shows mesh bounds when True. Default False. Alias ``show_grid`` also
accepted.
notebook : bool, optional
When True, the resulting plot is placed inline a jupyter notebook.
Assumes a jupyter console is active.
show_axes : bool, optional
Shows a vtk axes widget. Enabled by default.
text : str, optional
Adds text at the bottom of the plot.
**kwargs : optional keyword arguments
See help(Plotter.add_mesh) for additional options.
Returns
-------
cpos : list
List of camera position, focal point, and view up.
img : numpy.ndarray
Array containing pixel RGB and alpha. Sized:
[Window height x Window width x 3] for transparent_background=False
[Window height x Window width x 4] for transparent_background=True
Returned only when screenshot enabled
"""
if notebook is None:
if run_from_ipython():
try:
notebook = type(get_ipython()).__module__.startswith('ipykernel.')
except NameError:
pass
if notebook:
off_screen = notebook
plotter = Plotter(off_screen=off_screen, notebook=notebook)
if show_axes:
plotter.add_axes()
plotter.set_background(background)
if isinstance(var_item, list):
if len(var_item) == 2: # might be arrows
isarr_0 = isinstance(var_item[0], np.ndarray)
isarr_1 = isinstance(var_item[1], np.ndarray)
if isarr_0 and isarr_1:
plotter.add_arrows(var_item[0], var_item[1])
else:
for item in var_item:
plotter.add_mesh(item, **kwargs)
else:
for item in var_item:
plotter.add_mesh(item, **kwargs)
else:
plotter.add_mesh(var_item, **kwargs)
if text:
plotter.add_text(text)
if show_bounds or kwargs.get('show_grid', False):
if kwargs.get('show_grid', False):
plotter.show_grid()
else:
plotter.show_bounds()
if cpos is None:
cpos = plotter.get_default_cam_pos()
plotter.camera_position = cpos
plotter.camera_set = False
else:
plotter.camera_position = cpos
if eye_dome_lighting:
plotter.enable_eye_dome_lighting()
result = plotter.show(window_size=window_size,
auto_close=False,
interactive=interactive,
full_screen=full_screen,
screenshot=screenshot,
return_img=return_img,
use_panel=use_panel)
# close and return camera position and maybe image
plotter.close()
# Result will be handled by plotter.show(): cpos or [cpos, img]
return result
def plot_arrows(cent, direction, **kwargs):
"""
Plots arrows as vectors
Parameters
----------
cent : np.ndarray
Accepts a single 3d point or array of 3d points.
directions : np.ndarray
Accepts a single 3d point or array of 3d vectors.
Must contain the same number of items as cent.
**kwargs : additional arguments, optional
See help(pyvista.Plot)
Returns
-------
Same as Plot. See help(pyvista.Plot)
"""
return plot([cent, direction], **kwargs)
def system_supports_plotting():
"""
Check if x server is running
Returns
-------
system_supports_plotting : bool
True when on Linux and running an xserver. Returns None when
on a non-linux platform.
"""
try:
if os.environ['ALLOW_PLOTTING'].lower() == 'true':
return True
except KeyError:
pass
try:
p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
p.communicate()
return p.returncode == 0
except:
return False
class BasePlotter(object):
"""
To be used by the Plotter and QtInteractor classes.
Parameters
----------
shape : list or tuple, optional
Number of sub-render windows inside of the main window.
Specify two across with ``shape=(2, 1)`` and a two by two grid
with ``shape=(2, 2)``. By default there is only one renderer.
border : bool, optional
Draw a border around each render window. Default False.
border_color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
border_width : float, optional
Width of the border in pixels when enabled.
"""
def __new__(cls, *args, **kwargs):
if cls is BasePlotter:
raise TypeError("pyvista.BasePlotter is an abstract class and may not be instantiated.")
return object.__new__(cls)
def __init__(self, shape=(1, 1), border=None, border_color='k',
border_width=1.0):
""" Initialize base plotter """
self.image_transparent_background = rcParams['transparent_background']
# by default add border for multiple plots
if border is None:
if shape != (1, 1):
border = True
else:
border = False
# add render windows
self.renderers = []
self._active_renderer_index = 0
assert_str = '"shape" should be a list or tuple'
assert isinstance(shape, collections.Iterable), assert_str
assert shape[0] > 0, '"shape" must be positive'
assert shape[1] > 0, '"shape" must be positive'
self.shape = shape
for i in reversed(range(shape[0])):
for j in range(shape[1]):
renderer = pyvista.Renderer(self, border, border_color, border_width)
x0 = i/shape[0]
y0 = j/shape[1]
x1 = (i+1)/shape[0]
y1 = (j+1)/shape[1]
renderer.SetViewport(y0, x0, y1, x1)
self.renderers.append(renderer)
# This keeps track of scalar names already plotted and their ranges
self._scalar_bar_ranges = {}
self._scalar_bar_mappers = {}
self._scalar_bar_actors = {}
self._scalar_bar_widgets = {}
self._actors = {}
# track if the camera has been setup
# self.camera_set = False
self._first_time = True
# Keep track of the scale
self._labels = []
# Set default style
self._style = vtk.vtkInteractorStyleRubberBandPick()
# Add self to open plotters
_ALL_PLOTTERS[str(hex(id(self)))] = self
# lighting style
self.lighting = vtk.vtkLightKit()
# self.lighting.SetHeadLightWarmth(1.0)
# self.lighting.SetHeadLightWarmth(1.0)
for renderer in self.renderers:
self.lighting.AddLightsToRenderer(renderer)
renderer.LightFollowCameraOn()
def update_style(self):
if not hasattr(self, '_style'):
self._style = vtk.vtkInteractorStyleTrackballCamera()
if hasattr(self, 'iren'):
return self.iren.SetInteractorStyle(self._style)
def enable_trackball_style(self):
""" sets the interactive style to trackball - the default syle """
self._style = vtk.vtkInteractorStyleTrackballCamera()
return self.update_style()
def enable_image_style(self):
""" sets the interactive style to image
Controls:
- Left Mouse button triggers window level events
- CTRL Left Mouse spins the camera around its view plane normal
- SHIFT Left Mouse pans the camera
- CTRL SHIFT Left Mouse dollys (a positional zoom) the camera
- Middle mouse button pans the camera
- Right mouse button dollys the camera.
- SHIFT Right Mouse triggers pick events
"""
self._style = vtk.vtkInteractorStyleImage()
return self.update_style()
def enable_joystick_style(self):
""" sets the interactive style to joystick
allows the user to move (rotate, pan, etc.) the camera, the point of
view for the scene. The position of the mouse relative to the center of
the scene determines the speed at which the camera moves, and the speed
of the mouse movement determines the acceleration of the camera, so the
camera continues to move even if the mouse if not moving.
For a 3-button mouse, the left button is for rotation, the right button
for zooming, the middle button for panning, and ctrl + left button for
spinning. (With fewer mouse buttons, ctrl + shift + left button is
for zooming, and shift + left button is for panning.)
"""
self._style = vtk.vtkInteractorStyleJoystickCamera()
return self.update_style()
def enable_zoom_style(self):
""" sets the interactive style to rubber band zoom
This interactor style allows the user to draw a rectangle in the render
window using the left mouse button. When the mouse button is released,
the current camera zooms by an amount determined from the shorter side
of the drawn rectangle.
"""
self._style = vtk.vtkInteractorStyleRubberBandZoom()
return self.update_style()
def enable_terrain_style(self):
""" sets the interactive style to terrain
Used to manipulate a camera which is viewing a scene with a natural
view up, e.g., terrain. The camera in such a scene is manipulated by
specifying azimuth (angle around the view up vector) and elevation
(the angle from the horizon).
"""
self._style = vtk.vtkInteractorStyleTerrain()
return self.update_style()
def enable_rubber_band_style(self):
""" sets the interactive style to rubber band picking
This interactor style allows the user to draw a rectangle in the render
window by hitting 'r' and then using the left mouse button.
When the mouse button is released, the attached picker operates on the
pixel in the center of the selection rectangle. If the picker happens to
be a vtkAreaPicker it will operate on the entire selection rectangle.
When the 'p' key is hit the above pick operation occurs on a 1x1
rectangle. In other respects it behaves the same as its parent class.
"""
self._style = vtk.vtkInteractorStyleRubberBandPick()
return self.update_style()
def set_focus(self, point):
""" sets focus to a point """
if isinstance(point, np.ndarray):
if point.ndim != 1:
point = point.ravel()
self.camera.SetFocalPoint(point)
self._render()
def set_position(self, point, reset=False):
""" sets camera position to a point """
if isinstance(point, np.ndarray):
if point.ndim != 1:
point = point.ravel()
self.camera.SetPosition(point)
if reset:
self.reset_camera()
self.camera_set = True
self._render()
def set_viewup(self, vector):
""" sets camera viewup vector """
if isinstance(vector, np.ndarray):
if vector.ndim != 1:
vector = vector.ravel()
self.camera.SetViewUp(vector)
self._render()
def _render(self):
""" redraws render window if the render window exists """
if hasattr(self, 'ren_win'):
if hasattr(self, 'render_trigger'):
self.render_trigger.emit()
elif not self._first_time:
self.render()
def add_axes(self, interactive=None, color=None, box=False, box_arguments=None):
""" Add an interactive axes widget """
if interactive is None:
interactive = rcParams['interactive']
if hasattr(self, 'axes_widget'):
self.axes_widget.SetInteractive(interactive)
self._update_axes_color(color)
return
# Chose widget type
if box:
if box_arguments is None:
box_arguments = {}
prop_assembly = create_axes_orientation_box(**box_arguments)
self.axes_actor = prop_assembly
else:
self.axes_actor = vtk.vtkAxesActor()
self.axes_widget = vtk.vtkOrientationMarkerWidget()
self.axes_widget.SetOrientationMarker(self.axes_actor)
if hasattr(self, 'iren'):
self.axes_widget.SetInteractor(self.iren)
self.axes_widget.SetEnabled(1)
self.axes_widget.SetInteractive(interactive)
# Set the color
self._update_axes_color(color)
def hide_axes(self):
"""Hide the axes orientation widget"""
if hasattr(self, 'axes_widget'):
self.axes_widget.EnabledOff()
def show_axes(self):
"""Show the axes orientation widget"""
if hasattr(self, 'axes_widget'):
self.axes_widget.EnabledOn()
else:
self.add_axes()
def key_press_event(self, obj, event):
""" Listens for key press event """
key = self.iren.GetKeySym()
log.debug('Key %s pressed' % key)
if key == 'q':
self.q_pressed = True
# Grab screenshot right before renderer closes
self.last_image = self.screenshot(True, return_img=True)
elif key == 'b':
self.observer = self.iren.AddObserver('LeftButtonPressEvent',
self.left_button_down)
elif key == 'v':
self.isometric_view_interactive()
def left_button_down(self, obj, event_type):
"""Register the event for a left button down click"""
# Get 2D click location on window
click_pos = self.iren.GetEventPosition()
# Get corresponding click location in the 3D plot
picker = vtk.vtkWorldPointPicker()
picker.Pick(click_pos[0], click_pos[1], 0, self.renderer)
self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
if np.any(np.isnan(self.pickpoint)):
self.pickpoint[:] = 0
def isometric_view_interactive(self):
""" sets the current interactive render window to isometric view """
interactor = self.iren.GetInteractorStyle()
renderer = interactor.GetCurrentRenderer()
renderer.view_isometric()
def update(self, stime=1, force_redraw=True):
"""
Update window, redraw, process messages query
Parameters
----------
stime : int, optional
Duration of timer that interrupt vtkRenderWindowInteractor in
milliseconds.
force_redraw : bool, optional
Call vtkRenderWindowInteractor.Render() immediately.
"""
if stime <= 0:
stime = 1
curr_time = time.time()
if Plotter.last_update_time > curr_time:
Plotter.last_update_time = curr_time
if not hasattr(self, 'iren'):
return
update_rate = self.iren.GetDesiredUpdateRate()
if (curr_time - Plotter.last_update_time) > (1.0/update_rate):
self.right_timer_id = self.iren.CreateRepeatingTimer(stime)
self.iren.Start()
self.iren.DestroyTimer(self.right_timer_id)
self._render()
Plotter.last_update_time = curr_time
else:
if force_redraw:
self.iren.Render()
def add_mesh(self, mesh, color=None, style=None, scalars=None,
rng=None, stitle=None, show_edges=None,
point_size=5.0, opacity=1.0, line_width=None,
flip_scalars=False, lighting=None, n_colors=256,
interpolate_before_map=False, cmap=None, label=None,
reset_camera=None, scalar_bar_args=None,
multi_colors=False, name=None, texture=None,
render_points_as_spheres=None, smooth_shading=False,
render_lines_as_tubes=False, edge_color=None,
ambient=0.0, show_scalar_bar=None, nan_color=None,
nan_opacity=1.0, loc=None, backface_culling=False,
rgb=False, categories=False, **kwargs):
"""
Adds a unstructured, structured, or surface mesh to the
plotting object.
Also accepts a 3D numpy.ndarray
Parameters
----------
mesh : vtk unstructured, structured, polymesh, or 3D numpy.ndarray
A vtk unstructured, structured, or polymesh to plot.
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
Color will be overridden when scalars are input.
style : string, optional
Visualization style of the vtk mesh. One for the following:
style='surface'
style='wireframe'
style='points'
Defaults to 'surface'
scalars : numpy array, optional
Scalars used to "color" the mesh. Accepts an array equal
to the number of cells or the number of points in the
mesh. Array should be sized as a single vector. If both
color and scalars are None, then the active scalars are
used
rng : 2 item list, optional
Range of mapper for scalars. Defaults to minimum and
maximum of scalars array. Example: ``[-1, 2]``. ``clim``
is also an accepted alias for this.
stitle : string, optional
Scalar title. By default there is no scalar legend bar.
Setting this creates the legend bar and adds a title to
it. To create a bar with no title, use an empty string
(i.e. '').
show_edges : bool, optional
Shows the edges of a mesh. Does not apply to a wireframe
representation.
point_size : float, optional
Point size. Applicable when style='points'. Default 5.0
opacity : float, optional
Opacity of mesh. Should be between 0 and 1. Default 1.0.
A string option can also be specified to map the scalar range
to the opacity. Options are: linear, linear_r, geom, geom_r
line_width : float, optional
Thickness of lines. Only valid for wireframe and surface
representations. Default None.
flip_scalars : bool, optional
Flip direction of cmap.
lighting : bool, optional
Enable or disable view direction lighting. Default False.
n_colors : int, optional
Number of colors to use when displaying scalars. Default
256.
interpolate_before_map : bool, optional
Enabling makes for a smoother scalar display. Default
False
cmap : str, optional
cmap string. See available matplotlib cmaps. Only
applicable for when displaying scalars. Defaults None
(rainbow). Requires matplotlib.
multi_colors : bool, optional
If a ``MultiBlock`` dataset is given this will color each
block by a solid color using matplotlib's color cycler.
name : str, optional
The name for the added mesh/actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
texture : vtk.vtkTexture or np.ndarray or boolean, optional
A texture to apply if the input mesh has texture
coordinates. This will not work with MultiBlock
datasets. If set to ``True``, the first avaialble texture
on the object will be used. If a string name is given, it
will pull a texture with that name associated to the input
mesh.
ambient : float, optional
When lighting is enabled, this is the amount of light from
0 to 1 that reaches the actor when not directed at the
light source emitted from the viewer. Default 0.2.
nan_color : string or 3 item list, optional, defaults to gray
The color to use for all NaN values in the plotted scalar
array.
nan_opacity : float, optional
Opacity of NaN values. Should be between 0 and 1.
Default 1.0
backface_culling : bool optional
Does not render faces that should not be visible to the
plotter. This can be helpful for dense surface meshes,
especially when edges are visible, but can cause flat
meshes to be partially displayed. Default False.
rgb : bool, optional
If an 2 dimensional array is passed as the scalars, plot those
values as RGB+A colors! ``rgba`` is also accepted alias for this.
categories : bool, optional
If fetching a colormap from matplotlib, this is the number of
categories to use in that colormap. If set to ``True``, then
the number of unique values in the scalar array will be used.
Returns
-------
actor: vtk.vtkActor
VTK actor of the mesh.
"""
if scalar_bar_args is None:
scalar_bar_args = {}
if isinstance(mesh, np.ndarray):
mesh = pyvista.PolyData(mesh)
style = 'points'
# Convert the VTK data object to a pyvista wrapped object if neccessary
if not is_pyvista_obj(mesh):
mesh = wrap(mesh)
# Compute surface normals if using smooth shading
if smooth_shading:
# extract surface if mesh is exterior
if isinstance(mesh, (pyvista.UnstructuredGrid, pyvista.StructuredGrid)):
grid = mesh
mesh = grid.extract_surface()
ind = mesh.point_arrays['vtkOriginalPointIds']
# remap scalars
if scalars is not None:
scalars = scalars[ind]
mesh.compute_normals(cell_normals=False, inplace=True)
if show_edges is None:
show_edges = rcParams['show_edges']
if edge_color is None:
edge_color = rcParams['edge_color']
if show_scalar_bar is None:
show_scalar_bar = rcParams['show_scalar_bar']
if lighting is None:
lighting = rcParams['lighting']
if rng is None:
rng = kwargs.get('clim', None)
if render_points_as_spheres is None:
render_points_as_spheres = rcParams['render_points_as_spheres']
if name is None:
name = '{}({})'.format(type(mesh).__name__, str(hex(id(mesh))))
if isinstance(mesh, pyvista.MultiBlock):
self.remove_actor(name, reset_camera=reset_camera)
# frist check the scalars
if rng is None and scalars is not None:
# Get the data range across the array for all blocks
# if scalar specified
if isinstance(scalars, str):
rng = mesh.get_data_range(scalars)
else:
# TODO: an array was given... how do we deal with
# that? Possibly a 2D arrays or list of
# arrays where first index corresponds to
# the block? This could get complicated real
# quick.
raise RuntimeError('Scalar array must be given as a string name for multiblock datasets.')
if multi_colors:
# Compute unique colors for each index of the block
try:
import matplotlib as mpl
from itertools import cycle
cycler = mpl.rcParams['axes.prop_cycle']
colors = cycle(cycler)
except ImportError:
multi_colors = False
logging.warning('Please install matplotlib for color cycles')
# Now iteratively plot each element of the multiblock dataset
actors = []
for idx in range(mesh.GetNumberOfBlocks()):
if mesh[idx] is None:
continue
# Get a good name to use
next_name = '{}-{}'.format(name, idx)
# Get the data object
if not is_pyvista_obj(mesh[idx]):
data = wrap(mesh.GetBlock(idx))
if not is_pyvista_obj(mesh[idx]):
continue # move on if we can't plot it
else:
data = mesh.GetBlock(idx)
if data is None:
# Note that a block can exist but be None type
continue
# Now check that scalars is available for this dataset
if isinstance(data, vtk.vtkMultiBlockDataSet) or get_scalar(data, scalars) is None:
ts = None
else:
ts = scalars
if multi_colors:
color = next(colors)['color']
a = self.add_mesh(data, color=color, style=style,
scalars=ts, rng=rng, stitle=stitle,
show_edges=show_edges,
point_size=point_size, opacity=opacity,
line_width=line_width,
flip_scalars=flip_scalars,
lighting=lighting, n_colors=n_colors,
interpolate_before_map=interpolate_before_map,
cmap=cmap, label=label,
scalar_bar_args=scalar_bar_args,
reset_camera=reset_camera, name=next_name,
texture=None,
render_points_as_spheres=render_points_as_spheres,
render_lines_as_tubes=render_lines_as_tubes,
edge_color=edge_color,
show_scalar_bar=show_scalar_bar, nan_color=nan_color,
nan_opacity=nan_opacity,
loc=loc, rgb=rgb, **kwargs)
actors.append(a)
if (reset_camera is None and not self.camera_set) or reset_camera:
cpos = self.get_default_cam_pos()
self.camera_position = cpos
self.camera_set = False
self.reset_camera()
return actors
if nan_color is None:
nan_color = rcParams['nan_color']
nanr, nanb, nang = parse_color(nan_color)
nan_color = nanr, nanb, nang, nan_opacity
if color is True:
color = rcParams['color']
if mesh.n_points < 1:
raise RuntimeError('Empty meshes cannot be plotted. Input mesh has zero points.')
# set main values
self.mesh = mesh
self.mapper = vtk.vtkDataSetMapper()
self.mapper.SetInputData(self.mesh)
if isinstance(scalars, str):
self.mapper.SetArrayName(scalars)
actor, prop = self.add_actor(self.mapper,
reset_camera=reset_camera,
name=name, loc=loc, culling=backface_culling)
# Try to plot something if no preference given
if scalars is None and color is None and texture is None:
# Prefer texture first
if len(list(mesh.textures.keys())) > 0:
texture = True
# If no texture, plot any active scalar
else:
# Make sure scalar components are not vectors/tuples
scalars = mesh.active_scalar
# Don't allow plotting of string arrays by default
if scalars is not None and np.issubdtype(scalars.dtype, np.number):
if stitle is None:
stitle = mesh.active_scalar_info[1]
else:
scalars = None
if texture == True or isinstance(texture, (str, int)):
texture = mesh._activate_texture(texture)
if texture:
if isinstance(texture, np.ndarray):
texture = numpy_to_texture(texture)
if not isinstance(texture, (vtk.vtkTexture, vtk.vtkOpenGLTexture)):
raise TypeError('Invalid texture type ({})'.format(type(texture)))
if mesh.GetPointData().GetTCoords() is None:
raise AssertionError('Input mesh does not have texture coordinates to support the texture.')
actor.SetTexture(texture)
# Set color to white by default when using a texture
if color is None:
color = 'white'
if scalars is None:
show_scalar_bar = False
self.mapper.SetScalarModeToUsePointFieldData()
# Scalar formatting ===================================================
if cmap is None: # grab alias for cmaps: colormap
cmap = kwargs.get('colormap', None)
if cmap is None: # Set default map if matplotlib is avaialble
try:
import matplotlib
cmap = rcParams['cmap']
except ImportError:
pass
title = 'Data' if stitle is None else stitle
if scalars is not None:
# if scalars is a string, then get the first array found with that name
append_scalars = True
if isinstance(scalars, str):
title = scalars
scalars = get_scalar(mesh, scalars,
preference=kwargs.get('preference', 'cell'), err=True)
if stitle is None:
stitle = title
#append_scalars = False
if not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if not np.issubdtype(scalars.dtype, np.number):
raise TypeError('Non-numeric scalars are currently not supported for plotting.')
if rgb is False or rgb is None:
rgb = kwargs.get('rgba', False)
if rgb:
if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4:
raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.')
if scalars.ndim != 1:
if rgb:
pass
elif scalars.ndim == 2 and (scalars.shape[0] == mesh.n_points or scalars.shape[0] == mesh.n_cells):
scalars = np.linalg.norm(scalars.copy(), axis=1)
title = '{}-normed'.format(title)
else:
scalars = scalars.ravel()
if scalars.dtype == np.bool:
scalars = scalars.astype(np.float)
# Scalar interpolation approach
if scalars.shape[0] == mesh.n_points:
self.mesh._add_point_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUsePointData()
self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors)
if interpolate_before_map:
self.mapper.InterpolateScalarsBeforeMappingOn()
elif scalars.shape[0] == mesh.n_cells:
self.mesh._add_cell_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUseCellData()
self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors)
if interpolate_before_map:
self.mapper.InterpolateScalarsBeforeMappingOn()
else:
_raise_not_matching(scalars, mesh)
# Set scalar range
if rng is None:
rng = [np.nanmin(scalars), np.nanmax(scalars)]