0
# PyVista
1
2
PyVista is a comprehensive Python library providing a high-level, Pythonic interface to the Visualization Toolkit (VTK) for 3D scientific data visualization and mesh analysis. It wraps VTK's powerful visualization backend through NumPy integration and direct array access, facilitating rapid prototyping, analysis, and visual integration of spatially referenced datasets.
3
4
## Package Information
5
6
- **Package Name**: pyvista
7
- **Language**: Python
8
- **Installation**: `pip install pyvista`
9
- **Optional Dependencies**:
10
- `pip install pyvista[all]` (includes colormaps, I/O, and Jupyter support)
11
- `pip install pyvista[jupyter]` (for Jupyter notebook integration)
12
13
## Core Imports
14
15
```python
16
import pyvista as pv
17
```
18
19
For accessing submodules:
20
21
```python
22
import pyvista as pv
23
24
# Examples and datasets
25
pv.examples # Built-in and downloadable examples
26
pv.demos # Interactive demonstrations
27
28
# Utilities and extensions
29
pv.utilities # Utility functions
30
pv.ext # Extensions
31
pv.trame # Trame integration for web-based visualization
32
33
# Plotting functions available directly
34
pv.plot() # Simple plotting function
35
pv.Plotter() # Advanced plotting interface
36
```
37
38
## Basic Usage
39
40
```python
41
import pyvista as pv
42
import numpy as np
43
44
# Create a simple mesh
45
mesh = pv.Sphere(radius=1.0, theta_resolution=30, phi_resolution=30)
46
47
# Add some data to the mesh
48
mesh['elevation'] = mesh.points[:, 2] # Z-coordinate as scalar data
49
50
# Create a basic plot
51
plotter = pv.Plotter()
52
plotter.add_mesh(mesh, scalars='elevation', cmap='viridis')
53
plotter.show()
54
55
# Or use the simple plot function
56
mesh.plot(scalars='elevation', cmap='viridis')
57
58
# Read a file and plot
59
mesh = pv.read('path/to/file.vtk')
60
mesh.plot()
61
62
# Create and visualize volumetric data
63
grid = pv.ImageData(dimensions=(10, 10, 10))
64
grid['values'] = np.random.random(grid.n_points)
65
grid.plot(volume=True)
66
```
67
68
## Architecture
69
70
PyVista's architecture is built around VTK's data model with Pythonic enhancements:
71
72
- **DataSet Classes**: Core data structures (`PolyData`, `UnstructuredGrid`, `ImageData`, etc.) that wrap VTK objects
73
- **Filter Mixins**: Methods added to dataset classes for processing (clipping, smoothing, etc.)
74
- **Plotting System**: High-level plotting interface with `Plotter` class managing scenes, actors, and rendering
75
- **Array Management**: Seamless NumPy integration for point/cell data manipulation
76
- **File I/O**: Universal file reading/writing supporting 20+ formats
77
- **Geometric Primitives**: Built-in creation of spheres, cubes, and other basic shapes
78
79
## Capabilities
80
81
### Data Structures and Mesh Types
82
83
Core dataset classes for representing different types of 3D data including polygonal surfaces, volumetric grids, point clouds, and composite datasets.
84
85
```python { .api }
86
class PolyData:
87
"""Polygonal data (surfaces, lines, vertices)."""
88
89
class UnstructuredGrid:
90
"""Unstructured mesh with arbitrary cell types."""
91
92
class StructuredGrid:
93
"""Structured curvilinear grid."""
94
95
class ImageData:
96
"""Uniform rectilinear grid (voxel data)."""
97
98
class MultiBlock:
99
"""Multi-block dataset container."""
100
```
101
102
[Data Structures](./data-structures.md)
103
104
### Mesh Generation and Geometric Primitives
105
106
Built-in functions for creating basic geometric shapes, parametric surfaces, and complex 3D objects with customizable parameters.
107
108
```python { .api }
109
def Sphere(radius=0.5, center=(0.0, 0.0, 0.0), direction=(0.0, 0.0, 1.0),
110
theta_resolution=30, phi_resolution=30, start_theta=0.0, end_theta=360.0,
111
start_phi=0.0, end_phi=180.0) -> PolyData: ...
112
def Cube(x_length=1.0, y_length=1.0, z_length=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
113
def Cylinder(center=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), radius=0.5,
114
height=1.0, resolution=100, capping=True) -> PolyData: ...
115
def Cone(center=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), height=1.0,
116
radius=0.5, resolution=6, capping=True) -> PolyData: ...
117
def Plane(center=(0.0, 0.0, 0.0), direction=(0.0, 0.0, 1.0), i_size=1, j_size=1,
118
i_resolution=10, j_resolution=10) -> PolyData: ...
119
def Arrow(start=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), tip_length=0.25,
120
tip_radius=0.1, shaft_radius=0.05) -> PolyData: ...
121
def Line(pointa=(-0.5, 0.0, 0.0), pointb=(0.5, 0.0, 0.0), resolution=1) -> PolyData: ...
122
def Circle(radius=0.5, resolution=100) -> PolyData: ...
123
def Disc(center=(0.0, 0.0, 0.0), inner=0.25, outer=0.5) -> PolyData: ...
124
def Text3D(string, depth=0.5) -> PolyData: ...
125
# Platonic solids
126
def Tetrahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
127
def Octahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
128
def Dodecahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
129
def Icosahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
130
def Icosphere(radius=1.0, center=(0.0, 0.0, 0.0), nsub=1) -> PolyData: ...
131
# Parametric surfaces
132
def ParametricTorus(ringradius=1.0, crosssectionradius=0.2) -> PolyData: ...
133
def ParametricEllipsoid(xradius=1.0, yradius=1.0, zradius=1.0) -> PolyData: ...
134
def ParametricKlein() -> PolyData: ...
135
def Spline(points, n_points=None) -> PolyData: ...
136
def KochanekSpline(points, tension=0.0, bias=0.0, continuity=0.0) -> PolyData: ...
137
```
138
139
[Geometric Primitives](./geometric-primitives.md)
140
141
### Data Processing and Filtering
142
143
Comprehensive mesh processing capabilities including clipping, slicing, smoothing, decimation, boolean operations, and geometric transformations.
144
145
```python { .api }
146
# Dataset methods for processing
147
def clip(self, normal='x', origin=None, invert=False, **kwargs): ...
148
def slice(self, normal='x', origin=None, generate_triangles=False, **kwargs): ...
149
def smooth(self, n_iter=20, relaxation_factor=0.01, **kwargs): ...
150
def decimate(self, target_reduction=0.5, **kwargs): ...
151
def contour(self, isosurfaces=10, **kwargs): ...
152
def threshold(self, value=None, **kwargs): ...
153
# Coordinate transformations
154
def cartesian_to_spherical(x, y, z): ...
155
def spherical_to_cartesian(r, theta, phi): ...
156
def transform_vectors_sph_to_cart(theta, phi, r, u, v, w): ...
157
# Grid and mesh operations
158
def merge(datasets, merge_points=True, **kwargs): ...
159
def sample_function(function, bounds=(-1, 1, -1, 1, -1, 1), dims=(50, 50, 50)): ...
160
def voxelize_volume(mesh, density, **kwargs): ...
161
```
162
163
[Data Processing](./data-processing.md)
164
165
### Plotting and Visualization
166
167
Advanced 3D plotting system with support for multiple datasets, custom colormaps, lighting, cameras, annotations, and interactive widgets.
168
169
```python { .api }
170
class Plotter:
171
"""Main plotting interface for 3D visualization."""
172
def add_mesh(self, mesh, **kwargs): ...
173
def show(self, **kwargs): ...
174
175
def plot(*args, **kwargs): ...
176
```
177
178
[Plotting and Visualization](./plotting.md)
179
180
### File Input/Output
181
182
Universal file reading and writing supporting VTK formats, STL, PLY, OBJ, Exodus, and integration with external libraries like MeshIO.
183
184
```python { .api }
185
def read(filename, force_ext=None, file_format=None, progress_bar=False, **kwargs): ...
186
def read_texture(filename, progress_bar=False): ...
187
def read_exodus(filename, **kwargs): ...
188
def read_meshio(filename, file_format=None, **kwargs): ...
189
def read_pickle(filename): ...
190
def save_meshio(mesh, filename, file_format=None, **kwargs): ...
191
def save_pickle(mesh, filename): ...
192
def set_pickle_format(file_format): ...
193
def set_vtkwriter_mode(mode): ...
194
```
195
196
[File I/O](./file-io.md)
197
198
### Example Datasets
199
200
Extensive collection of built-in and downloadable example datasets for testing, learning, and demonstration purposes.
201
202
```python { .api }
203
# Built-in examples (no download required)
204
def load_ant() -> PolyData: ...
205
def load_airplane() -> PolyData: ...
206
def load_sphere() -> PolyData: ...
207
def load_uniform() -> ImageData: ...
208
def load_rectilinear() -> RectilinearGrid: ...
209
def load_structured() -> StructuredGrid: ...
210
def load_hexbeam() -> UnstructuredGrid: ...
211
def load_globe() -> PolyData: ...
212
def load_hydrogen_orbital(n=1, l=0, m=0) -> ImageData: ...
213
# Downloadable examples
214
def download_bunny() -> PolyData: ...
215
def download_dragon() -> PolyData: ...
216
def download_brain() -> ImageData: ...
217
def download_head() -> ImageData: ...
218
def download_cow() -> PolyData: ...
219
def download_teapot() -> PolyData: ...
220
def download_gears() -> PolyData: ...
221
def download_motor() -> MultiBlock: ...
222
def download_hurricane() -> StructuredGrid: ...
223
def download_kitchen() -> StructuredGrid: ...
224
# Utility functions
225
def delete_downloads(): ...
226
def get_downloads_cache_dir() -> str: ...
227
def set_downloads_cache_dir(path): ...
228
def list_examples() -> dict: ...
229
def load_random() -> 'DataSet': ...
230
```
231
232
[Example Datasets](./examples.md)
233
234
## Global Configuration
235
236
```python { .api }
237
# Global constants and configuration
238
OFF_SCREEN: bool # Off-screen rendering mode
239
BUILDING_GALLERY: bool # Gallery building mode
240
DEFAULT_SCALARS_NAME: str # Default name for scalar arrays
241
MAX_N_COLOR_BARS: int # Maximum number of color bars
242
243
# Version information
244
__version__: str # PyVista version
245
vtk_version_info: object # VTK version information
246
247
# System reporting
248
class Report:
249
"""System and environment report."""
250
251
def get_gpu_info() -> dict: ...
252
```
253
254
## Type Definitions
255
256
```python { .api }
257
from typing import Union, Optional, Tuple, List, Dict, Any, Sequence, Literal
258
import numpy as np
259
260
# Common type aliases used throughout PyVista
261
ArrayLike = Union[np.ndarray, List, Tuple]
262
ColorLike = Union[str, Tuple[float, float, float], Tuple[int, int, int]]
263
BoundsLike = Tuple[float, float, float, float, float, float]
264
VectorLike = Union[List[float], Tuple[float, ...], np.ndarray]
265
MatrixLike = Union[List[List[float]], np.ndarray]
266
267
# Dataset type unions
268
DataSetType = Union['PolyData', 'UnstructuredGrid', 'StructuredGrid', 'ImageData', 'RectilinearGrid']
269
DataObjectType = Union[DataSetType, 'MultiBlock', 'PartitionedDataSet', 'Table']
270
GridType = Union['StructuredGrid', 'ImageData', 'RectilinearGrid']
271
PointSetType = Union['PolyData', 'UnstructuredGrid', 'StructuredGrid']
272
PointGridType = Union['PolyData', 'UnstructuredGrid', 'StructuredGrid', 'PointGrid']
273
274
# VTK specific types
275
ID_TYPE = Union[np.int32, np.int64]
276
277
# Configuration types
278
PICKLE_FORMAT = Literal['vtk', 'xml', 'legacy']
279
VTK_SNAKE_CASE_STATE = Literal['allow', 'warning', 'error']
280
281
# Plotting types
282
CameraPosition = Union[List[float], Tuple[float, ...]]
283
```