Easier Pythonic interface to VTK for 3D scientific data visualization and mesh analysis
npx @tessl/cli install tessl/pypi-pyvista@0.46.0PyVista 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.
pip install pyvistapip install pyvista[all] (includes colormaps, I/O, and Jupyter support)pip install pyvista[jupyter] (for Jupyter notebook integration)import pyvista as pvFor accessing submodules:
import pyvista as pv
# Examples and datasets
pv.examples # Built-in and downloadable examples
pv.demos # Interactive demonstrations
# Utilities and extensions
pv.utilities # Utility functions
pv.ext # Extensions
pv.trame # Trame integration for web-based visualization
# Plotting functions available directly
pv.plot() # Simple plotting function
pv.Plotter() # Advanced plotting interfaceimport pyvista as pv
import numpy as np
# Create a simple mesh
mesh = pv.Sphere(radius=1.0, theta_resolution=30, phi_resolution=30)
# Add some data to the mesh
mesh['elevation'] = mesh.points[:, 2] # Z-coordinate as scalar data
# Create a basic plot
plotter = pv.Plotter()
plotter.add_mesh(mesh, scalars='elevation', cmap='viridis')
plotter.show()
# Or use the simple plot function
mesh.plot(scalars='elevation', cmap='viridis')
# Read a file and plot
mesh = pv.read('path/to/file.vtk')
mesh.plot()
# Create and visualize volumetric data
grid = pv.ImageData(dimensions=(10, 10, 10))
grid['values'] = np.random.random(grid.n_points)
grid.plot(volume=True)PyVista's architecture is built around VTK's data model with Pythonic enhancements:
PolyData, UnstructuredGrid, ImageData, etc.) that wrap VTK objectsPlotter class managing scenes, actors, and renderingCore dataset classes for representing different types of 3D data including polygonal surfaces, volumetric grids, point clouds, and composite datasets.
class PolyData:
"""Polygonal data (surfaces, lines, vertices)."""
class UnstructuredGrid:
"""Unstructured mesh with arbitrary cell types."""
class StructuredGrid:
"""Structured curvilinear grid."""
class ImageData:
"""Uniform rectilinear grid (voxel data)."""
class MultiBlock:
"""Multi-block dataset container."""Built-in functions for creating basic geometric shapes, parametric surfaces, and complex 3D objects with customizable parameters.
def Sphere(radius=0.5, center=(0.0, 0.0, 0.0), direction=(0.0, 0.0, 1.0),
theta_resolution=30, phi_resolution=30, start_theta=0.0, end_theta=360.0,
start_phi=0.0, end_phi=180.0) -> PolyData: ...
def Cube(x_length=1.0, y_length=1.0, z_length=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
def Cylinder(center=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), radius=0.5,
height=1.0, resolution=100, capping=True) -> PolyData: ...
def Cone(center=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), height=1.0,
radius=0.5, resolution=6, capping=True) -> PolyData: ...
def Plane(center=(0.0, 0.0, 0.0), direction=(0.0, 0.0, 1.0), i_size=1, j_size=1,
i_resolution=10, j_resolution=10) -> PolyData: ...
def Arrow(start=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0), tip_length=0.25,
tip_radius=0.1, shaft_radius=0.05) -> PolyData: ...
def Line(pointa=(-0.5, 0.0, 0.0), pointb=(0.5, 0.0, 0.0), resolution=1) -> PolyData: ...
def Circle(radius=0.5, resolution=100) -> PolyData: ...
def Disc(center=(0.0, 0.0, 0.0), inner=0.25, outer=0.5) -> PolyData: ...
def Text3D(string, depth=0.5) -> PolyData: ...
# Platonic solids
def Tetrahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
def Octahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
def Dodecahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
def Icosahedron(radius=1.0, center=(0.0, 0.0, 0.0)) -> PolyData: ...
def Icosphere(radius=1.0, center=(0.0, 0.0, 0.0), nsub=1) -> PolyData: ...
# Parametric surfaces
def ParametricTorus(ringradius=1.0, crosssectionradius=0.2) -> PolyData: ...
def ParametricEllipsoid(xradius=1.0, yradius=1.0, zradius=1.0) -> PolyData: ...
def ParametricKlein() -> PolyData: ...
def Spline(points, n_points=None) -> PolyData: ...
def KochanekSpline(points, tension=0.0, bias=0.0, continuity=0.0) -> PolyData: ...Comprehensive mesh processing capabilities including clipping, slicing, smoothing, decimation, boolean operations, and geometric transformations.
# Dataset methods for processing
def clip(self, normal='x', origin=None, invert=False, **kwargs): ...
def slice(self, normal='x', origin=None, generate_triangles=False, **kwargs): ...
def smooth(self, n_iter=20, relaxation_factor=0.01, **kwargs): ...
def decimate(self, target_reduction=0.5, **kwargs): ...
def contour(self, isosurfaces=10, **kwargs): ...
def threshold(self, value=None, **kwargs): ...
# Coordinate transformations
def cartesian_to_spherical(x, y, z): ...
def spherical_to_cartesian(r, theta, phi): ...
def transform_vectors_sph_to_cart(theta, phi, r, u, v, w): ...
# Grid and mesh operations
def merge(datasets, merge_points=True, **kwargs): ...
def sample_function(function, bounds=(-1, 1, -1, 1, -1, 1), dims=(50, 50, 50)): ...
def voxelize_volume(mesh, density, **kwargs): ...Advanced 3D plotting system with support for multiple datasets, custom colormaps, lighting, cameras, annotations, and interactive widgets.
class Plotter:
"""Main plotting interface for 3D visualization."""
def add_mesh(self, mesh, **kwargs): ...
def show(self, **kwargs): ...
def plot(*args, **kwargs): ...Universal file reading and writing supporting VTK formats, STL, PLY, OBJ, Exodus, and integration with external libraries like MeshIO.
def read(filename, force_ext=None, file_format=None, progress_bar=False, **kwargs): ...
def read_texture(filename, progress_bar=False): ...
def read_exodus(filename, **kwargs): ...
def read_meshio(filename, file_format=None, **kwargs): ...
def read_pickle(filename): ...
def save_meshio(mesh, filename, file_format=None, **kwargs): ...
def save_pickle(mesh, filename): ...
def set_pickle_format(file_format): ...
def set_vtkwriter_mode(mode): ...Extensive collection of built-in and downloadable example datasets for testing, learning, and demonstration purposes.
# Built-in examples (no download required)
def load_ant() -> PolyData: ...
def load_airplane() -> PolyData: ...
def load_sphere() -> PolyData: ...
def load_uniform() -> ImageData: ...
def load_rectilinear() -> RectilinearGrid: ...
def load_structured() -> StructuredGrid: ...
def load_hexbeam() -> UnstructuredGrid: ...
def load_globe() -> PolyData: ...
def load_hydrogen_orbital(n=1, l=0, m=0) -> ImageData: ...
# Downloadable examples
def download_bunny() -> PolyData: ...
def download_dragon() -> PolyData: ...
def download_brain() -> ImageData: ...
def download_head() -> ImageData: ...
def download_cow() -> PolyData: ...
def download_teapot() -> PolyData: ...
def download_gears() -> PolyData: ...
def download_motor() -> MultiBlock: ...
def download_hurricane() -> StructuredGrid: ...
def download_kitchen() -> StructuredGrid: ...
# Utility functions
def delete_downloads(): ...
def get_downloads_cache_dir() -> str: ...
def set_downloads_cache_dir(path): ...
def list_examples() -> dict: ...
def load_random() -> 'DataSet': ...# Global constants and configuration
OFF_SCREEN: bool # Off-screen rendering mode
BUILDING_GALLERY: bool # Gallery building mode
DEFAULT_SCALARS_NAME: str # Default name for scalar arrays
MAX_N_COLOR_BARS: int # Maximum number of color bars
# Version information
__version__: str # PyVista version
vtk_version_info: object # VTK version information
# System reporting
class Report:
"""System and environment report."""
def get_gpu_info() -> dict: ...from typing import Union, Optional, Tuple, List, Dict, Any, Sequence, Literal
import numpy as np
# Common type aliases used throughout PyVista
ArrayLike = Union[np.ndarray, List, Tuple]
ColorLike = Union[str, Tuple[float, float, float], Tuple[int, int, int]]
BoundsLike = Tuple[float, float, float, float, float, float]
VectorLike = Union[List[float], Tuple[float, ...], np.ndarray]
MatrixLike = Union[List[List[float]], np.ndarray]
# Dataset type unions
DataSetType = Union['PolyData', 'UnstructuredGrid', 'StructuredGrid', 'ImageData', 'RectilinearGrid']
DataObjectType = Union[DataSetType, 'MultiBlock', 'PartitionedDataSet', 'Table']
GridType = Union['StructuredGrid', 'ImageData', 'RectilinearGrid']
PointSetType = Union['PolyData', 'UnstructuredGrid', 'StructuredGrid']
PointGridType = Union['PolyData', 'UnstructuredGrid', 'StructuredGrid', 'PointGrid']
# VTK specific types
ID_TYPE = Union[np.int32, np.int64]
# Configuration types
PICKLE_FORMAT = Literal['vtk', 'xml', 'legacy']
VTK_SNAKE_CASE_STATE = Literal['allow', 'warning', 'error']
# Plotting types
CameraPosition = Union[List[float], Tuple[float, ...]]