Easier Pythonic interface to VTK for 3D scientific data visualization and mesh analysis
—
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.
Simple plotting functions for quick visualization.
def plot(*args, show=True, return_plotter=False, **kwargs):
"""
Plot datasets with automatic type detection.
Parameters:
*args: Datasets, numpy arrays, or other plottable objects
show (bool): Display the plot immediately
return_plotter (bool): Return the plotter object
**kwargs: Additional plotting parameters
Returns:
None or Plotter: Plotter object if return_plotter=True
"""Main plotting interface providing full control over 3D scenes.
class Plotter:
"""
Main plotting class for creating 3D visualizations.
Attributes:
camera: Camera - Scene camera object
renderer: Renderer - VTK renderer
render_window: object - VTK render window
mesh: object - Currently active mesh
mapper: object - Currently active mapper
"""
def __init__(self, off_screen=None, notebook=None, shape=(1, 1),
groups=None, row_weights=None, col_weights=None,
border=True, border_color='k', border_width=2.0,
title=None, window_size=None, line_smoothing=False,
point_smoothing=False, polygon_smoothing=False,
splitting_position=None, lighting='light kit', theme=None,
image_scale=None, **kwargs):
"""
Initialize plotter with rendering options.
Parameters:
off_screen (bool): Render off-screen
notebook (bool): Enable notebook mode
shape (tuple): Subplot grid shape (rows, cols)
groups (list): Subplot groupings
row_weights (list): Relative row heights
col_weights (list): Relative column widths
border (bool): Show subplot borders
border_color (str): Border color
border_width (float): Border line width
title (str): Window title
window_size (tuple): Window size (width, height)
line_smoothing (bool): Enable line smoothing
point_smoothing (bool): Enable point smoothing
polygon_smoothing (bool): Enable polygon smoothing
splitting_position (float): Splitter position for subplots
lighting (str): Lighting setup ('light kit', 'three lights', 'none')
theme (str or Theme): Plotting theme
image_scale (int): Resolution scaling factor
"""Core method for adding 3D objects to plots.
def add_mesh(self, mesh, color=None, style=None, scalars=None, clim=None,
show_edges=False, edge_color=None, point_size=5.0, line_width=None,
opacity=1.0, flip_scalars=False, lighting=None, n_colors=256,
interpolate_before_map=True, cmap=None, label=None,
reset_camera=None, scalar_bar_args=None, show_scalar_bar=None,
multi_colors=False, name=None, texture=None, render_points_as_spheres=None,
render_lines_as_tubes=None, smooth_shading=None, ambient=0.0,
diffuse=1.0, specular=0.0, specular_power=1.0, nan_color=None,
nan_opacity=1.0, culling=None, rgb=None, categories=False,
silhouette=None, use_transparency=False, below_color=None,
above_color=None, annotations=None, pickable=True, preference='point',
log_scale=False, pbr=False, metallic=0.0, roughness=0.5,
render=True, user_matrix=None, component=None, **kwargs) -> Actor:
"""
Add a mesh to the plotting scene.
Parameters:
mesh (DataSet): Mesh or dataset to plot
color (str or tuple): Mesh color
style (str): Render style ('surface', 'wireframe', 'points')
scalars (str or array): Scalar data for coloring
clim (tuple): Color range (min, max)
show_edges (bool): Show mesh edges
edge_color (str): Edge color
point_size (float): Point size for point rendering
line_width (float): Line width for wireframe/edges
opacity (float): Mesh opacity (0.0 to 1.0)
flip_scalars (bool): Flip scalar color mapping
lighting (bool): Enable mesh lighting
n_colors (int): Number of colors in colormap
interpolate_before_map (bool): Interpolate scalars before mapping
cmap (str): Colormap name
label (str): Label for legend
reset_camera (bool): Reset camera to fit mesh
scalar_bar_args (dict): Scalar bar configuration
show_scalar_bar (bool): Show scalar color bar
multi_colors (bool): Use multi-color rendering
name (str): Name for mesh actor
texture (Texture): Texture to apply
render_points_as_spheres (bool): Render points as 3D spheres
render_lines_as_tubes (bool): Render lines as 3D tubes
smooth_shading (bool): Enable smooth shading
ambient (float): Ambient lighting coefficient
diffuse (float): Diffuse lighting coefficient
specular (float): Specular lighting coefficient
specular_power (float): Specular highlight sharpness
nan_color (str): Color for NaN values
nan_opacity (float): Opacity for NaN values
culling (str): Face culling ('front', 'back')
rgb (bool): Interpret scalars as RGB colors
categories (bool): Treat scalars as categories
silhouette (dict): Silhouette rendering options
use_transparency (bool): Enable transparency
below_color (str): Color for values below range
above_color (str): Color for values above range
annotations (dict): Text annotations
pickable (bool): Allow mesh picking
preference (str): Scalar association preference
log_scale (bool): Use logarithmic color scale
pbr (bool): Enable physically based rendering
metallic (float): PBR metallic parameter
roughness (float): PBR roughness parameter
render (bool): Render immediately
user_matrix (array): User transformation matrix
component (int): Vector component to display
Returns:
Actor: VTK actor object
"""Methods for controlling plot display and interaction.
def show(self, title=None, window_size=None, interactive=True, auto_close=True,
interactive_update=False, full_screen=False, screenshot=None,
return_img=False, cpos=None, use_panel=None, jupyter_backend=None,
return_viewer=False, return_cpos=False, before_close_callback=None,
**kwargs):
"""
Display the plotting scene.
Parameters:
title (str): Window title
window_size (tuple): Window size (width, height)
interactive (bool): Enable interactive mode
auto_close (bool): Automatically close after display
interactive_update (bool): Enable interactive updates
full_screen (bool): Display in full screen
screenshot (str): Save screenshot to file
return_img (bool): Return screenshot as array
cpos (tuple): Camera position
use_panel (bool): Use panel for display
jupyter_backend (str): Jupyter backend to use
return_viewer (bool): Return viewer object
return_cpos (bool): Return camera position
before_close_callback (callable): Callback before closing
Returns:
Various: Depends on return options
"""
def close(self):
"""Close the plotting window and clean up resources."""
def clear(self, render=True):
"""
Clear all actors from the scene.
Parameters:
render (bool): Re-render after clearing
"""
def reset_camera(self, render=True):
"""
Reset camera to fit all actors in scene.
Parameters:
render (bool): Re-render after reset
"""Save plot images and export scenes.
def screenshot(self, filename=None, transparent_background=None,
return_img=False, window_size=None, scale=None):
"""
Take a screenshot of the current plot.
Parameters:
filename (str): Output filename
transparent_background (bool): Make background transparent
return_img (bool): Return image as numpy array
window_size (tuple): Override window size
scale (int): Resolution scaling factor
Returns:
None or np.ndarray: Image array if return_img=True
"""
def save_graphic(self, filename, title='PyVista Export', raster=True,
painter=True):
"""
Save plot as vector graphics.
Parameters:
filename (str): Output filename (.svg, .eps, .ps, .pdf, .tex)
title (str): Document title
raster (bool): Enable raster graphics
painter (bool): Enable painter mode
"""Manage camera position and orientation.
class Camera:
"""
Camera object for controlling viewpoint.
Attributes:
position: tuple - Camera position (x, y, z)
focal_point: tuple - Point camera looks at
up: tuple - Camera up vector
roll: float - Camera roll angle
elevation: float - Camera elevation angle
azimuth: float - Camera azimuth angle
distance: float - Distance to focal point
parallel_projection: bool - Use parallel projection
parallel_scale: float - Parallel projection scale
"""
def view_isometric(self, negative=False):
"""Set isometric view."""
def view_vector(self, vector, viewup=None):
"""
Set camera to look along vector direction.
Parameters:
vector (tuple): View direction vector
viewup (tuple): Up direction vector
"""
def zoom(self, value):
"""
Zoom camera by factor.
Parameters:
value (float): Zoom factor
"""
def set_position(self, position, reset=False):
"""
Set camera position.
Parameters:
position (tuple): Camera position (x, y, z)
reset (bool): Reset camera after positioning
"""
def set_focus(self, point):
"""
Set camera focal point.
Parameters:
point (tuple): Focal point coordinates
"""
def set_viewup(self, vector):
"""
Set camera up vector.
Parameters:
vector (tuple): Up direction vector
"""Control scene lighting.
class Light:
"""
Light source for illuminating scenes.
Attributes:
position: tuple - Light position
focal_point: tuple - Light focal point
color: tuple - Light color (R, G, B)
intensity: float - Light intensity
on: bool - Light on/off state
"""
def __init__(self, position=(0, 0, 1), focal_point=(0, 0, 0),
color=(1.0, 1.0, 1.0), light_type='camera', intensity=1.0,
cone_angle=30.0, exponent=1.0, positional=False,
show_actor=False, attenuation_values=(1.0, 0.0, 0.0)):
"""
Create light source.
Parameters:
position (tuple): Light position
focal_point (tuple): Light focal point
color (tuple): Light color
light_type (str): Light type ('camera', 'scene', 'headlight')
intensity (float): Light intensity
cone_angle (float): Cone angle for spotlights
exponent (float): Light attenuation exponent
positional (bool): Positional light
show_actor (bool): Show light actor
attenuation_values (tuple): Attenuation coefficients
"""
def add_light(self, light, only_active=False, render=True):
"""
Add light to scene.
Parameters:
light (Light): Light object to add
only_active (bool): Add only to active renderer
render (bool): Re-render after adding
"""
def remove_all_lights(self, render=True):
"""
Remove all lights from scene.
Parameters:
render (bool): Re-render after removal
"""Add text annotations to plots.
def add_text(self, text, position='upper_left', font_size=18, color=None,
font=None, shadow=False, name=None, viewport=False,
render=True) -> Actor:
"""
Add text annotation to plot.
Parameters:
text (str): Text string to display
position (str or tuple): Text position
font_size (int): Font size
color (str): Text color
font (str): Font family
shadow (bool): Add text shadow
name (str): Name for text actor
viewport (bool): Use viewport coordinates
render (bool): Re-render after adding
Returns:
Actor: Text actor object
"""
def add_point_labels(self, points, labels, point_color=None, point_size=None,
font_size=None, text_color=None, font_family=None,
shadow=False, show_points=True, always_visible=False,
name=None, render=True) -> tuple:
"""
Add labels at point locations.
Parameters:
points (array-like): Point coordinates
labels (list): Text labels for points
point_color (str): Point marker color
point_size (float): Point marker size
font_size (int): Label font size
text_color (str): Label text color
font_family (str): Font family
shadow (bool): Add text shadow
show_points (bool): Show point markers
always_visible (bool): Labels always visible
name (str): Name for label actors
render (bool): Re-render after adding
Returns:
tuple: Point and label actors
"""
def add_title(self, title, font_size=None, color=None, font=None,
shadow=False, render=True) -> Actor:
"""
Add title to plot.
Parameters:
title (str): Title text
font_size (int): Title font size
color (str): Title color
font (str): Font family
shadow (bool): Add shadow
render (bool): Re-render after adding
Returns:
Actor: Title actor
"""Add color bars and legends.
def add_scalar_bar(self, title=None, mapper=None, n_labels=5, italic=False,
bold=False, title_font_size=None, label_font_size=None,
color=None, font_family=None, shadow=False, width=None,
height=None, position_x=None, position_y=None,
vertical=True, interactive=None, fmt=None, use_opacity=True,
outline=False, nan_annotation=False, below_label=None,
above_label=None, background_color=None, n_colors=None,
categories=False, render=True) -> Actor:
"""
Add scalar color bar to plot.
Parameters:
title (str): Color bar title
mapper (object): Data mapper for color mapping
n_labels (int): Number of labels
italic (bool): Italic text
bold (bool): Bold text
title_font_size (int): Title font size
label_font_size (int): Label font size
color (str): Text color
font_family (str): Font family
shadow (bool): Add text shadow
width (float): Color bar width
height (float): Color bar height
position_x (float): X position
position_y (float): Y position
vertical (bool): Vertical orientation
interactive (bool): Interactive color bar
fmt (str): Number format string
use_opacity (bool): Show opacity
outline (bool): Draw outline
nan_annotation (bool): Show NaN annotation
below_label (str): Below-range label
above_label (str): Above-range label
background_color (str): Background color
n_colors (int): Number of color levels
categories (bool): Categorical colors
render (bool): Re-render after adding
Returns:
Actor: Scalar bar actor
"""Add interactive 3D widgets for manipulation.
def add_mesh_clip_plane(self, mesh, normal='x', invert=False, widget_color=None,
value=0.0, assign_to_axis=None, tubing=False,
origin_translation=True, outline_translation=False,
implicit=True, normal_rotation=True, crinkle=False,
interaction_event='end', name=None, **kwargs) -> tuple:
"""
Add interactive clipping plane widget.
Parameters:
mesh (DataSet): Mesh to clip
normal (str or tuple): Clipping plane normal
invert (bool): Invert clipping
widget_color (str): Widget color
value (float): Initial clipping value
assign_to_axis (str): Constrain to axis
tubing (bool): Show plane as tube
origin_translation (bool): Allow origin translation
outline_translation (bool): Allow outline translation
implicit (bool): Use implicit plane
normal_rotation (bool): Allow normal rotation
crinkle (bool): Show crinkled clipping
interaction_event (str): Widget interaction event
name (str): Actor name
Returns:
tuple: Clipped mesh and widget actors
"""
def add_mesh_slice_orthogonal(self, mesh, generate_triangles=False, widget_color=None,
tubing=False, interaction_event='end', **kwargs) -> tuple:
"""
Add orthogonal slicing widget.
Parameters:
mesh (DataSet): Mesh to slice
generate_triangles (bool): Triangulate slices
widget_color (str): Widget color
tubing (bool): Show planes as tubes
interaction_event (str): Widget interaction event
Returns:
tuple: Sliced meshes and widget actors
"""Create complex multi-panel visualizations.
def subplot(self, index_row, index_column=None):
"""
Set active subplot for rendering.
Parameters:
index_row (int): Row index or linear index
index_column (int): Column index
"""
def add_mesh_subplot(self, mesh, subplot_index, **kwargs):
"""
Add mesh to specific subplot.
Parameters:
mesh (DataSet): Mesh to add
subplot_index (tuple): Subplot indices (row, col)
**kwargs: Mesh rendering options
"""
def link_views(self, views=None):
"""
Link camera views between subplots.
Parameters:
views (list): List of subplot indices to link
"""
def unlink_views(self, views=None):
"""
Unlink camera views between subplots.
Parameters:
views (list): List of subplot indices to unlink
"""import pyvista as pv
import numpy as np
# Create sample data
mesh = pv.Sphere()
mesh['elevation'] = mesh.points[:, 2]
# Simple plot
mesh.plot(scalars='elevation', cmap='viridis')
# Using Plotter for more control
plotter = pv.Plotter()
plotter.add_mesh(mesh, scalars='elevation', cmap='coolwarm',
show_edges=True, show_scalar_bar=True)
plotter.add_title("Sphere with Elevation Data")
plotter.show()import pyvista as pv
# Load data
mesh = pv.examples.load_airplane()
# Create 2x2 subplot layout
plotter = pv.Plotter(shape=(2, 2))
# Different views in each subplot
plotter.subplot(0, 0)
plotter.add_mesh(mesh, color='red')
plotter.add_title("Red Airplane")
plotter.subplot(0, 1)
plotter.add_mesh(mesh, style='wireframe')
plotter.add_title("Wireframe")
plotter.subplot(1, 0)
plotter.add_mesh(mesh, style='points', point_size=10)
plotter.add_title("Points")
plotter.subplot(1, 1)
plotter.add_mesh(mesh.outline(), color='black', line_width=5)
plotter.add_mesh(mesh, opacity=0.5)
plotter.add_title("With Outline")
plotter.show()import pyvista as pv
# Load volume data
grid = pv.examples.download_brain()
# Create interactive plot with clipping
plotter = pv.Plotter()
# Add volume with clipping widget
plotter.add_mesh_clip_plane(grid, normal='x', widget_color='red')
# Add orthogonal slicing widget
plotter.add_mesh_slice_orthogonal(grid, widget_color='blue')
plotter.show()Install with Tessl CLI
npx tessl i tessl/pypi-pyvista