0
# Plotting and Visualization
1
2
PyVista's plotting system provides comprehensive 3D visualization capabilities built on VTK's rendering pipeline with intuitive Python interfaces for creating publication-quality figures and interactive visualizations.
3
4
## Capabilities
5
6
### Core Plotting Interface
7
8
#### Main Plotting Functions
9
10
Simple plotting functions for quick visualization.
11
12
```python { .api }
13
def plot(*args, show=True, return_plotter=False, **kwargs):
14
"""
15
Plot datasets with automatic type detection.
16
17
Parameters:
18
*args: Datasets, numpy arrays, or other plottable objects
19
show (bool): Display the plot immediately
20
return_plotter (bool): Return the plotter object
21
**kwargs: Additional plotting parameters
22
23
Returns:
24
None or Plotter: Plotter object if return_plotter=True
25
"""
26
```
27
28
#### Plotter Class
29
30
Main plotting interface providing full control over 3D scenes.
31
32
```python { .api }
33
class Plotter:
34
"""
35
Main plotting class for creating 3D visualizations.
36
37
Attributes:
38
camera: Camera - Scene camera object
39
renderer: Renderer - VTK renderer
40
render_window: object - VTK render window
41
mesh: object - Currently active mesh
42
mapper: object - Currently active mapper
43
"""
44
45
def __init__(self, off_screen=None, notebook=None, shape=(1, 1),
46
groups=None, row_weights=None, col_weights=None,
47
border=True, border_color='k', border_width=2.0,
48
title=None, window_size=None, line_smoothing=False,
49
point_smoothing=False, polygon_smoothing=False,
50
splitting_position=None, lighting='light kit', theme=None,
51
image_scale=None, **kwargs):
52
"""
53
Initialize plotter with rendering options.
54
55
Parameters:
56
off_screen (bool): Render off-screen
57
notebook (bool): Enable notebook mode
58
shape (tuple): Subplot grid shape (rows, cols)
59
groups (list): Subplot groupings
60
row_weights (list): Relative row heights
61
col_weights (list): Relative column widths
62
border (bool): Show subplot borders
63
border_color (str): Border color
64
border_width (float): Border line width
65
title (str): Window title
66
window_size (tuple): Window size (width, height)
67
line_smoothing (bool): Enable line smoothing
68
point_smoothing (bool): Enable point smoothing
69
polygon_smoothing (bool): Enable polygon smoothing
70
splitting_position (float): Splitter position for subplots
71
lighting (str): Lighting setup ('light kit', 'three lights', 'none')
72
theme (str or Theme): Plotting theme
73
image_scale (int): Resolution scaling factor
74
"""
75
```
76
77
### Mesh Rendering
78
79
#### Adding Meshes to Scene
80
81
Core method for adding 3D objects to plots.
82
83
```python { .api }
84
def add_mesh(self, mesh, color=None, style=None, scalars=None, clim=None,
85
show_edges=False, edge_color=None, point_size=5.0, line_width=None,
86
opacity=1.0, flip_scalars=False, lighting=None, n_colors=256,
87
interpolate_before_map=True, cmap=None, label=None,
88
reset_camera=None, scalar_bar_args=None, show_scalar_bar=None,
89
multi_colors=False, name=None, texture=None, render_points_as_spheres=None,
90
render_lines_as_tubes=None, smooth_shading=None, ambient=0.0,
91
diffuse=1.0, specular=0.0, specular_power=1.0, nan_color=None,
92
nan_opacity=1.0, culling=None, rgb=None, categories=False,
93
silhouette=None, use_transparency=False, below_color=None,
94
above_color=None, annotations=None, pickable=True, preference='point',
95
log_scale=False, pbr=False, metallic=0.0, roughness=0.5,
96
render=True, user_matrix=None, component=None, **kwargs) -> Actor:
97
"""
98
Add a mesh to the plotting scene.
99
100
Parameters:
101
mesh (DataSet): Mesh or dataset to plot
102
color (str or tuple): Mesh color
103
style (str): Render style ('surface', 'wireframe', 'points')
104
scalars (str or array): Scalar data for coloring
105
clim (tuple): Color range (min, max)
106
show_edges (bool): Show mesh edges
107
edge_color (str): Edge color
108
point_size (float): Point size for point rendering
109
line_width (float): Line width for wireframe/edges
110
opacity (float): Mesh opacity (0.0 to 1.0)
111
flip_scalars (bool): Flip scalar color mapping
112
lighting (bool): Enable mesh lighting
113
n_colors (int): Number of colors in colormap
114
interpolate_before_map (bool): Interpolate scalars before mapping
115
cmap (str): Colormap name
116
label (str): Label for legend
117
reset_camera (bool): Reset camera to fit mesh
118
scalar_bar_args (dict): Scalar bar configuration
119
show_scalar_bar (bool): Show scalar color bar
120
multi_colors (bool): Use multi-color rendering
121
name (str): Name for mesh actor
122
texture (Texture): Texture to apply
123
render_points_as_spheres (bool): Render points as 3D spheres
124
render_lines_as_tubes (bool): Render lines as 3D tubes
125
smooth_shading (bool): Enable smooth shading
126
ambient (float): Ambient lighting coefficient
127
diffuse (float): Diffuse lighting coefficient
128
specular (float): Specular lighting coefficient
129
specular_power (float): Specular highlight sharpness
130
nan_color (str): Color for NaN values
131
nan_opacity (float): Opacity for NaN values
132
culling (str): Face culling ('front', 'back')
133
rgb (bool): Interpret scalars as RGB colors
134
categories (bool): Treat scalars as categories
135
silhouette (dict): Silhouette rendering options
136
use_transparency (bool): Enable transparency
137
below_color (str): Color for values below range
138
above_color (str): Color for values above range
139
annotations (dict): Text annotations
140
pickable (bool): Allow mesh picking
141
preference (str): Scalar association preference
142
log_scale (bool): Use logarithmic color scale
143
pbr (bool): Enable physically based rendering
144
metallic (float): PBR metallic parameter
145
roughness (float): PBR roughness parameter
146
render (bool): Render immediately
147
user_matrix (array): User transformation matrix
148
component (int): Vector component to display
149
150
Returns:
151
Actor: VTK actor object
152
"""
153
```
154
155
### Display Control
156
157
#### Scene Management
158
159
Methods for controlling plot display and interaction.
160
161
```python { .api }
162
def show(self, title=None, window_size=None, interactive=True, auto_close=True,
163
interactive_update=False, full_screen=False, screenshot=None,
164
return_img=False, cpos=None, use_panel=None, jupyter_backend=None,
165
return_viewer=False, return_cpos=False, before_close_callback=None,
166
**kwargs):
167
"""
168
Display the plotting scene.
169
170
Parameters:
171
title (str): Window title
172
window_size (tuple): Window size (width, height)
173
interactive (bool): Enable interactive mode
174
auto_close (bool): Automatically close after display
175
interactive_update (bool): Enable interactive updates
176
full_screen (bool): Display in full screen
177
screenshot (str): Save screenshot to file
178
return_img (bool): Return screenshot as array
179
cpos (tuple): Camera position
180
use_panel (bool): Use panel for display
181
jupyter_backend (str): Jupyter backend to use
182
return_viewer (bool): Return viewer object
183
return_cpos (bool): Return camera position
184
before_close_callback (callable): Callback before closing
185
186
Returns:
187
Various: Depends on return options
188
"""
189
190
def close(self):
191
"""Close the plotting window and clean up resources."""
192
193
def clear(self, render=True):
194
"""
195
Clear all actors from the scene.
196
197
Parameters:
198
render (bool): Re-render after clearing
199
"""
200
201
def reset_camera(self, render=True):
202
"""
203
Reset camera to fit all actors in scene.
204
205
Parameters:
206
render (bool): Re-render after reset
207
"""
208
```
209
210
#### Screenshots and Export
211
212
Save plot images and export scenes.
213
214
```python { .api }
215
def screenshot(self, filename=None, transparent_background=None,
216
return_img=False, window_size=None, scale=None):
217
"""
218
Take a screenshot of the current plot.
219
220
Parameters:
221
filename (str): Output filename
222
transparent_background (bool): Make background transparent
223
return_img (bool): Return image as numpy array
224
window_size (tuple): Override window size
225
scale (int): Resolution scaling factor
226
227
Returns:
228
None or np.ndarray: Image array if return_img=True
229
"""
230
231
def save_graphic(self, filename, title='PyVista Export', raster=True,
232
painter=True):
233
"""
234
Save plot as vector graphics.
235
236
Parameters:
237
filename (str): Output filename (.svg, .eps, .ps, .pdf, .tex)
238
title (str): Document title
239
raster (bool): Enable raster graphics
240
painter (bool): Enable painter mode
241
"""
242
```
243
244
### Camera and Viewing
245
246
#### Camera Control
247
248
Manage camera position and orientation.
249
250
```python { .api }
251
class Camera:
252
"""
253
Camera object for controlling viewpoint.
254
255
Attributes:
256
position: tuple - Camera position (x, y, z)
257
focal_point: tuple - Point camera looks at
258
up: tuple - Camera up vector
259
roll: float - Camera roll angle
260
elevation: float - Camera elevation angle
261
azimuth: float - Camera azimuth angle
262
distance: float - Distance to focal point
263
parallel_projection: bool - Use parallel projection
264
parallel_scale: float - Parallel projection scale
265
"""
266
267
def view_isometric(self, negative=False):
268
"""Set isometric view."""
269
270
def view_vector(self, vector, viewup=None):
271
"""
272
Set camera to look along vector direction.
273
274
Parameters:
275
vector (tuple): View direction vector
276
viewup (tuple): Up direction vector
277
"""
278
279
def zoom(self, value):
280
"""
281
Zoom camera by factor.
282
283
Parameters:
284
value (float): Zoom factor
285
"""
286
287
def set_position(self, position, reset=False):
288
"""
289
Set camera position.
290
291
Parameters:
292
position (tuple): Camera position (x, y, z)
293
reset (bool): Reset camera after positioning
294
"""
295
296
def set_focus(self, point):
297
"""
298
Set camera focal point.
299
300
Parameters:
301
point (tuple): Focal point coordinates
302
"""
303
304
def set_viewup(self, vector):
305
"""
306
Set camera up vector.
307
308
Parameters:
309
vector (tuple): Up direction vector
310
"""
311
```
312
313
### Lighting
314
315
#### Light Sources
316
317
Control scene lighting.
318
319
```python { .api }
320
class Light:
321
"""
322
Light source for illuminating scenes.
323
324
Attributes:
325
position: tuple - Light position
326
focal_point: tuple - Light focal point
327
color: tuple - Light color (R, G, B)
328
intensity: float - Light intensity
329
on: bool - Light on/off state
330
"""
331
332
def __init__(self, position=(0, 0, 1), focal_point=(0, 0, 0),
333
color=(1.0, 1.0, 1.0), light_type='camera', intensity=1.0,
334
cone_angle=30.0, exponent=1.0, positional=False,
335
show_actor=False, attenuation_values=(1.0, 0.0, 0.0)):
336
"""
337
Create light source.
338
339
Parameters:
340
position (tuple): Light position
341
focal_point (tuple): Light focal point
342
color (tuple): Light color
343
light_type (str): Light type ('camera', 'scene', 'headlight')
344
intensity (float): Light intensity
345
cone_angle (float): Cone angle for spotlights
346
exponent (float): Light attenuation exponent
347
positional (bool): Positional light
348
show_actor (bool): Show light actor
349
attenuation_values (tuple): Attenuation coefficients
350
"""
351
352
def add_light(self, light, only_active=False, render=True):
353
"""
354
Add light to scene.
355
356
Parameters:
357
light (Light): Light object to add
358
only_active (bool): Add only to active renderer
359
render (bool): Re-render after adding
360
"""
361
362
def remove_all_lights(self, render=True):
363
"""
364
Remove all lights from scene.
365
366
Parameters:
367
render (bool): Re-render after removal
368
"""
369
```
370
371
### Annotations and Text
372
373
#### Text and Labels
374
375
Add text annotations to plots.
376
377
```python { .api }
378
def add_text(self, text, position='upper_left', font_size=18, color=None,
379
font=None, shadow=False, name=None, viewport=False,
380
render=True) -> Actor:
381
"""
382
Add text annotation to plot.
383
384
Parameters:
385
text (str): Text string to display
386
position (str or tuple): Text position
387
font_size (int): Font size
388
color (str): Text color
389
font (str): Font family
390
shadow (bool): Add text shadow
391
name (str): Name for text actor
392
viewport (bool): Use viewport coordinates
393
render (bool): Re-render after adding
394
395
Returns:
396
Actor: Text actor object
397
"""
398
399
def add_point_labels(self, points, labels, point_color=None, point_size=None,
400
font_size=None, text_color=None, font_family=None,
401
shadow=False, show_points=True, always_visible=False,
402
name=None, render=True) -> tuple:
403
"""
404
Add labels at point locations.
405
406
Parameters:
407
points (array-like): Point coordinates
408
labels (list): Text labels for points
409
point_color (str): Point marker color
410
point_size (float): Point marker size
411
font_size (int): Label font size
412
text_color (str): Label text color
413
font_family (str): Font family
414
shadow (bool): Add text shadow
415
show_points (bool): Show point markers
416
always_visible (bool): Labels always visible
417
name (str): Name for label actors
418
render (bool): Re-render after adding
419
420
Returns:
421
tuple: Point and label actors
422
"""
423
424
def add_title(self, title, font_size=None, color=None, font=None,
425
shadow=False, render=True) -> Actor:
426
"""
427
Add title to plot.
428
429
Parameters:
430
title (str): Title text
431
font_size (int): Title font size
432
color (str): Title color
433
font (str): Font family
434
shadow (bool): Add shadow
435
render (bool): Re-render after adding
436
437
Returns:
438
Actor: Title actor
439
"""
440
```
441
442
#### Scalar Bars and Legends
443
444
Add color bars and legends.
445
446
```python { .api }
447
def add_scalar_bar(self, title=None, mapper=None, n_labels=5, italic=False,
448
bold=False, title_font_size=None, label_font_size=None,
449
color=None, font_family=None, shadow=False, width=None,
450
height=None, position_x=None, position_y=None,
451
vertical=True, interactive=None, fmt=None, use_opacity=True,
452
outline=False, nan_annotation=False, below_label=None,
453
above_label=None, background_color=None, n_colors=None,
454
categories=False, render=True) -> Actor:
455
"""
456
Add scalar color bar to plot.
457
458
Parameters:
459
title (str): Color bar title
460
mapper (object): Data mapper for color mapping
461
n_labels (int): Number of labels
462
italic (bool): Italic text
463
bold (bool): Bold text
464
title_font_size (int): Title font size
465
label_font_size (int): Label font size
466
color (str): Text color
467
font_family (str): Font family
468
shadow (bool): Add text shadow
469
width (float): Color bar width
470
height (float): Color bar height
471
position_x (float): X position
472
position_y (float): Y position
473
vertical (bool): Vertical orientation
474
interactive (bool): Interactive color bar
475
fmt (str): Number format string
476
use_opacity (bool): Show opacity
477
outline (bool): Draw outline
478
nan_annotation (bool): Show NaN annotation
479
below_label (str): Below-range label
480
above_label (str): Above-range label
481
background_color (str): Background color
482
n_colors (int): Number of color levels
483
categories (bool): Categorical colors
484
render (bool): Re-render after adding
485
486
Returns:
487
Actor: Scalar bar actor
488
"""
489
```
490
491
### Interactive Widgets
492
493
#### 3D Widgets
494
495
Add interactive 3D widgets for manipulation.
496
497
```python { .api }
498
def add_mesh_clip_plane(self, mesh, normal='x', invert=False, widget_color=None,
499
value=0.0, assign_to_axis=None, tubing=False,
500
origin_translation=True, outline_translation=False,
501
implicit=True, normal_rotation=True, crinkle=False,
502
interaction_event='end', name=None, **kwargs) -> tuple:
503
"""
504
Add interactive clipping plane widget.
505
506
Parameters:
507
mesh (DataSet): Mesh to clip
508
normal (str or tuple): Clipping plane normal
509
invert (bool): Invert clipping
510
widget_color (str): Widget color
511
value (float): Initial clipping value
512
assign_to_axis (str): Constrain to axis
513
tubing (bool): Show plane as tube
514
origin_translation (bool): Allow origin translation
515
outline_translation (bool): Allow outline translation
516
implicit (bool): Use implicit plane
517
normal_rotation (bool): Allow normal rotation
518
crinkle (bool): Show crinkled clipping
519
interaction_event (str): Widget interaction event
520
name (str): Actor name
521
522
Returns:
523
tuple: Clipped mesh and widget actors
524
"""
525
526
def add_mesh_slice_orthogonal(self, mesh, generate_triangles=False, widget_color=None,
527
tubing=False, interaction_event='end', **kwargs) -> tuple:
528
"""
529
Add orthogonal slicing widget.
530
531
Parameters:
532
mesh (DataSet): Mesh to slice
533
generate_triangles (bool): Triangulate slices
534
widget_color (str): Widget color
535
tubing (bool): Show planes as tubes
536
interaction_event (str): Widget interaction event
537
538
Returns:
539
tuple: Sliced meshes and widget actors
540
"""
541
```
542
543
### Subplots and Multi-Panel Layouts
544
545
#### Subplot Management
546
547
Create complex multi-panel visualizations.
548
549
```python { .api }
550
def subplot(self, index_row, index_column=None):
551
"""
552
Set active subplot for rendering.
553
554
Parameters:
555
index_row (int): Row index or linear index
556
index_column (int): Column index
557
"""
558
559
def add_mesh_subplot(self, mesh, subplot_index, **kwargs):
560
"""
561
Add mesh to specific subplot.
562
563
Parameters:
564
mesh (DataSet): Mesh to add
565
subplot_index (tuple): Subplot indices (row, col)
566
**kwargs: Mesh rendering options
567
"""
568
569
def link_views(self, views=None):
570
"""
571
Link camera views between subplots.
572
573
Parameters:
574
views (list): List of subplot indices to link
575
"""
576
577
def unlink_views(self, views=None):
578
"""
579
Unlink camera views between subplots.
580
581
Parameters:
582
views (list): List of subplot indices to unlink
583
"""
584
```
585
586
## Usage Examples
587
588
### Basic plotting
589
590
```python
591
import pyvista as pv
592
import numpy as np
593
594
# Create sample data
595
mesh = pv.Sphere()
596
mesh['elevation'] = mesh.points[:, 2]
597
598
# Simple plot
599
mesh.plot(scalars='elevation', cmap='viridis')
600
601
# Using Plotter for more control
602
plotter = pv.Plotter()
603
plotter.add_mesh(mesh, scalars='elevation', cmap='coolwarm',
604
show_edges=True, show_scalar_bar=True)
605
plotter.add_title("Sphere with Elevation Data")
606
plotter.show()
607
```
608
609
### Multi-panel visualization
610
611
```python
612
import pyvista as pv
613
614
# Load data
615
mesh = pv.examples.load_airplane()
616
617
# Create 2x2 subplot layout
618
plotter = pv.Plotter(shape=(2, 2))
619
620
# Different views in each subplot
621
plotter.subplot(0, 0)
622
plotter.add_mesh(mesh, color='red')
623
plotter.add_title("Red Airplane")
624
625
plotter.subplot(0, 1)
626
plotter.add_mesh(mesh, style='wireframe')
627
plotter.add_title("Wireframe")
628
629
plotter.subplot(1, 0)
630
plotter.add_mesh(mesh, style='points', point_size=10)
631
plotter.add_title("Points")
632
633
plotter.subplot(1, 1)
634
plotter.add_mesh(mesh.outline(), color='black', line_width=5)
635
plotter.add_mesh(mesh, opacity=0.5)
636
plotter.add_title("With Outline")
637
638
plotter.show()
639
```
640
641
### Interactive visualization with widgets
642
643
```python
644
import pyvista as pv
645
646
# Load volume data
647
grid = pv.examples.download_brain()
648
649
# Create interactive plot with clipping
650
plotter = pv.Plotter()
651
652
# Add volume with clipping widget
653
plotter.add_mesh_clip_plane(grid, normal='x', widget_color='red')
654
655
# Add orthogonal slicing widget
656
plotter.add_mesh_slice_orthogonal(grid, widget_color='blue')
657
658
plotter.show()
659
```