LoopStructural.visualisation.Loop3DView#

class LoopStructural.visualisation.Loop3DView(*args, **kwargs)#

Bases: Plotter

Loop3DView is a subclass of pyvista. Plotter that is designed to interface with the LoopStructural geological modelling package.

Parameters:
  • model (GeologicalModel, optional) – A loopstructural model used as reference for some methods, by default None

  • background (str, optional) – colour for the background, by default ‘white’

__init__(model=None, background='white', *args, **kwargs)#

Loop3DView is a subclass of pyvista. Plotter that is designed to interface with the LoopStructural geological modelling package.

Parameters:
  • model (GeologicalModel, optional) – A loopstructural model used as reference for some methods, by default None

  • background (str, optional) – colour for the background, by default ‘white’

Methods

__init__([model, background])

Loop3DView is a subclass of pyvista.

add_actor(actor[, reset_camera, name, ...])

Add an actor to render window.

add_affine_transform_widget(actor[, origin, ...])

Add a 3D affine transform widget.

add_arrows(cent, direction[, mag])

Add arrows to the plotter.

add_axes([interactive, line_width, color, ...])

Add an interactive axes widget in the bottom left corner.

add_axes_at_origin([x_color, y_color, ...])

Add axes actor at origin.

add_background_image(image_path[, scale, ...])

Add a background image to a plot.

add_blurring()

Add blurring.

add_bounding_box([color, corner_factor, ...])

Add an unlabeled and unticked box at the boundaries of plot.

add_box_axes(*[, interactive, line_width, ...])

Add an interactive color box axes widget in the bottom left corner.

add_box_widget(callback[, bounds, factor, ...])

Add a box widget to the scene.

add_camera3d_widget()

Add a camera3d widget allow to move the camera.

add_camera_orientation_widget([animate, ...])

Add a camera orientation widget to the active renderer.

add_chart(chart, *charts)

Add a chart to this renderer.

add_checkbox_button_widget(callback[, ...])

Add a checkbox button widget to the scene.

add_composite(dataset[, color, style, ...])

Add a composite dataset to the plotter.

add_cursor([bounds, focal_point, color])

Add a cursor of a PyVista or VTK dataset to the scene.

add_floor([face, i_resolution, ...])

Show a floor mesh.

add_key_event(key, callback)

Add a function to callback when the given key is pressed.

add_legend([labels, bcolor, border, size, ...])

Add a legend to render window.

add_legend_scale([corner_offset_factor, ...])

Annotate the render window with scale and distance information.

add_light(light[, only_active])

Add a Light to the scene.

add_line_widget(callback[, bounds, factor, ...])

Add a line widget to the scene.

add_lines(lines[, color, width, label, ...])

Add lines to the plotting object.

add_logo_widget([logo, position, size, opacity])

Add a logo widget to the top of the viewport.

add_measurement_widget([callback, color])

Interactively measure distance with a distance widget.

add_mesh(mesh[, color, style, scalars, ...])

Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene.

add_mesh_clip_box(mesh[, invert, ...])

Clip a mesh using a box widget.

add_mesh_clip_plane(mesh[, normal, invert, ...])

Clip a mesh using a plane widget.

add_mesh_isovalue(mesh[, scalars, ...])

Create a contour of a mesh with a slider.

add_mesh_slice(mesh[, normal, ...])

Slice a mesh using a plane widget.

add_mesh_slice_orthogonal(mesh[, ...])

Slice a mesh with three interactive planes.

add_mesh_slice_spline(mesh[, ...])

Slice a mesh with a spline widget.

add_mesh_threshold(mesh[, scalars, invert, ...])

Apply a threshold on a mesh with a slider.

add_north_arrow_widget([interactive, color, ...])

Add a geographic north arrow to the scene.

add_on_render_callback(callback[, render_event])

Add a method to be called post-render.

add_orientation_widget(actor[, interactive, ...])

Use the given actor in an orientation marker widget.

add_plane_widget(callback[, normal, origin, ...])

Add a plane widget to the scene.

add_point_labels(points, labels[, italic, ...])

Create a point actor with one label from list labels assigned to each point.

add_point_scalar_labels(points, labels[, ...])

Label the points from a dataset with the values of their scalars.

add_points(points[, style])

Add points to a mesh.

add_ruler(pointa, pointb[, flip_range, ...])

Add ruler.

add_scalar_bar([title, mapper, n_labels, ...])

Create scalar bar using the ranges as set by the last input mesh.

add_silhouette(mesh[, color, line_width, ...])

Add a silhouette of a PyVista or VTK dataset to the scene.

add_slider_widget(callback, rng[, value, ...])

Add a slider bar widget.

add_sphere_widget(callback[, center, ...])

Add one or many sphere widgets to a scene.

add_spline_widget(callback[, bounds, ...])

Create and add a spline widget to the scene.

add_text(text[, position, font_size, color, ...])

Add text to plot object in the top left corner by default.

add_text_slider_widget(callback, data[, ...])

Add a text slider bar widget.

add_timer_event(max_steps, duration, callback)

Add a function to callback as timer event.

add_title(title[, font_size, color, font, ...])

Add text to the top center of the plot.

add_volume(volume[, scalars, clim, ...])

Add a volume, rendered using a smart mapper by default.

add_volume_clip_plane(volume[, normal, ...])

Clip a volume using a plane widget.

clear()

Clear plot by removing all actors and properties.

clear_actors()

Clear actors from all renderers.

clear_box_widgets()

Remove all of the box widgets.

clear_button_widgets()

Remove all of the button widgets.

clear_camera3d_widgets()

Remove all of the camera3d widgets.

clear_camera_widgets()

Remove all of the camera widgets.

clear_events_for_key(key[, raise_on_missing])

Remove the callbacks associated to the key.

clear_line_widgets()

Remove all of the line widgets.

clear_logo_widgets()

Remove all of the logo widgets.

clear_measure_widgets()

Remove all of the measurement widgets.

clear_on_render_callbacks()

Clear all callback methods previously registered with render().

clear_plane_widgets()

Remove all of the plane widgets.

clear_slider_widgets()

Remove all of the slider widgets.

clear_sphere_widgets()

Remove all of the sphere widgets.

clear_spline_widgets()

Remove all of the spline widgets.

close()

Close the render window.

deep_clean()

Clean the plotter of the memory.

disable()

Disable this renderer's camera from being interactive.

disable_3_lights()

Please use enable_lightkit, this method has been deprecated.

disable_anti_aliasing([all_renderers])

Disable anti-aliasing.

disable_depth_of_field()

Disable depth of field plotting.

disable_depth_peeling()

Disable depth peeling.

disable_eye_dome_lighting()

Disable eye dome lighting (EDL).

disable_hidden_line_removal([all_renderers])

Disable hidden line removal.

disable_parallel_projection()

Reset the camera to use perspective projection.

disable_picking()

Disable any active picking and remove observers.

disable_shadows()

Disable shadows.

disable_ssao()

Disable surface space ambient occlusion (SSAO).

disable_stereo_render()

Disable anaglyph stereo rendering.

display()

enable()

Enable this renderer's camera to be interactive.

enable_2d_style()

Set the interactive style to 2D.

enable_3_lights([only_active])

Enable 3-lights illumination.

enable_anti_aliasing([aa_type, ...])

Enable anti-aliasing.

enable_block_picking([callback, side])

Enable composite block picking.

enable_cell_picking([callback, through, ...])

Enable picking of cells with a rectangle selection tool.

enable_custom_trackball_style([left, ...])

Set the interactive style to a custom style based on Trackball Camera.

enable_depth_of_field([automatic_focal_distance])

Enable depth of field plotting.

enable_depth_peeling([number_of_peels, ...])

Enable depth peeling to improve rendering of translucent geometry.

enable_element_picking([callback, mode, ...])

Select individual elements on a mesh.

enable_eye_dome_lighting()

Enable eye dome lighting (EDL).

enable_fly_to_right_click([callback])

Set the camera to track right click positions.

enable_geodesic_picking([callback, ...])

Enable picking at geodesic paths.

enable_hidden_line_removal([all_renderers])

Enable hidden line removal.

enable_horizon_picking([callback, normal, ...])

Enable horizon picking.

enable_image_style()

Set the interactive style to Image.

enable_joystick_actor_style()

Set the interactive style to Joystick Actor.

enable_joystick_style()

Set the interactive style to Joystick Camera.

enable_lightkit([only_active])

Enable the default light-kit lighting.

enable_mesh_picking([callback, show, ...])

Enable picking of a mesh.

enable_parallel_projection()

Enable parallel projection.

enable_path_picking([callback, ...])

Enable picking at paths.

enable_point_picking([callback, tolerance, ...])

Enable picking at points under the cursor.

enable_rectangle_picking([callback, ...])

Enable rectangle based picking at cells.

enable_rectangle_through_picking([callback, ...])

Enable rectangle based cell picking through the scene.

enable_rectangle_visible_picking([callback, ...])

Enable rectangle based cell picking on visible surfaces.

enable_rubber_band_2d_style()

Set the interactive style to Rubber Band 2D.

enable_rubber_band_style()

Set the interactive style to Rubber Band Picking.

enable_shadows()

Enable shadows.

enable_ssao([radius, bias, kernel_size, blur])

Enable surface space ambient occlusion (SSAO).

enable_stereo_render()

Enable anaglyph stereo rendering.

enable_surface_point_picking([callback, ...])

Enable picking of a point on the surface of a mesh.

enable_terrain_style([mouse_wheel_zooms, ...])

Set the interactive style to Terrain.

enable_trackball_actor_style()

Set the interactive style to Trackball Actor.

enable_trackball_style()

Set the interactive style to Trackball Camera.

enable_zoom_style()

Set the interactive style to Rubber Band Zoom.

export_gltf(filename[, inline_data, ...])

Export the current rendering scene as a glTF file.

export_html(filename)

Export this plotter as an interactive scene to a HTML file.

export_obj(filename)

Export scene to OBJ format.

export_vrml(filename)

Export the current rendering scene as a VRML file.

export_vtksz([filename, format])

Export this plotter as a VTK.js OfflineLocalView file.

fly_to(point)

Move the current camera's focal point to a position point.

fly_to_mouse_position([focus])

Focus on last stored mouse position.

generate_orbital_path([factor, n_points, ...])

Generate an orbital path around the data scene.

get_default_cam_pos([negative])

Return the default focal points and viewup.

get_image_depth([fill_value, ...])

Return a depth image representing current render window.

get_pick_position()

Get the pick position or area.

hide_axes()

Hide the axes orientation widget.

hide_axes_all()

Hide the axes orientation widget in all renderers.

image_scale_context([scale])

Set the image scale in an isolated context.

import_3ds(filename)

Import a 3DS file into the plotter.

import_gltf(filename[, set_camera])

Import a glTF file into the plotter.

import_obj(filename[, filename_mtl])

Import from .obj wavefront files.

import_vrml(filename)

Import a VRML file into the plotter.

increment_point_size_and_line_width(increment)

Increment point size and line width of all actors.

isometric_view()

Reset the camera to a default isometric view.

isometric_view_interactive()

Set the current interactive render window to isometric view.

key_press_event(*args)

Listen for key press event.

left_button_down(*args)

Register the event for a left button down click.

link_views([views])

Link the views' cameras.

open_gif(filename[, loop, fps, palettesize, ...])

Open a gif file.

open_movie(filename[, framerate, quality])

Establish a connection to the ffmpeg writer.

orbit_on_path([path, focus, step, viewup, ...])

Orbit on the given path focusing on the focus point.

pick_click_position()

Get corresponding click location in the 3D plot.

pick_mouse_position()

Get corresponding mouse location in the 3D plot.

plot_block_model([cmap, model, ...])

plot_data(feature[, value, vector, scale, ...])

plot_fault(fault[, surface, slip_vector, ...])

plot_fault_displacements([fault_list, ...])

plot_fold(fold[, pyvista_kwargs])

plot_model_surfaces([strati, faults, cmap, ...])

plot_scalar_field(geological_feature[, ...])

plot_surface(geological_feature[, value, ...])

Add an isosurface of a geological feature to the model

plot_vector_field(geological_feature[, ...])

remove_actor(actor[, reset_camera, render])

Remove an actor from the Renderer.

remove_all_lights([only_active])

Remove all lights from the scene.

remove_background_image()

Remove the background image at the current renderer.

remove_blurring()

Remove a single blurring pass.

remove_bounding_box([render])

Remove bounding box.

remove_bounds_axes()

Remove bounds axes.

remove_chart(chart_or_index)

Remove a chart from this renderer.

remove_environment_texture()

Remove the environment texture.

remove_floors([clear_kwargs, render])

Remove all floor actors.

remove_legend([render])

Remove the legend actor.

remove_scalar_bar([title, render])

Remove a scalar bar.

render()

Render the main window.

reset_camera([render, bounds])

Reset the camera of the active render window.

reset_camera_clipping_range()

Reset camera clipping planes.

reset_key_events()

Reset all of the key press events to their defaults.

rotate(angles)

Rotate the camera by the given angles order is roll, azimuth, elevation as defined by pyvista

save_graphic(filename[, title, raster, painter])

Save a screenshot of the rendering window as a graphic file.

screenshot([filename, ...])

Take screenshot at current camera position.

set_background(color[, top, right, side, ...])

Set the background color.

set_chart_interaction(interactive[, toggle])

Set or toggle interaction with charts for the active renderer.

set_color_cycler(color_cycler[, all_renderers])

Set or reset the color cycler.

set_environment_texture(texture[, is_srgb])

Set the environment texture used for image based lighting.

set_focus(point)

Set focus to a point.

set_position(point[, reset, render])

Set camera position to a point.

set_scale([xscale, yscale, zscale, ...])

Scale all the actors in the scene.

set_viewup(vector[, reset, render])

Set camera viewup vector.

show([title, window_size, interactive, ...])

Display the plotting window.

show_axes()

Show the axes orientation widget.

show_axes_all()

Show the axes orientation widget in all renderers.

show_bounds([mesh, bounds, axes_ranges, ...])

Add bounds axes.

show_grid(**kwargs)

Show grid lines and bounds axes labels.

store_click_position(*args)

Store click position in viewport coordinates.

store_mouse_position(*args)

Store mouse position.

subplot(index_row[, index_column])

Set the active subplot.

track_click_position([callback, side, ...])

Keep track of the click position.

track_mouse_position()

Keep track of the mouse position.

unlink_views([views])

Unlink the views' cameras.

untrack_click_position([side])

Stop tracking the click position.

untrack_mouse_position()

Stop tracking the mouse position.

update([stime, force_redraw])

Update window, redraw, process messages query.

update_bounds_axes()

Update the bounds axes of the render window.

update_coordinates(points[, mesh, render])

Update the points of an object in the plotter.

update_scalar_bar_range(clim[, name])

Update the value range of the active or named scalar bar.

update_scalars(scalars[, mesh, render])

Update scalars of an object in the plotter.

view_isometric([negative, render, bounds])

Reset the camera to a default isometric view.

view_vector(vector[, viewup, render, bounds])

Point the camera in the direction of the given vector.

view_xy([negative, render, bounds])

View the XY plane.

view_xz([negative, render, bounds])

View the XZ plane.

view_yx([negative, render, bounds])

View the YX plane.

view_yz([negative, render, bounds])

View the YZ plane.

view_zx([negative, render, bounds])

View the ZX plane.

view_zy([negative, render, bounds])

View the ZY plane.

where_is(name)

Return the subplot coordinates of a given actor.

window_size_context([window_size])

Set the render window size in an isolated context.

write_frame()

Write a single frame to the movie file.

zoom_camera(value)

Zoom of the camera and render.

Attributes

actors

Return the actors of the active renderer.

background_color

Return the background color of the active render window.

bounds

Return the bounds of the active renderer.

camera

Return the active camera of the active renderer.

camera_position

Return camera position of the active render window.

camera_set

Return or set if the camera of the active renderer has been set.

center

Return the center of the active renderer.

click_position

image

Return an image array of current render window.

image_depth

Return a depth image representing current render window.

image_scale

Get or set the scale factor when saving a screenshot.

last_update_time

legend

Legend actor.

length

Return the length of the diagonal of the bounding box of the scene.

meshes

Return plotter meshes.

mouse_position

parallel_projection

Return or set parallel projection state of active render window.

parallel_scale

Return or set parallel scale of active render window.

pickable_actors

Return or set the pickable actors.

picked_actor

Return the picked mesh.

picked_block_index

Return the picked block index.

picked_cell

Return the picked cell.

picked_cells

Return the picked cells.

picked_mesh

Return the picked mesh.

picked_point

Return the picked point.

render_window

Access the vtkRenderWindow attached to this plotter.

renderer

Return the active renderer.

scalar_bar

First scalar bar (kept for backwards compatibility).

scalar_bars

Scalar bars.

scale

Return the scaling of the active renderer.

shape

Return the shape of the plotter.

suppress_rendering

Get or set whether to suppress render calls.

theme

Return or set the theme used for this plotter.

window_size

Return the render window size in (width, height).

property actors#

Return the actors of the active renderer.

Returns:

dict – Dictionary of active actors.

add_actor(actor, reset_camera=False, name=None, culling=False, pickable=True, render=True, remove_existing_actor=True)#

Add an actor to render window.

Creates an actor if input is a mapper.

Parameters:
  • actor (vtk.vtkActor | vtk.vtkMapper | pyvista.Actor) – The actor to be added. Can be either vtkActor or vtkMapper.

  • reset_camera (bool, default: False) – Resets the camera when True.

  • name (str, optional) – Name to assign to the actor. Defaults to the memory address.

  • culling (str, default: False) – Does not render faces that are culled. Options are 'front' or 'back'. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed.

  • pickable (bool, default: True) – Whether to allow this actor to be pickable within the render window.

  • render (bool, default: True) – If the render window is being shown, trigger a render after adding the actor.

  • remove_existing_actor (bool, default: True) – Removes any existing actor if the named actor name is already present.

Returns:

  • actor (vtk.vtkActor or pyvista.Actor) – The actor.

  • actor_properties (vtk.Properties) – Actor properties.

add_affine_transform_widget(actor, origin=None, start=True, scale=0.15, line_radius=0.02, always_visible=True, axes_colors=None, axes=None, release_callback=None, interact_callback=None)#

Add a 3D affine transform widget.

This widget allows interactive transformations including translation and rotation using the left mouse button.

Parameters:
  • actor (pyvista.Actor) – The actor to which the widget is attached to.

  • origin (sequence[float], optional) – Origin of the widget. Default is the origin of the main actor.

  • start (bool, default: True) – If True, start the widget immediately.

  • scale (float, default: 0.15) – Scale factor for the widget relative to the length of the actor.

  • line_radius (float, default: 0.02) – Relative radius of the lines composing the widget.

  • always_visible (bool, default: True) – Make the widget always visible. Setting this to False will cause the widget geometry to be hidden by other actors in the plotter.

  • axes_colors (tuple[ColorLike], optional) – Uses the theme by default. Configure the individual axis colors by modifying either the theme with pyvista.global_theme.axes.x_color = <COLOR> or setting this with a tuple as in ('r', 'g', 'b').

  • axes (numpy.ndarray, optional) – (3, 3) Numpy array defining the X, Y, and Z axes. By default this matches the default coordinate system.

  • release_callback (callable, optional) – Call this method when releasing the left mouse button. It is passed the user_matrix of the actor.

  • interact_callback (callable, optional) – Call this method when moving the mouse with the left mouse button pressed down and a valid movement actor selected. It is passed the user_matrix of the actor.

Returns:

pyvista.widgets.AffineWidget3D – The affine widget.

Notes

After interacting with the actor, the transform will be stored within pyvista.Actor.user_matrix but will not be applied to the dataset. Use this matrix in conjunction with pyvista.DataSetFilters.transform() to transform the dataset.

Examples

Add the 3d affine widget.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere())
>>> widget = pl.add_affine_transform_widget(actor)
>>> pl.show()

Access the transform from the actor.

>>> actor.user_matrix
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])
add_arrows(cent, direction, mag=1, **kwargs)#

Add arrows to the plotter.

Parameters:
  • cent (np.ndarray) – Array of centers.

  • direction (np.ndarray) – Array of direction vectors.

  • mag (float, optional) – Amount to scale the direction vectors.

  • **kwargs (dict, optional) – See pyvista.Plotter.add_mesh() for optional keyword arguments.

Returns:

pyvista.Actor – Actor of the arrows.

Examples

Plot a random field of vectors and save a screenshot of it.

>>> import numpy as np
>>> import pyvista as pv
>>> rng = np.random.default_rng(seed=0)
>>> cent = rng.random((10, 3))
>>> direction = rng.random((10, 3))
>>> plotter = pv.Plotter()
>>> _ = plotter.add_arrows(cent, direction, mag=2)
>>> plotter.show()
add_axes(interactive=None, line_width=2, color=None, x_color=None, y_color=None, z_color=None, xlabel='X', ylabel='Y', zlabel='Z', labels_off=False, box=None, box_args=None, viewport=(0, 0, 0.2, 0.2), **kwargs)#

Add an interactive axes widget in the bottom left corner.

Parameters:
  • interactive (bool, optional) – Enable this orientation widget to be moved by the user.

  • line_width (int, default: 2) – The width of the marker lines.

  • color (ColorLike, optional) – Color of the labels.

  • x_color (ColorLike, optional) – Color used for the x-axis arrow. Defaults to theme axes parameters.

  • y_color (ColorLike, optional) – Color used for the y-axis arrow. Defaults to theme axes parameters.

  • z_color (ColorLike, optional) – Color used for the z-axis arrow. Defaults to theme axes parameters.

  • xlabel (str, default: "X") – Text used for the x-axis.

  • ylabel (str, default: "Y") – Text used for the y-axis.

  • zlabel (str, default: "Z") – Text used for the z-axis.

  • labels_off (bool, default: false) – Enable or disable the text labels for the axes.

  • box (bool, optional) –

    Show a box orientation marker. Use box_args to adjust. See pyvista.create_axes_orientation_box() for details.

    Deprecated since version 0.43.0: The is deprecated. Use add_box_axes method instead.

  • box_args (dict, optional) – Parameters for the orientation box widget when box=True. See the parameters of pyvista.create_axes_orientation_box().

  • viewport (sequence[float], default: (0, 0, 0.2, 0.2)) – Viewport (xstart, ystart, xend, yend) of the widget.

  • **kwargs (dict, optional) – Used for passing parameters for the orientation marker widget. See the parameters of pyvista.create_axes_marker().

Returns:

AxesActor – Axes actor of the added widget.

See also

show_axes

Similar method which calls add_axes() without any parameters.

add_axes_at_origin

Add an pyvista.AxesActor to the origin of a scene.

Examples

Show axes without labels and with thick lines.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Box(), show_edges=True)
>>> _ = pl.add_axes(line_width=5, labels_off=True)
>>> pl.show()

Specify more parameters for the axes marker.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Box(), show_edges=True)
>>> _ = pl.add_axes(
...     line_width=5,
...     cone_radius=0.6,
...     shaft_length=0.7,
...     tip_length=0.3,
...     ambient=0.5,
...     label_size=(0.4, 0.16),
... )
>>> pl.show()
add_axes_at_origin(x_color=None, y_color=None, z_color=None, xlabel='X', ylabel='Y', zlabel='Z', line_width=2, labels_off=False)#

Add axes actor at origin.

Parameters:
  • x_color (ColorLike, optional) – The color of the x axes arrow.

  • y_color (ColorLike, optional) – The color of the y axes arrow.

  • z_color (ColorLike, optional) – The color of the z axes arrow.

  • xlabel (str, default: "X") – The label of the x axes arrow.

  • ylabel (str, default: "Y") – The label of the y axes arrow.

  • zlabel (str, default: "Z") – The label of the z axes arrow.

  • line_width (int, default: 2) – Width of the arrows.

  • labels_off (bool, default: False) – Disables the label text when True.

Returns:

vtk.vtkAxesActor – Actor of the axes.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere(center=(2, 0, 0)), color='r')
>>> _ = pl.add_mesh(pv.Sphere(center=(0, 2, 0)), color='g')
>>> _ = pl.add_mesh(pv.Sphere(center=(0, 0, 2)), color='b')
>>> _ = pl.add_axes_at_origin()
>>> pl.show()
add_background_image(image_path, scale=1.0, auto_resize=True, as_global=True)#

Add a background image to a plot.

Parameters:
  • image_path (str) – Path to an image file.

  • scale (float, default: 1.0) – Scale the image larger or smaller relative to the size of the window. For example, a scale size of 2 will make the largest dimension of the image twice as large as the largest dimension of the render window.

  • auto_resize (bool, default: True) – Resize the background when the render window changes size.

  • as_global (bool, default: True) – When multiple render windows are present, setting as_global=False will cause the background to only appear in one window.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(pv.Sphere())
>>> plotter.add_background_image(examples.mapfile)
>>> plotter.show()
add_blurring()#

Add blurring.

This can be added several times to increase the degree of blurring.

Examples

Add two blurring passes to the plotter and show it.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.add_blurring()
>>> pl.add_blurring()
>>> pl.show()

See blur_example for a full example using this method.

add_bounding_box(color='grey', corner_factor=0.5, line_width=None, opacity=1.0, render_lines_as_tubes=False, lighting=None, reset_camera=None, outline=True, culling='front')#

Add an unlabeled and unticked box at the boundaries of plot.

Useful for when wanting to plot outer grids while still retaining all edges of the boundary.

Parameters:
  • color (ColorLike, default: "grey") –

    Color of all labels and axis titles. Default white. Either a string, rgb sequence, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • corner_factor (float, default: 0.5) – This is the factor along each axis to draw the default box. Default is 0.5 to show the full box.

  • line_width (float, optional) – Thickness of lines.

  • opacity (float, default: 1.0) – Opacity of mesh. Should be between 0 and 1.

  • render_lines_as_tubes (bool, default: False) – Show lines as thick tubes rather than flat lines. Control the width with line_width.

  • lighting (bool, optional) – Enable or disable directional lighting for this actor.

  • reset_camera (bool, optional) – Reset camera position when True to include all actors.

  • outline (bool, default: True) – Default is True. when False, a box with faces is shown with the specified culling.

  • culling (str, default: "front") – Does not render faces on the bounding box that are culled. Options are 'front' or 'back'.

Returns:

vtk.vtkActor – VTK actor of the bounding box.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> _ = pl.add_bounding_box(line_width=5, color='black')
>>> pl.show()
add_box_axes(*, interactive=None, line_width=2, text_scale=0.366667, edge_color='black', x_color=None, y_color=None, z_color=None, xlabel='X', ylabel='Y', zlabel='Z', x_face_color='white', y_face_color='white', z_face_color='white', label_color=None, labels_off=False, opacity=0.5, show_text_edges=False, viewport=(0, 0, 0.2, 0.2))#

Add an interactive color box axes widget in the bottom left corner.

Parameters:
  • interactive (bool, optional) – Enable this orientation widget to be moved by the user.

  • line_width (float, optional) – The width of the marker lines.

  • text_scale (float, optional) – Size of the text relative to the faces.

  • edge_color (ColorLike, optional) – Color of the edges.

  • x_color (ColorLike, optional) – Color of the x-axis text.

  • y_color (ColorLike, optional) – Color of the y-axis text.

  • z_color (ColorLike, optional) – Color of the z-axis text.

  • xlabel (str, optional) – Text used for the x-axis.

  • ylabel (str, optional) – Text used for the y-axis.

  • zlabel (str, optional) – Text used for the z-axis.

  • x_face_color (ColorLike, optional) – Color used for the x-axis arrow. Defaults to theme axes parameters.

  • y_face_color (ColorLike, optional) – Color used for the y-axis arrow. Defaults to theme axes parameters.

  • z_face_color (ColorLike, optional) – Color used for the z-axis arrow. Defaults to theme axes parameters.

  • label_color (ColorLike, optional) – Color of the labels.

  • labels_off (bool, optional) – Enable or disable the text labels for the axes.

  • opacity (float, optional) – Opacity in the range of [0, 1] of the orientation box.

  • show_text_edges (bool, optional) – Enable or disable drawing the vector text edges.

  • viewport (sequence[float], default: (0, 0, 0.2, 0.2)) – Viewport (xstart, ystart, xend, yend) of the widget.

Returns:

vtk.vtkAxesActor – Axes actor.

Examples

Use the axes orientation widget instead of the default arrows.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> _ = pl.add_box_axes()
>>> pl.show()
add_box_widget(callback, bounds=None, factor=1.25, rotation_enabled=True, color=None, use_planes=False, outline_translation=True, pass_widget=False, interaction_event='end')#

Add a box widget to the scene.

This is useless without a callback function. You can pass a callable function that takes a single argument, the PolyData box output from this widget, and performs a task with that box.

Parameters:
  • callback (callable) – The method called every time the box is updated. This has two options: Take a single argument, the PolyData box (default) or if use_planes=True, then it takes a single argument of the plane collection as a vtkPlanes object.

  • bounds (tuple(float)) – Length 6 tuple of the bounding box where the widget is placed.

  • factor (float, optional) – An inflation factor to expand on the bounds when placing.

  • rotation_enabled (bool, optional) – If False, the box widget cannot be rotated and is strictly orthogonal to the Cartesian axes.

  • color (ColorLike, optional) – Either a string, rgb sequence, or hex color string. Defaults to pyvista.global_theme.font.color.

  • use_planes (bool, optional) – Changes the arguments passed to the callback to the planes that make up the box.

  • outline_translation (bool, optional) – If False, the box widget cannot be translated and is strictly placed at the given bounds.

  • pass_widget (bool, optional) – If True, the widget will be passed as the last argument of the callback.

  • interaction_event (vtk.vtkCommand.EventIds, str, optional) –

    The VTK interaction event to use for triggering the callback. Accepts either the strings 'start', 'end', 'always' or a vtk.vtkCommand.EventIds.

    Changed in version 0.38.0: Now accepts either strings or vtk.vtkCommand.EventIds.

Returns:

vtk.vtkBoxWidget – Box widget.

Examples

Shows an interactive box that is used to resize and relocate a sphere.

>>> import pyvista as pv
>>> import numpy as np
>>> plotter = pv.Plotter()
>>> def simulate(widget):
...     bounds = widget.bounds
...     new_center = np.array(
...         [
...             (bounds[0] + bounds[1]) / 2,
...             (bounds[2] + bounds[3]) / 2,
...             (bounds[4] + bounds[5]) / 2,
...         ]
...     )
...     new_radius = (
...         min(
...             (bounds[1] - bounds[0]) / 2,
...             (bounds[3] - bounds[2]) / 2,
...             (bounds[5] - bounds[4]) / 2,
...         )
...         - 0.3
...     )
...     sphere = pv.Sphere(new_radius, new_center)
...     _ = plotter.add_mesh(sphere, name="Sphere")
...
>>> _ = plotter.add_box_widget(callback=simulate)
>>> plotter.show()
add_camera3d_widget()#

Add a camera3d widget allow to move the camera.

Note

This widget requires vtk>=9.3.0.

Returns:

vtkCamera3DWidget – The camera3d widget.

Examples

Add a camera3d widget to the scene.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plotter = pv.Plotter(shape=(1, 2))
>>> _ = plotter.add_mesh(sphere, show_edges=True)
>>> plotter.subplot(0, 1)
>>> _ = plotter.add_mesh(sphere, show_edges=True)
>>> _ = plotter.add_camera3d_widget()
>>> plotter.show(cpos=plotter.camera_position)
add_camera_orientation_widget(animate=True, n_frames=20)#

Add a camera orientation widget to the active renderer.

Note

This widget requires vtk>=9.1.0.

Parameters:
  • animate (bool, default: True) – Enable or disable jump-to-axis-view animation.

  • n_frames (int, default: 20) – The number of frames to animate the jump-to-axis-viewpoint feature.

Returns:

vtkCameraOrientationWidget – Camera orientation widget.

Examples

Add a camera orientation widget to the scene.

>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
...     mesh, scalars=range(6), show_scalar_bar=False
... )
>>> _ = plotter.add_camera_orientation_widget()
>>> plotter.show()
add_chart(chart, *charts)#

Add a chart to this renderer.

Parameters:
  • chart (Chart) – Chart to add to renderer.

  • *charts (Chart) – Charts to add to renderer.

Examples

>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.plot(range(10), range(10))
>>> pl = pv.Plotter()
>>> pl.add_chart(chart)
>>> pl.show()
add_checkbox_button_widget(callback, value=False, position=(10.0, 10.0), size=50, border_size=5, color_on='blue', color_off='grey', background_color='white')#

Add a checkbox button widget to the scene.

This is useless without a callback function. You can pass a callable function that takes a single argument, the state of this button widget and performs a task with that value.

Parameters:
  • callback (callable) – The method called every time the button is clicked. This should take a single parameter: the bool value of the button.

  • value (bool, default: False) – The default state of the button.

  • position (sequence[float], default: (10.0, 10.0)) – The absolute coordinates of the bottom left point of the button.

  • size (int, default: 50) – The size of the button in number of pixels.

  • border_size (int, default: 5) – The size of the borders of the button in pixels.

  • color_on (ColorLike, optional) – The color used when the button is checked. Default is 'blue'.

  • color_off (ColorLike, optional) – The color used when the button is not checked. Default is 'grey'.

  • background_color (ColorLike, optional) – The background color of the button. Default is 'white'.

Returns:

vtk.vtkButtonWidget – The VTK button widget configured as a checkbox button.

Examples

The following example generates a static image of the widget.

>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> p = pv.Plotter()
>>> actor = p.add_mesh(mesh)
>>> def toggle_vis(flag):
...     actor.SetVisibility(flag)
...
>>> _ = p.add_checkbox_button_widget(toggle_vis, value=True)
>>> p.show()

Download the interactive example at checkbox_widget_example.

add_composite(dataset, color=None, style=None, scalars=None, clim=None, show_edges=None, edge_color=None, point_size=None, 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, render_points_as_spheres=None, render_lines_as_tubes=None, smooth_shading=None, split_sharp_edges=None, ambient=None, diffuse=None, specular=None, specular_power=None, nan_color=None, nan_opacity=1.0, culling=None, rgb=None, below_color=None, above_color=None, annotations=None, pickable=True, preference='point', log_scale=False, pbr=None, metallic=None, roughness=None, render=True, component=None, color_missing_with_nan=False, copy_mesh=False, show_vertices=None, edge_opacity=None, **kwargs)#

Add a composite dataset to the plotter.

Parameters:
  • dataset (pyvista.MultiBlock) – A pyvista.MultiBlock dataset.

  • color (ColorLike, default: pyvista.plotting.themes.Theme.color) – Use to make the entire mesh have a single solid color. Either a string, RGB list, or hex color string. For example: color='white', color='w', color=[1.0, 1.0, 1.0], or color='#FFFFFF'. Color will be overridden if scalars are specified. To color each element of the composite dataset individually, you will need to iteratively call add_mesh for each sub-dataset.

  • style (str, default: 'wireframe') – Visualization style of the mesh. One of the following: style='surface', style='wireframe', style='points'. Defaults to 'surface'. Note that 'wireframe' only shows a wireframe of the outer geometry.

  • scalars (str, optional) – Scalars used to “color” the points or cells of the dataset. Accepts only a string name of an array that is present on the composite dataset.

  • clim (sequence[float], optional) – Two item color bar range for scalars. Defaults to minimum and maximum of scalars array. Example: [-1, 2]. rng is also an accepted alias for this.

  • show_edges (bool, default: pyvista.global_theme.show_edges) – Shows the edges of a mesh. Does not apply to a wireframe representation.

  • edge_color (ColorLike, default: pyvista.global_theme.edge_color) –

    The solid color to give the edges when show_edges=True. Either a string, RGB list, or hex color string.

    Defaults to pyvista.global_theme.edge_color.

  • point_size (float, default: 5.0) – Point size of any points in the dataset plotted. Also applicable when style=’points’. Default 5.0.

  • line_width (float, optional) – Thickness of lines. Only valid for wireframe and surface representations.

  • opacity (float, default: 1.0) – Opacity of the mesh. A single float value that will be applied globally opacity of the mesh and uniformly applied everywhere - should be between 0 and 1.

  • flip_scalars (bool, default: False) – Flip direction of cmap. Most colormaps allow *_r suffix to do this as well.

  • lighting (bool, default: True) – Enable or disable view direction lighting.

  • n_colors (int, default: 256) – Number of colors to use when displaying scalars. The scalar bar will also have this many colors.

  • interpolate_before_map (bool, default: True) – Enabling makes for a smoother scalars display. When False, OpenGL will interpolate the mapped colors which can result in showing colors that are not present in the color map.

  • cmap (str | list, | pyvista.LookupTable, default: pyvista.plotting.themes.Theme.cmap) –

    If a string, this is the name of the matplotlib colormap to use when mapping the scalars. See available Matplotlib colormaps. Only applicable for when displaying scalars. colormap is also an accepted alias for this. If colorcet or cmocean are installed, their colormaps can be specified by name.

    You can also specify a list of colors to override an existing colormap with a custom one. For example, to create a three color colormap you might specify ['green', 'red', 'blue'].

    This parameter also accepts a pyvista.LookupTable. If this is set, all parameters controlling the color map like n_colors will be ignored.

  • label (str, optional) – String label to use when adding a legend to the scene with pyvista.Plotter.add_legend().

  • reset_camera (bool, optional) – Reset the camera after adding this mesh to the scene. The default setting is None, where the camera is only reset if this plotter has already been shown. If False, the camera is not reset regardless of the state of the Plotter. When True, the camera is always reset.

  • scalar_bar_args (dict, optional) – Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see pyvista.Plotter.add_scalar_bar().

  • show_scalar_bar (bool) – If False, a scalar bar will not be added to the scene. Defaults to True unless rgba=True.

  • multi_colors (bool | str | cycler.Cycler | sequence[ColorLike], default: False) –

    Color each block by a solid color using a custom cycler.

    If True, the default ‘matplotlib’ color cycler is used.

    See set_color_cycler for usage of custom color cyclers.

  • 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.

  • render_points_as_spheres (bool, default: False) – Render points as spheres rather than dots.

  • render_lines_as_tubes (bool, default: False) – Show lines as thick tubes rather than flat lines. Control the width with line_width.

  • smooth_shading (bool, default: :attr`pyvista.plotting.themes.Theme.smooth_shading`) – Enable smooth shading when True using the Phong shading algorithm. When False, uses flat shading. Automatically enabled when pbr=True. See shading_example.

  • split_sharp_edges (bool, default: False) – Split sharp edges exceeding 30 degrees when plotting with smooth shading. Control the angle with the optional keyword argument feature_angle. By default this is False unless overridden by the global or plotter theme. Note that enabling this will create a copy of the input mesh within the plotter. See shading_example.

  • ambient (float, default: 0.0) – When lighting is enabled, this is the amount of light in the range of 0 to 1 (default 0.0) that reaches the actor when not directed at the light source emitted from the viewer.

  • diffuse (float, default: 1.0) – The diffuse lighting coefficient.

  • specular (float, default: 0.0) – The specular lighting coefficient.

  • specular_power (float, default: 1.0) – The specular power. Between 0.0 and 128.0.

  • nan_color (ColorLike, default: pyvista.plotting.themes.Theme.nan_color) – The color to use for all NaN values in the plotted scalar array.

  • nan_opacity (float, default: 1.0) – Opacity of NaN values. Should be between 0 and 1.

  • culling (str, bool, default: False) –

    Does not render faces that are culled. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. One of the following:

    • True - Enable backface culling

    • "b" - Enable backface culling

    • "back" - Enable backface culling

    • "backface" - Enable backface culling

    • "f" - Enable frontface culling

    • "front" - Enable frontface culling

    • "frontface" - Enable frontface culling

    • False - Disable both backface and frontface culling

  • rgb (bool, default: False) – If an 2 dimensional array is passed as the scalars, plot those values as RGB(A) colors. rgba is also an accepted alias for this. Opacity (the A) is optional. If a scalars array ending with "_rgb" or "_rgba" is passed, the default becomes True. This can be overridden by setting this parameter to False.

  • below_color (ColorLike, optional) – Solid color for values below the scalars range (clim). This will automatically set the scalar bar below_label to 'below'.

  • above_color (ColorLike, optional) – Solid color for values below the scalars range (clim). This will automatically set the scalar bar above_label to 'above'.

  • annotations (dict, optional) – Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the string annotations.

  • pickable (bool, default: True) – Set whether this actor is pickable.

  • preference (str, default: 'point') – For each block, when block.n_points == block.n_cells and setting scalars, this parameter sets how the scalars will be mapped to the mesh. For example, when 'point' the scalars will be associated with the mesh points if available. Can be either 'point' or 'cell'.

  • log_scale (bool, default: False) – Use log scale when mapping data to colors. Scalars less than zero are mapped to the smallest representable positive float.

  • pbr (bool, default: False) – Enable physics based rendering (PBR) if the mesh is PolyData. Use the color argument to set the base color.

  • metallic (float, default: 0.0) – Usually this value is either 0 or 1 for a real material but any value in between is valid. This parameter is only used by PBR interpolation.

  • roughness (float, default: 0.5) – This value has to be between 0 (glossy) and 1 (rough). A glossy material has reflections and a high specular part. This parameter is only used by PBR interpolation.

  • render (bool, default: True) – Force a render when True.

  • component (int, optional) – Set component of vector valued scalars to plot. Must be nonnegative, if supplied. If None, the magnitude of the vector is plotted.

  • color_missing_with_nan (bool, default: False) – Color any missing values with the nan_color. This is useful when not all blocks of the composite dataset have the specified scalars.

  • copy_mesh (bool, default: False) – If True, a copy of the mesh will be made before adding it to the plotter. This is useful if e.g. you would like to add the same mesh to a plotter multiple times and display different scalars. Setting copy_mesh to False is necessary if you would like to update the mesh after adding it to the plotter and have these updates rendered, e.g. by changing the active scalars or through an interactive widget.

  • show_vertices (bool, optional) –

    When style is not 'points', render the external surface vertices. The following optional keyword arguments may be used to control the style of the vertices:

    • vertex_color - The color of the vertices

    • vertex_style - Change style to 'points_gaussian'

    • vertex_opacity - Control the opacity of the vertices

  • edge_opacity (float, optional) –

    Edge opacity of the mesh. A single float value that will be applied globally edge opacity of the mesh and uniformly applied everywhere - should be between 0 and 1.

    Note

    edge_opacity uses SetEdgeOpacity as the underlying method which requires VTK version 9.3 or higher. If SetEdgeOpacity is not available, edge_opacity is set to 1.

  • **kwargs (dict, optional) – Optional keyword arguments.

Returns:

  • pyvista.Actor – Actor of the composite dataset.

  • pyvista.CompositePolyDataMapper – Composite PolyData mapper.

Examples

Add a sphere and a cube as a multiblock dataset to a plotter and then change the visibility and color of the blocks.

Note index 1 and 2 are used to access the individual blocks of the composite dataset. This is because the pyvista.MultiBlock is the root node of the “tree” and is index 0. This allows you to access individual blocks or the entire composite dataset itself in the case of multiple nested composite datasets.

>>> import pyvista as pv
>>> dataset = pv.MultiBlock(
...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
... )
>>> pl = pv.Plotter()
>>> actor, mapper = pl.add_composite(dataset)
>>> mapper.block_attr[1].color = 'b'
>>> mapper.block_attr[1].opacity = 0.5
>>> mapper.block_attr[2].color = 'r'
>>> pl.show()
add_cursor(bounds=(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0), focal_point=(0.0, 0.0, 0.0), color=None)#

Add a cursor of a PyVista or VTK dataset to the scene.

Parameters:
  • bounds (sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)) –

    Specify the bounds in the format of:

    • (xmin, xmax, ymin, ymax, zmin, zmax)

  • focal_point (sequence[float], default: (0.0, 0.0, 0.0)) – The focal point of the cursor.

  • color (ColorLike, optional) –

    Either a string, RGB sequence, or hex color string. For one of the following.

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

Returns:

vtk.vtkActor – VTK actor of the 2D cursor.

Examples

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere)
>>> _ = plotter.add_cursor()
>>> plotter.show()
add_floor(face='-z', i_resolution=10, j_resolution=10, color=None, line_width=None, opacity=1.0, show_edges=False, lighting=False, edge_color=None, reset_camera=None, pad=0.0, offset=0.0, pickable=False, store_floor_kwargs=True)#

Show a floor mesh.

This generates planes at the boundaries of the scene to behave like floors or walls.

Parameters:
  • face (str, default: "-z") – The face at which to place the plane. Options are ('-z', '-y', '-x', '+z', '+y', and '+z'). Where the -/+ sign indicates on which side of the axis the plane will lie. For example, '-z' would generate a floor on the XY-plane and the bottom of the scene (minimum z).

  • i_resolution (int, default: 10) – Number of points on the plane in the i direction.

  • j_resolution (int, default: 10) – Number of points on the plane in the j direction.

  • color (ColorLike, optional) – Color of all labels and axis titles. Default gray. Either a string, rgb list, or hex color string.

  • line_width (float, default: False) – Thickness of the edges. Only if show_edges is True.

  • opacity (float, default: 1.0) – The opacity of the generated surface.

  • show_edges (bool, default: False) – Flag on whether to show the mesh edges for tiling.

  • line_width – Thickness of lines. Only valid for wireframe and surface representations.

  • lighting (bool, default: False) – Enable or disable view direction lighting.

  • edge_color (ColorLike, optional) – Color of the edges of the mesh.

  • reset_camera (bool, optional) – Resets the camera when True after adding the floor.

  • pad (float, default: 0.0) – Percentage padding between 0 and 1.

  • offset (float, default: 0.0) – Percentage offset along plane normal.

  • pickable (bool, default: false) – Make this floor actor pickable in the renderer.

  • store_floor_kwargs (bool, default: True) – Stores the keyword arguments used when adding this floor. Useful when updating the bounds and regenerating the floor.

Returns:

vtk.vtkActor – VTK actor of the floor.

Examples

Add a floor below a sphere and plot it.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.add_floor()
>>> pl.show()
add_key_event(key, callback)#

Add a function to callback when the given key is pressed.

These are non-unique - thus a key could map to many callback functions. The callback function must not have any arguments.

Parameters:
  • key (str) – The key to trigger the event.

  • callback (callable) – A callable that takes no arguments (keyword arguments are allowed).

add_legend(labels=None, bcolor=None, border=False, size=(0.2, 0.2), name=None, loc='upper right', face=None, font_family=None, background_opacity=1.0)#

Add a legend to render window.

Entries must be a list containing one string and color entry for each item.

Parameters:
  • labels (list, optional) –

    When set to None, uses existing labels as specified by

    • add_mesh

    • add_lines

    • add_points

    List containing one entry for each item to be added to the legend. Each entry can contain one of the following:

    • Two strings ([label, color]), where label is the name of the item to add, and color is the color of the label to add.

    • Three strings ([label, color, face]) where label is the name of the item to add, color is the color of the label to add, and face is a string which defines the face (i.e. circle, triangle, box, etc.). face could be also "none" (no face shown for the entry), or a pyvista.PolyData.

    • A dict with the key label. Optionally you can add the keys color and face. The values of these keys can be strings. For the face key, it can be also a pyvista.PolyData.

  • bcolor (ColorLike, default: (0.5, 0.5, 0.5)) – Background color, either a three item 0 to 1 RGB color list, or a matplotlib color string (e.g. 'w' or 'white' for a white color). If None, legend background is disabled.

  • border (bool, default: False) – Controls if there will be a border around the legend. Default False.

  • size (sequence[float], default: (0.2, 0.2)) – Two float sequence, each float between 0 and 1. For example (0.1, 0.1) would make the legend 10% the size of the entire figure window.

  • name (str, optional) – The name for the added 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.

  • loc (str, default: "upper right") –

    Location string. One of the following:

    • 'upper right'

    • 'upper left'

    • 'lower left'

    • 'lower right'

    • 'center left'

    • 'center right'

    • 'lower center'

    • 'upper center'

    • 'center'

  • face (str | pyvista.PolyData, optional) –

    Face shape of legend face. Defaults to a triangle for most meshes, with the exception of glyphs where the glyph is shown (e.g. arrows).

    You may set it to one of the following:

    • None: "none"

    • Line: "-" or "line"

    • Triangle: "^" or 'triangle'

    • Circle: "o" or 'circle'

    • Rectangle: "r" or 'rectangle'

    • Custom: pyvista.PolyData

    Passing "none" removes the legend face. A custom face can be created using pyvista.PolyData. This will be rendered from the XY plane.

  • font_family (str, optional) – Font family. Must be either 'courier', 'times', or 'arial'. Defaults to pyvista.global_theme.font.family.

  • background_opacity (float, default: 1.0) – Set background opacity.

Returns:

vtk.vtkLegendBoxActor – Actor for the legend.

Examples

Create a legend by labeling the meshes when using add_mesh

>>> import pyvista as pv
>>> from pyvista import examples
>>> sphere = pv.Sphere(center=(0, 0, 1))
>>> cube = pv.Cube()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
...     sphere, 'grey', smooth_shading=True, label='Sphere'
... )
>>> _ = plotter.add_mesh(cube, 'r', label='Cube')
>>> _ = plotter.add_legend(bcolor='w', face=None)
>>> plotter.show()

Alternatively provide labels in the plotter.

>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere, 'grey', smooth_shading=True)
>>> _ = plotter.add_mesh(cube, 'r')
>>> legend_entries = []
>>> legend_entries.append(['My Mesh', 'w'])
>>> legend_entries.append(['My Other Mesh', 'k'])
>>> _ = plotter.add_legend(legend_entries)
>>> plotter.show()
add_legend_scale(corner_offset_factor=2.0, bottom_border_offset=30, top_border_offset=30, left_border_offset=30, right_border_offset=30, bottom_axis_visibility=True, top_axis_visibility=True, left_axis_visibility=True, right_axis_visibility=True, legend_visibility=True, xy_label_mode=False, render=True, color=None, font_size_factor=0.6, label_size_factor=1.0, label_format=None, number_minor_ticks=0, tick_length=5, minor_tick_length=3, show_ticks=True, tick_label_offset=2)#

Annotate the render window with scale and distance information.

Its basic goal is to provide an indication of the scale of the scene. Four axes surrounding the render window indicate (in a variety of ways) the scale of what the camera is viewing. An option also exists for displaying a scale legend.

Parameters:
  • corner_offset_factor (float, default: 2.0) – The corner offset value.

  • bottom_border_offset (int, default: 30) – Bottom border offset. Recommended value 50.

  • top_border_offset (int, default: 30) – Top border offset. Recommended value 50.

  • left_border_offset (int, default: 30) – Left border offset. Recommended value 100.

  • right_border_offset (int, default: 30) – Right border offset. Recommended value 100.

  • bottom_axis_visibility (bool, default: True) – Whether the bottom axis is visible.

  • top_axis_visibility (bool, default: True) – Whether the top axis is visible.

  • left_axis_visibility (bool, default: True) – Whether the left axis is visible.

  • right_axis_visibility (bool, default: True) – Whether the right axis is visible.

  • legend_visibility (bool, default: True) – Whether the legend scale is visible.

  • xy_label_mode (bool, default: False) – The axes can be programmed either to display distance scales or x-y coordinate values. By default, the scales display a distance. However, if you know that the view is down the z-axis, the scales can be programmed to display x-y coordinate values.

  • render (bool, default: True) – Whether to render when the actor is added.

  • color (ColorLike, optional) –

    Either a string, rgb list, or hex color string for tick text and tick line colors.

    Warning

    The axis labels tend to be either white or black.

  • font_size_factor (float, default: 0.6) – Factor to scale font size overall.

  • label_size_factor (float, default: 1.0) – Factor to scale label size relative to title size.

  • label_format (str, optional) – A printf style format for labels, e.g. '%E'. See old-string-formatting.

  • number_minor_ticks (int, default: 0) – Number of minor ticks between major ticks.

  • tick_length (int, default: 5) – Length of ticks in pixels.

  • minor_tick_length (int, default: 3) – Length of minor ticks in pixels.

  • show_ticks (bool, default: True) – Whether to show the ticks.

  • tick_label_offset (int, default: 2) – Offset between tick and label in pixels.

Returns:

vtk.vtkActor – The actor for the added vtkLegendScaleActor.

Warning

Please be aware that the axes and scale values are subject to perspective effects. The distances are computed in the focal plane of the camera. When there are large view angles (i.e., perspective projection), the computed distances may provide users the wrong sense of scale. These effects are not present when parallel projection is enabled.

Examples

>>> import pyvista as pv
>>> cone = pv.Cone(height=2.0, radius=0.5)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(cone)
>>> _ = pl.add_legend_scale()
>>> pl.show()
add_light(light, only_active=False)#

Add a Light to the scene.

Parameters:
  • light (Light or vtkLight) – The light to be added.

  • only_active (bool, default: False) – If True, only add the light to the active renderer. The default is that every renderer adds the light. To add the light to an arbitrary renderer, see pyvista.Renderer.add_light().

Examples

Create a plotter that we initialize with no lights, and add a cube and a single headlight to it.

>>> import pyvista as pv
>>> plotter = pv.Plotter(lighting='none')
>>> _ = plotter.add_mesh(pv.Cube())
>>> light = pv.Light(color='cyan', light_type='headlight')
>>> plotter.add_light(light)
>>> plotter.show()
add_line_widget(callback, bounds=None, factor=1.25, resolution=100, color=None, use_vertices=False, pass_widget=False, interaction_event=45)#

Add a line widget to the scene.

This is useless without a callback function. You can pass a callable function that takes a single argument, the PolyData line output from this widget, and performs a task with that line.

Parameters:
  • callback (callable) – The method called every time the line is updated. This has two options: Take a single argument, the PolyData line (default) or if use_vertices=True, then it can take two arguments of the coordinates of the line’s end points.

  • bounds (tuple(float), optional) – Length 6 tuple of the bounding box where the widget is placed.

  • factor (float, optional) – An inflation factor to expand on the bounds when placing.

  • resolution (int, optional) – The number of points in the line created.

  • color (ColorLike, optional) – Either a string, rgb sequence, or hex color string.

  • use_vertices (bool, optional) – Changes the arguments of the callback method to take the end points of the line instead of a PolyData object.

  • pass_widget (bool, default: False) – If True, the widget will be passed as the last argument of the callback.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

Returns:

vtk.vtkLineWidget – Created line widget.

Examples

Shows an interactive line widget to move the sliced object like in add_mesh_slice function.

>>> import pyvista as pv
>>> from pyvista import examples
>>> import numpy as np
>>> model = examples.load_channels()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(model, opacity=0.4)
>>> def move_center(pointa, pointb):
...     center = (np.array(pointa) + np.array(pointb)) / 2
...     normal = np.array(pointa) - np.array(pointb)
...     single_slc = model.slice(normal=normal, origin=center)
...
...     _ = pl.add_mesh(single_slc, name="slc")
...
>>> _ = pl.add_line_widget(callback=move_center, use_vertices=True)
>>> pl.show()
add_lines(lines, color='w', width=5, label=None, name=None, connected=False)#

Add lines to the plotting object.

Parameters:
  • lines (np.ndarray) – Points representing line segments. For example, two line segments would be represented as np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]]).

  • color (ColorLike, default: 'w') –

    Either a string, rgb list, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • width (float, default: 5) – Thickness of lines.

  • label (str, default: None) – String label to use when adding a legend to the scene with pyvista.Plotter.add_legend().

  • name (str, default: None) – The name for the added 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.

  • connected (bool, default: False) – Treat lines as points representing a series of connected lines. For example, two connected line segments would be represented as np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]]). If False, an even number of points must be passed to lines, and the lines need not be connected.

Returns:

vtk.vtkActor – Lines actor.

Examples

Plot two lines.

>>> import numpy as np
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
>>> actor = pl.add_lines(points, color='purple', width=3)
>>> pl.camera_position = 'xy'
>>> pl.show()

Adding lines with connected=True will add a series of connected line segments.

>>> pl = pv.Plotter()
>>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
>>> actor = pl.add_lines(
...     points, color='purple', width=3, connected=True
... )
>>> pl.camera_position = 'xy'
>>> pl.show()
add_logo_widget(logo: pyvista.ImageData | str | pathlib.Path | None = None, position: tuple[float, float] | Sequence[float] | NumpyArray[float] = (0.75, 0.8), size: tuple[float, float] | Sequence[float] | NumpyArray[float] = (0.2, 0.2), opacity: float = 1.0)#

Add a logo widget to the top of the viewport.

If no logo is passed, the PyVista logo will be used.

Parameters:
  • logo (pyvista.ImageData or pathlib.Path, optional) – The logo to display. If a pathlike is passed, it is assumed to be a file path to an image.

  • position (tuple(float), optional) – The position of the logo in the viewport. The first value is the horizontal position and the second value is the vertical position. Both values must be between 0 and 1.

  • size (tuple(float), optional) – The size of the logo in the viewport. The first value is the horizontal size and the second value is the vertical size. Both values must be between 0 and 1.

  • opacity (float, optional) – The opacity of the logo. Must be between 0 and 1.

Returns:

vtkLogoWidget – The logo widget.

Examples

Add a logo widget to the scene.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_logo_widget()
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.show()
add_measurement_widget(callback=None, color=None)#

Interactively measure distance with a distance widget.

Creates an overlay documenting the selected line and total distance between two mouse left-click interactions.

The measurement overlay stays on the rendering until the widget is deleted. Only one measurement can be added by each widget instance.

Parameters:
  • callback (Callable[[tuple[float, float, float], [tuple[float, float, float], int], float]) – The method called every time the widget calculates a distance measurement. This callback receives the start point and end point as cartesian coordinate tuples and the calculated distance between the two points.

  • color (ColorLike, optional) – The color of the measurement widget.

Returns:

vtk.vtkDistanceWidget – The newly created distance widget.

add_mesh(mesh, color=None, style=None, scalars=None, clim=None, show_edges=None, edge_color=None, point_size=None, line_width=None, opacity=None, flip_scalars=False, lighting=None, n_colors=256, interpolate_before_map=None, 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, split_sharp_edges=None, ambient=None, diffuse=None, specular=None, specular_power=None, 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=None, metallic=None, roughness=None, render=True, user_matrix=None, component=None, emissive=None, copy_mesh=False, backface_params=None, show_vertices=None, edge_opacity=None, **kwargs)#

Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene.

This method is using a mesh representation to view the surfaces and/or geometry of datasets. For volume rendering, see pyvista.Plotter.add_volume().

To see the what most of the following parameters look like in action, please refer to pyvista.Property.

Parameters:
  • mesh (pyvista.DataSet or pyvista.MultiBlock or vtk.vtkAlgorithm) – Any PyVista or VTK mesh is supported. Also, any dataset that pyvista.wrap() can handle including NumPy arrays of XYZ points. Plotting also supports VTK algorithm objects (vtk.vtkAlgorithm and vtk.vtkAlgorithmOutput). When passing an algorithm, the rendering pipeline will be connected to the passed algorithm to dynamically update the scene.

  • color (ColorLike, optional) –

    Use to make the entire mesh have a single solid color. Either a string, RGB list, or hex color string. For example: color='white', color='w', color=[1.0, 1.0, 1.0], or color='#FFFFFF'. Color will be overridden if scalars are specified.

    Defaults to pyvista.global_theme.color.

  • style (str, optional) – Visualization style of the mesh. One of the following: style='surface', style='wireframe', style='points', style='points_gaussian'. Defaults to 'surface'. Note that 'wireframe' only shows a wireframe of the outer geometry. 'points_gaussian' can be modified with the emissive, render_points_as_spheres options.

  • scalars (str | numpy.ndarray, optional) – Scalars used to “color” the mesh. Accepts a string name of an array that is present on the mesh or 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.

  • clim (sequence[float], optional) – Two item color bar range for scalars. Defaults to minimum and maximum of scalars array. Example: [-1, 2]. rng is also an accepted alias for this.

  • show_edges (bool, optional) – Shows the edges of a mesh. Does not apply to a wireframe representation.

  • edge_color (ColorLike, optional) –

    The solid color to give the edges when show_edges=True. Either a string, RGB list, or hex color string.

    Defaults to pyvista.global_theme.edge_color.

  • point_size (float, optional) – Point size of any nodes in the dataset plotted. Also applicable when style=’points’. Default 5.0.

  • line_width (float, optional) – Thickness of lines. Only valid for wireframe and surface representations. Default None.

  • opacity (float | str| array_like) – Opacity of the mesh. If a single float value is given, it will be the global opacity of the mesh and uniformly applied everywhere - should be between 0 and 1. A string can also be specified to map the scalars range to a predefined opacity transfer function (options include: 'linear', 'linear_r', 'geom', 'geom_r'). A string could also be used to map a scalars array from the mesh to the opacity (must have same number of elements as the scalars argument). Or you can pass a custom made transfer function that is an array either n_colors in length or shorter.

  • flip_scalars (bool, default: False) – Flip direction of cmap. Most colormaps allow *_r suffix to do this as well.

  • lighting (bool, optional) – Enable or disable view direction lighting. Default False.

  • n_colors (int, optional) – Number of colors to use when displaying scalars. Defaults to 256. The scalar bar will also have this many colors.

  • interpolate_before_map (bool, optional) – Enabling makes for a smoother scalars display. Default is True. When False, OpenGL will interpolate the mapped colors which can result is showing colors that are not present in the color map.

  • cmap (str | list | pyvista.LookupTable, default: pyvista.plotting.themes.Theme.cmap) –

    If a string, this is the name of the matplotlib colormap to use when mapping the scalars. See available Matplotlib colormaps. Only applicable for when displaying scalars. colormap is also an accepted alias for this. If colorcet or cmocean are installed, their colormaps can be specified by name.

    You can also specify a list of colors to override an existing colormap with a custom one. For example, to create a three color colormap you might specify ['green', 'red', 'blue'].

    This parameter also accepts a pyvista.LookupTable. If this is set, all parameters controlling the color map like n_colors will be ignored.

  • label (str, optional) – String label to use when adding a legend to the scene with pyvista.Plotter.add_legend().

  • reset_camera (bool, optional) – Reset the camera after adding this mesh to the scene. The default setting is None, where the camera is only reset if this plotter has already been shown. If False, the camera is not reset regardless of the state of the Plotter. When True, the camera is always reset.

  • scalar_bar_args (dict, optional) – Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see pyvista.Plotter.add_scalar_bar().

  • show_scalar_bar (bool, optional) – If False, a scalar bar will not be added to the scene.

  • multi_colors (bool | str | cycler.Cycler | sequence[ColorLike], default: False) –

    If a pyvista.MultiBlock dataset is given this will color each block by a solid color using a custom cycler.

    If True, the default ‘matplotlib’ color cycler is used.

    See set_color_cycler for usage of custom color cycles.

  • 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 (pyvista.Texture or np.ndarray, optional) – A texture to apply if the input mesh has texture coordinates. This will not work with MultiBlock datasets.

  • render_points_as_spheres (bool, optional) – Render points as spheres rather than dots.

  • render_lines_as_tubes (bool, optional) – Show lines as thick tubes rather than flat lines. Control the width with line_width.

  • smooth_shading (bool, optional) – Enable smooth shading when True using the Phong shading algorithm. When False, use flat shading. Automatically enabled when pbr=True. See shading_example.

  • split_sharp_edges (bool, optional) – Split sharp edges exceeding 30 degrees when plotting with smooth shading. Control the angle with the optional keyword argument feature_angle. By default this is False unless overridden by the global or plotter theme. Note that enabling this will create a copy of the input mesh within the plotter. See shading_example.

  • ambient (float, optional) – When lighting is enabled, this is the amount of light in the range of 0 to 1 (default 0.0) that reaches the actor when not directed at the light source emitted from the viewer.

  • diffuse (float, optional) – The diffuse lighting coefficient. Default 1.0.

  • specular (float, optional) – The specular lighting coefficient. Default 0.0.

  • specular_power (float, optional) – The specular power. Between 0.0 and 128.0.

  • nan_color (ColorLike, optional) – 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.

  • culling (str, optional) – Does not render faces that are culled. Options are 'front' or 'back'. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Defaults to False.

  • rgb (bool, optional) – If an 2 dimensional array is passed as the scalars, plot those values as RGB(A) colors. rgba is also an accepted alias for this. Opacity (the A) is optional. If a scalars array ending with "_rgba" is passed, the default becomes True. This can be overridden by setting this parameter to False.

  • categories (bool, optional) – If set to True, then the number of unique values in the scalar array will be used as the n_colors argument.

  • silhouette (dict, bool, optional) –

    If set to True, plot a silhouette highlight for the mesh. This feature is only available for a triangulated PolyData. As a dict, it contains the properties of the silhouette to display:

    • color: ColorLike, color of the silhouette

    • line_width: float, edge width

    • opacity: float between 0 and 1, edge transparency

    • feature_angle: If a float, display sharp edges exceeding that angle in degrees.

    • decimate: float between 0 and 1, level of decimation

  • use_transparency (bool, optional) – Invert the opacity mappings and make the values correspond to transparency.

  • below_color (ColorLike, optional) – Solid color for values below the scalars range (clim). This will automatically set the scalar bar below_label to 'below'.

  • above_color (ColorLike, optional) – Solid color for values below the scalars range (clim). This will automatically set the scalar bar above_label to 'above'.

  • annotations (dict, optional) – Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the string annotations.

  • pickable (bool, optional) – Set whether this actor is pickable.

  • preference (str, default: "point") – When mesh.n_points == mesh.n_cells and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default 'point', causes the scalars will be associated with the mesh points. Can be either 'point' or 'cell'.

  • log_scale (bool, default: False) – Use log scale when mapping data to colors. Scalars less than zero are mapped to the smallest representable positive float.

  • pbr (bool, optional) – Enable physics based rendering (PBR) if the mesh is PolyData. Use the color argument to set the base color.

  • metallic (float, optional) – Usually this value is either 0 or 1 for a real material but any value in between is valid. This parameter is only used by PBR interpolation.

  • roughness (float, optional) – This value has to be between 0 (glossy) and 1 (rough). A glossy material has reflections and a high specular part. This parameter is only used by PBR interpolation.

  • render (bool, default: True) – Force a render when True.

  • user_matrix (np.ndarray | vtk.vtkMatrix4x4, default: np.eye(4)) – Matrix passed to the Actor class before rendering. This affects the actor/rendering only, not the input volume itself. The user matrix is the last transformation applied to the actor before rendering. Defaults to the identity matrix.

  • component (int, optional) – Set component of vector valued scalars to plot. Must be nonnegative, if supplied. If None, the magnitude of the vector is plotted.

  • emissive (bool, optional) – Treat the points/splats as emissive light sources. Only valid for style='points_gaussian' representation.

  • copy_mesh (bool, default: False) – If True, a copy of the mesh will be made before adding it to the plotter. This is useful if you would like to add the same mesh to a plotter multiple times and display different scalars. Setting copy_mesh to False is necessary if you would like to update the mesh after adding it to the plotter and have these updates rendered, e.g. by changing the active scalars or through an interactive widget. This should only be set to True with caution. Defaults to False. This is ignored if the input is a vtkAlgorithm subclass.

  • backface_params (dict | pyvista.Property, optional) – A pyvista.Property or a dict of parameters to use for backface rendering. This is useful for instance when the inside of oriented surfaces has a different color than the outside. When a pyvista.Property, this is directly used for backface rendering. When a dict, valid keys are pyvista.Property attributes, and values are corresponding values to use for the given property. Omitted keys (or the default of backface_params=None) default to the corresponding frontface properties.

  • show_vertices (bool, optional) –

    When style is not 'points', render the external surface vertices. The following optional keyword arguments may be used to control the style of the vertices:

    • vertex_color - The color of the vertices

    • vertex_style - Change style to 'points_gaussian'

    • vertex_opacity - Control the opacity of the vertices

  • edge_opacity (float, optional) –

    Edge opacity of the mesh. A single float value that will be applied globally edge opacity of the mesh and uniformly applied everywhere - should be between 0 and 1.

    Note

    edge_opacity uses SetEdgeOpacity as the underlying method which requires VTK version 9.3 or higher. If SetEdgeOpacity is not available, edge_opacity is set to 1.

  • **kwargs (dict, optional) – Optional keyword arguments.

Returns:

pyvista.plotting.actor.Actor – Actor of the mesh.

Examples

Add a sphere to the plotter and show it with a custom scalar bar title.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere['Data'] = sphere.points[:, 2]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
...     sphere, scalar_bar_args={'title': 'Z Position'}
... )
>>> plotter.show()

Plot using RGB on a single cell. Note that since the number of points and the number of cells are identical, we have to pass preference='cell'.

>>> import pyvista as pv
>>> import numpy as np
>>> vertices = np.array(
...     [
...         [0, 0, 0],
...         [1, 0, 0],
...         [0.5, 0.667, 0],
...         [0.5, 0.33, 0.667],
...     ]
... )
>>> faces = np.hstack(
...     [[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]]
... )
>>> mesh = pv.PolyData(vertices, faces)
>>> mesh.cell_data['colors'] = [
...     [255, 255, 255],
...     [0, 255, 0],
...     [0, 0, 255],
...     [255, 0, 0],
... ]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
...     mesh,
...     scalars='colors',
...     lighting=False,
...     rgb=True,
...     preference='cell',
... )
>>> plotter.camera_position = 'xy'
>>> plotter.show()

Note how this varies from preference=='point'. This is because each point is now being individually colored, versus in preference=='point', each cell face is individually colored.

>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
...     mesh,
...     scalars='colors',
...     lighting=False,
...     rgb=True,
...     preference='point',
... )
>>> plotter.camera_position = 'xy'
>>> plotter.show()

Plot a plane with a constant color and vary its opacity by point.

>>> plane = pv.Plane()
>>> plane.plot(
...     color='b',
...     opacity=np.linspace(0, 1, plane.n_points),
...     show_edges=True,
... )

Plot the points of a sphere with Gaussian smoothing while coloring by z position.

>>> mesh = pv.Sphere()
>>> mesh.plot(
...     scalars=mesh.points[:, 2],
...     style='points_gaussian',
...     opacity=0.5,
...     point_size=10,
...     render_points_as_spheres=False,
...     show_scalar_bar=False,
... )

Plot spheres using points_gaussian style and scale them by radius.

>>> N_SPHERES = 1_000_000
>>> rng = np.random.default_rng(seed=0)
>>> pos = rng.random((N_SPHERES, 3))
>>> rad = rng.random(N_SPHERES) * 0.01
>>> pdata = pv.PolyData(pos)
>>> pdata['radius'] = rad
>>> pdata.plot(
...     style='points_gaussian',
...     emissive=False,
...     render_points_as_spheres=True,
... )
add_mesh_clip_box(mesh, invert=False, rotation_enabled=True, widget_color=None, outline_translation=True, merge_points=True, crinkle=False, interaction_event='end', **kwargs)#

Clip a mesh using a box widget.

Add a mesh to the scene with a box widget that is used to clip the mesh interactively.

The clipped mesh is saved to the .box_clipped_meshes attribute on the plotter.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and clip or algorithm that produces said mesh.

  • invert (bool, optional) – Flag on whether to flip/invert the clip.

  • rotation_enabled (bool, optional) – If False, the box widget cannot be rotated and is strictly orthogonal to the cartesian axes.

  • widget_color (ColorLike, optional) –

    Color of the widget. Either a string, RGB sequence, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • outline_translation (bool, optional) – If False, the plane widget cannot be translated and is strictly placed at the given bounds.

  • merge_points (bool, optional) – If True (default), coinciding points of independently defined mesh elements will be merged.

  • crinkle (bool, optional) – Crinkle the clip by extracting the entire cells along the clip.

  • interaction_event (vtk.vtkCommand.EventIds, str, optional) –

    The VTK interaction event to use for triggering the callback. Accepts either the strings 'start', 'end', 'always' or a vtk.vtkCommand.EventIds.

    Changed in version 0.38.0: Changed from event_type to interaction_event and now accepts either strings and vtk.vtkCommand.EventIds.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_mesh() to control how the mesh is displayed.

Returns:

vtk.vtkActor – VTK actor of the mesh.

Examples

Shows an interactive clip box.

>>> import pyvista as pv
>>> mesh = pv.ParametricConicSpiral()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh_clip_box(mesh, color='white')
>>> pl.show()

For a full example see box_widget_example.

add_mesh_clip_plane(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', origin=None, outline_opacity=None, **kwargs)#

Clip a mesh using a plane widget.

Add a mesh to the scene with a plane widget that is used to clip the mesh interactively.

The clipped mesh is saved to the .plane_clipped_meshes attribute on the plotter.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and clip or algorithm that produces said mesh.

  • normal (str or tuple(float), optional) – The starting normal vector of the plane.

  • invert (bool, optional) – Flag on whether to flip/invert the clip.

  • widget_color (ColorLike, optional) – Either a string, RGB list, or hex color string.

  • value (float, optional) – Set the clipping value along the normal direction. The default value is 0.0.

  • assign_to_axis (str or int, optional) – Assign the normal of the plane to be parallel with a given axis. Options are (0, 'x'), (1, 'y'), or (2, 'z').

  • tubing (bool, optional) – When using an implicit plane wiget, this controls whether or not tubing is shown around the plane’s boundaries.

  • origin_translation (bool, optional) – If False, the plane widget cannot be translated by its origin and is strictly placed at the given origin. Only valid when using an implicit plane.

  • outline_translation (bool, optional) – If False, the box widget cannot be translated and is strictly placed at the given bounds.

  • implicit (bool, optional) – When True, a vtkImplicitPlaneWidget is used and when False, a vtkPlaneWidget is used.

  • normal_rotation (bool, optional) – Set the opacity of the normal vector arrow to 0 such that it is effectively disabled. This prevents the user from rotating the normal. This is forced to False when assign_to_axis is set.

  • crinkle (bool, optional) – Crinkle the clip by extracting the entire cells along the clip.

  • interaction_event (vtk.vtkCommand.EventIds, str, optional) –

    The VTK interaction event to use for triggering the callback. Accepts either the strings 'start', 'end', 'always' or a vtk.vtkCommand.EventIds.

    Changed in version 0.38.0: Now accepts either strings or vtk.vtkCommand.EventIds.

  • origin (tuple(float), optional) – The starting coordinate of the center of the plane.

  • outline_opacity (bool or float, optional) –

    Set the visible of outline. Only valid when using an implicit plane. Either a bool or float.

    Added in version 0.44.0.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_mesh() to control how the mesh is displayed.

Returns:

vtk.vtkActor – VTK actor of the mesh.

Examples

Shows an interactive plane used to clip the mesh and store it.

>>> import pyvista as pv
>>> from pyvista import examples
>>> vol = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh_clip_plane(vol, normal=[0, -1, 0])
>>> pl.show(cpos=[-2.1, 0.6, 1.5])
>>> pl.plane_clipped_meshes  

For a full example see plane_widget_example.

add_mesh_isovalue(mesh, scalars=None, compute_normals=False, compute_gradients=False, compute_scalars=True, preference='point', title=None, pointa=(0.4, 0.9), pointb=(0.9, 0.9), widget_color=None, **kwargs)#

Create a contour of a mesh with a slider.

Add a mesh to the scene with a slider widget that is used to contour at an isovalue of the point data on the mesh interactively.

The isovalue mesh is saved to the .isovalue_meshes attribute on the plotter.

Warning

This will not work with pyvista.PointSet as creating an isovalue is a dimension reducing operation on the geometry and point clouds are zero dimensional. This will similarly fail for point clouds in pyvista.PolyData.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and contour or algorithm that produces said mesh.

  • scalars (str, optional) – The string name of the scalars on the mesh to contour and display.

  • compute_normals (bool, optional) – Enable or disable the computation of normals. If the output data will be processed by filters that modify topology or geometry, it may be wise to disable computing normals.

  • compute_gradients (bool, optional) – Enable or disable the computation of gradients. If the output data will be processed by filters that modify topology or geometry, it may be wise to disable computing gradients.

  • compute_scalars (bool, optional) – Enable or disable the computation of scalars.

  • preference (str, optional) – When mesh.n_points == mesh.n_cells and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default 'point', causes the scalars will be associated with the mesh points. Can be either 'point' or 'cell'.

  • title (str, optional) – The string label of the slider widget.

  • pointa (sequence, optional) – The relative coordinates of the left point of the slider on the display port.

  • pointb (sequence) – The relative coordinates of the right point of the slider on the display port.

  • widget_color (ColorLike, optional) –

    Color of the widget. Either a string, RGB sequence, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_mesh() to control how the mesh is displayed.

Returns:

vtk.vtkActor – VTK actor of the mesh.

Examples

Shows an interactive slider controlling the altitude of the contours.

>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter()
>>> mesh = examples.load_random_hills()
>>> _ = pl.add_mesh(mesh, opacity=0.4)
>>> _ = pl.add_mesh_isovalue(mesh)
>>> pl.show()
add_mesh_slice(mesh, normal='x', generate_triangles=False, widget_color=None, assign_to_axis=None, tubing=False, origin_translation=True, outline_translation=False, implicit=True, normal_rotation=True, interaction_event=45, origin=None, outline_opacity=None, **kwargs)#

Slice a mesh using a plane widget.

Add a mesh to the scene with a plane widget that is used to slice the mesh interactively.

The sliced mesh is saved to the .plane_sliced_meshes attribute on the plotter.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and slice or algorithm that produces said mesh.

  • normal (str or tuple(float), optional) – The starting normal vector of the plane.

  • generate_triangles (bool, optional) – If this is enabled (False by default), the output will be triangles otherwise, the output will be the intersection polygons.

  • widget_color (ColorLike, optional) – Either a string, RGB sequence, or hex color string. Defaults to 'white'.

  • assign_to_axis (str or int, optional) – Assign the normal of the plane to be parallel with a given axis: options are (0, ‘x’), (1, ‘y’), or (2, ‘z’).

  • tubing (bool, optional) – When using an implicit plane wiget, this controls whether or not tubing is shown around the plane’s boundaries.

  • origin_translation (bool, optional) – If False, the plane widget cannot be translated by its origin and is strictly placed at the given origin. Only valid when using an implicit plane.

  • outline_translation (bool, optional) – If False, the box widget cannot be translated and is strictly placed at the given bounds.

  • implicit (bool, optional) – When True, a vtkImplicitPlaneWidget is used and when False, a vtkPlaneWidget is used.

  • normal_rotation (bool, optional) – Set the opacity of the normal vector arrow to 0 such that it is effectively disabled. This prevents the user from rotating the normal. This is forced to False when assign_to_axis is set.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

  • origin (tuple(float), optional) – The starting coordinate of the center of the plane.

  • outline_opacity (bool or float, optional) –

    Set the visible of outline. Only valid when using an implicit plane. Either a bool or float.

    Added in version 0.44.0.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_mesh() to control how the mesh is displayed.

Returns:

vtk.vtkActor – VTK actor of the mesh.

Examples

Shows an interactive plane used specifically for slicing.

>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter()
>>> mesh = examples.load_channels()
>>> _ = pl.add_mesh(mesh.outline())
>>> _ = pl.add_mesh_slice(mesh, normal=[1, 0, 0.3])
>>> pl.show()

For a full example see plane_widget_example.

add_mesh_slice_orthogonal(mesh, generate_triangles=False, widget_color=None, tubing=False, interaction_event=45, **kwargs)#

Slice a mesh with three interactive planes.

Adds three interactive plane slicing widgets for orthogonal slicing along each cartesian axis.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and threshold or algorithm that produces said mesh.

  • generate_triangles (bool, optional) – If this is enabled (False by default), the output will be triangles otherwise, the output will be the intersection polygons.

  • widget_color (ColorLike, optional) –

    Color of the widget. Either a string, RGB sequence, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • tubing (bool, optional) – When using an implicit plane wiget, this controls whether or not tubing is shown around the plane’s boundaries.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_mesh() to control how the mesh is displayed.

Returns:

list – List of vtk.vtkActor(s).

Examples

Shows an interactive plane sliced along each cartesian axis of the mesh.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> mesh = pv.Wavelet()
>>> _ = pl.add_mesh(mesh.outline())
>>> _ = pl.add_mesh_slice_orthogonal(mesh)
>>> pl.show()
add_mesh_slice_spline(mesh, generate_triangles=False, n_handles=5, resolution=25, widget_color=None, show_ribbon=False, ribbon_color='pink', ribbon_opacity=0.5, initial_points=None, closed=False, interaction_event=45, **kwargs)#

Slice a mesh with a spline widget.

Add a mesh to the scene with a spline widget that is used to slice the mesh interactively.

The sliced mesh is saved to the .spline_sliced_meshes attribute on the plotter.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and slice along the spline or algorithm that produces said mesh.

  • generate_triangles (bool, optional) – If this is enabled (False by default), the output will be triangles otherwise, the output will be the intersection polygons.

  • n_handles (int, optional) – The number of interactive spheres to control the spline’s parametric function.

  • resolution (int, optional) – The number of points to generate on the spline.

  • widget_color (ColorLike, optional) –

    Color of the widget. Either a string, RGB sequence, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • show_ribbon (bool, optional) – If True, the poly plane used for slicing will also be shown.

  • ribbon_color (ColorLike, optional) – Color of the ribbon. Either a string, RGB sequence, or hex color string.

  • ribbon_opacity (float, optional) – Opacity of ribbon. Defaults to 1.0 and must be between [0, 1].

  • initial_points (sequence, optional) – The points to initialize the widget placement. Must have same number of elements as n_handles. If the first and last point are the same, this will be a closed loop spline.

  • closed (bool, optional) – Make the spline a closed loop.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_mesh() to control how the mesh is displayed.

Returns:

vtk.vtkActor – VTK actor of the mesh.

add_mesh_threshold(mesh, scalars=None, invert=False, widget_color=None, preference='cell', title=None, pointa=(0.4, 0.9), pointb=(0.9, 0.9), continuous=False, all_scalars=False, method='upper', **kwargs)#

Apply a threshold on a mesh with a slider.

Add a mesh to the scene with a slider widget that is used to threshold the mesh interactively.

The threshold mesh is saved to the .threshold_meshes attribute on the plotter.

Parameters:
  • mesh (pyvista.DataSet or vtk.vtkAlgorithm) – The input dataset to add to the scene and threshold or algorithm that produces said mesh.

  • scalars (str, optional) – The string name of the scalars on the mesh to threshold and display.

  • invert (bool, default: False) – Invert the threshold results. That is, cells that would have been in the output with this option off are excluded, while cells that would have been excluded from the output are included.

  • widget_color (ColorLike, optional) –

    Color of the widget. Either a string, RGB sequence, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • preference (str, default: 'cell') – When mesh.n_points == mesh.n_cells and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default 'cell', causes the scalars to be associated with the mesh cells. Can be either 'point' or 'cell'.

  • title (str, optional) – The string label of the slider widget.

  • pointa (sequence, default: (0.4, 0.9)) – The relative coordinates of the left point of the slider on the display port.

  • pointb (sequence, default: (0.9, 0.9)) – The relative coordinates of the right point of the slider on the display port.

  • continuous (bool, default: False) – If this is enabled (default is False), use the continuous interval [minimum cell scalar, maximum cell scalar] to intersect the threshold bound, rather than the set of discrete scalar values from the vertices.

  • all_scalars (bool, default: False) – If using scalars from point data, all points in a cell must satisfy the threshold when this value is True. When False, any point of the cell with a scalar value satisfying the threshold criterion will extract the cell. Has no effect when using cell data.

  • method (str, default: 'upper') – Set the threshold method for single-values, defining which threshold bounds to use. If the value is a range, this parameter will be ignored, extracting data between the two values. For single values, 'lower' will extract data lower than the value. 'upper' will extract data larger than the value.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to add_mesh to control how the mesh is displayed.

Returns:

vtk.vtkActor – VTK actor of the mesh.

add_north_arrow_widget(interactive=None, color='#4169E1', opacity=1.0, line_width=2, edge_color=None, lighting=False, viewport=(0, 0, 0.1, 0.1))#

Add a geographic north arrow to the scene.

Added in version 0.44.0.

Parameters:
  • interactive (bool, optional) – Control if the orientation widget is interactive. By default uses the value from pyvista.global_theme.interactive.

  • color (ColorLike, optional) – Color of the north arrow.

  • opacity (float, optional) – Opacity of the north arrow.

  • line_width (float, optional) – Width of the north edge arrow lines.

  • edge_color (ColorLike, optional) – Color of the edges.

  • lighting (bool, optional) – Enable or disable lighting on north arrow.

  • viewport (sequence[float], default: (0, 0, 0.1, 0.1)) – Viewport (xstart, ystart, xend, yend) of the widget.

Returns:

vtk.vtkOrientationMarkerWidget – Orientation marker widget.

Examples

Use an north arrow as the orientation widget.

>>> import pyvista as pv
>>> from pyvista import examples
>>> terrain = examples.download_st_helens().warp_by_scalar()
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(terrain)
>>> widget = pl.add_north_arrow_widget()
>>> pl.enable_terrain_style(True)
>>> pl.show()
add_on_render_callback(callback, render_event=False)#

Add a method to be called post-render.

Parameters:
  • callback (callable) – The callback method to run post-render. This takes a single argument which is the plotter object.

  • render_event (bool, default: False) – If True, associate with all VTK RenderEvents. Otherwise, the callback is only handled on a successful render() from the PyVista plotter directly.

add_orientation_widget(actor, interactive=None, color=None, opacity=1.0, viewport=None)#

Use the given actor in an orientation marker widget.

Color and opacity are only valid arguments if a mesh is passed.

Parameters:
  • actor (vtk.vtkActor | pyvista.DataSet) – The mesh or actor to use as the marker.

  • interactive (bool, optional) – Control if the orientation widget is interactive. By default uses the value from pyvista.global_theme.interactive.

  • color (ColorLike, optional) – The color of the actor. This only applies if actor is a pyvista.DataSet.

  • opacity (int | float, default: 1.0) – Opacity of the marker.

  • viewport (sequence[float], optional) – Viewport (xstart, ystart, xend, yend) of the widget.

Returns:

vtk.vtkOrientationMarkerWidget – Orientation marker widget.

See also

add_axes

Add an axes orientation widget.

Examples

Use an Arrow as the orientation widget.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Cube(), show_edges=True)
>>> widget = pl.add_orientation_widget(pv.Arrow(), color='r')
>>> pl.show()
add_plane_widget(callback, normal='x', origin=None, bounds=None, factor=1.25, color=None, assign_to_axis=None, tubing=False, outline_translation=False, origin_translation=True, implicit=True, pass_widget=False, test_callback=True, normal_rotation=True, interaction_event='end', outline_opacity=None)#

Add a plane widget to the scene.

This is useless without a callback function. You can pass a callable function that takes two arguments, the normal and origin of the plane in that order output from this widget, and performs a task with that plane.

Parameters:
  • callback (callable) – The method called every time the plane is updated. Takes two arguments, the normal and origin of the plane in that order.

  • normal (str or tuple(float)) – The starting normal vector of the plane.

  • origin (tuple(float)) – The starting coordinate of the center of the plane.

  • bounds (tuple(float)) – Length 6 tuple of the bounding box where the widget is placed.

  • factor (float, optional) – An inflation factor to expand on the bounds when placing.

  • color (ColorLike, optional) – Either a string, rgb list, or hex color string.

  • assign_to_axis (str or int, optional) – Assign the normal of the plane to be parallel with a given axis: options are (0, 'x'), (1, 'y'), or (2, 'z').

  • tubing (bool, optional) – When using an implicit plane wiget, this controls whether or not tubing is shown around the plane’s boundaries.

  • outline_translation (bool, optional) – If False, the plane widget cannot be translated and is strictly placed at the given bounds. Only valid when using an implicit plane.

  • origin_translation (bool, optional) – If False, the plane widget cannot be translated by its origin and is strictly placed at the given origin. Only valid when using an implicit plane.

  • implicit (bool, optional) – When True, a vtkImplicitPlaneWidget is used and when False, a vtkPlaneWidget is used.

  • pass_widget (bool, optional) – If True, the widget will be passed as the last argument of the callback.

  • test_callback (bool, optional) – If True, run the callback function after the widget is created.

  • normal_rotation (bool, optional) – Set the opacity of the normal vector arrow to 0 such that it is effectively disabled. This prevents the user from rotating the normal. This is forced to False when assign_to_axis is set.

  • interaction_event (vtk.vtkCommand.EventIds, str, optional) –

    The VTK interaction event to use for triggering the callback. Accepts either the strings 'start', 'end', 'always' or a vtk.vtkCommand.EventIds.

    Changed in version 0.38.0: Now accepts either strings and vtk.vtkCommand.EventIds.

  • outline_opacity (bool or float, optional) –

    Set the visible of outline. Only valid when using an implicit plane. Either a bool or float.

    Added in version 0.44.0.

Returns:

vtk.vtkImplicitPlaneWidget or vtk.vtkPlaneWidget – Plane widget.

Examples

Shows an interactive plane moving along the x-axis in the random-hill example, which is used to mark the max altitude at a particular distance x.

>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.load_random_hills()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> def callback(normal, origin):
...     slc = mesh.slice(normal=normal, origin=origin)
...     origin = list(origin)
...     origin[2] = slc.bounds[5]
...     peak_plane = pv.Plane(
...         center=origin,
...         direction=[0, 0, 1],
...         i_size=20,
...         j_size=20,
...     )
...     _ = pl.add_mesh(
...         peak_plane, name="Peak", color='red', opacity=0.4
...     )
...
>>> _ = pl.add_plane_widget(callback, normal_rotation=False)
>>> pl.show()
add_point_labels(points, labels, italic=False, bold=True, font_size=None, text_color=None, font_family=None, shadow=False, show_points=True, point_color=None, point_size=None, name=None, shape_color='grey', shape='rounded_rect', fill_shape=True, margin=3, shape_opacity=1.0, pickable=False, render_points_as_spheres=False, tolerance=0.001, reset_camera=None, always_visible=False, render=True, justification_horizontal=None, justification_vertical=None, background_color=None, background_opacity=None)#

Create a point actor with one label from list labels assigned to each point.

Parameters:
  • points (sequence | pyvista.DataSet | vtk.vtkAlgorithm) – An n x 3 sequence points or pyvista.DataSet with points or mesh-producing algorithm.

  • labels (list | str) – List of labels. Must be the same length as points. If a string name is given with a pyvista.DataSet input for points, then these are fetched.

  • italic (bool, default: False) – Italicises title and bar labels.

  • bold (bool, default: True) – Bolds title and bar labels.

  • font_size (float, optional) – Sets the size of the title font.

  • text_color (ColorLike, optional) –

    Color of text. Either a string, RGB sequence, or hex color string.

    • text_color='white'

    • text_color='w'

    • text_color=[1.0, 1.0, 1.0]

    • text_color='#FFFFFF'

  • font_family (str, optional) – Font family. Must be either 'courier', 'times', or 'arial.

  • shadow (bool, default: False) – Adds a black shadow to the text.

  • show_points (bool, default: True) – Controls if points are visible.

  • point_color (ColorLike, optional) –

    Either a string, rgb list, or hex color string. One of the following.

    • point_color='white'

    • point_color='w'

    • point_color=[1.0, 1.0, 1.0]

    • point_color='#FFFFFF'

  • point_size (float, optional) – Size of points if visible.

  • name (str, optional) – The name for the added 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.

  • shape_color (ColorLike, default: "grey") – Color of shape (if visible). Either a string, rgb sequence, or hex color string.

  • shape (str, default: "rounded_rect") – The string name of the shape to use. Options are 'rect' or 'rounded_rect'. If you want no shape, pass None.

  • fill_shape (bool, default: True) – Fill the shape with the shape_color. Outlines if False.

  • margin (int, default: 3) – The size of the margin on the label background shape.

  • shape_opacity (float, default: 1.0) – The opacity of the shape in the range of [0, 1].

  • pickable (bool, default: False) – Set whether this actor is pickable.

  • render_points_as_spheres (bool, default: False) – Render points as spheres rather than dots.

  • tolerance (float, default: 0.001) – A tolerance to use to determine whether a point label is visible. A tolerance is usually required because the conversion from world space to display space during rendering introduces numerical round-off.

  • reset_camera (bool, optional) – Reset the camera after adding the points to the scene.

  • always_visible (bool, default: False) – Skip adding the visibility filter.

  • render (bool, default: True) – Force a render when True.

  • justification_horizontal (str, optional) –

    Text’s horizontal justification. Should be either “left”, “center” or “right”.

    Warning

    If the justification is not default, the shape will be out of alignment with the label. If you use other than default, Please use the background color. See: pyvista/pyvista#5407

  • justification_vertical (str, optional) –

    Text’s vertical justification. Should be either “bottom”, “center” or “top”.

    Warning

    If the justification is not default, the shape will be out of alignment with the label. If you use other than default, Please use the background color. See: pyvista/pyvista#5407

  • background_color (pyvista.Color, optional) – Background color of text’s property.

  • background_opacity (pyvista.Color, optional) – Background opacity of text’s property.

Returns:

vtk.vtkActor2D – VTK label actor. Can be used to change properties of the labels.

Examples

>>> import numpy as np
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> points = np.array(
...     [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 0.0, 0.0]]
... )
>>> labels = ['Point A', 'Point B', 'Point C']
>>> actor = pl.add_point_labels(
...     points,
...     labels,
...     italic=True,
...     font_size=20,
...     point_color='red',
...     point_size=20,
...     render_points_as_spheres=True,
...     always_visible=True,
...     shadow=True,
... )
>>> pl.camera_position = 'xy'
>>> pl.show()
add_point_scalar_labels(points, labels, fmt=None, preamble='', **kwargs)#

Label the points from a dataset with the values of their scalars.

Wrapper for pyvista.Plotter.add_point_labels().

Parameters:
  • points (sequence[float] | np.ndarray | pyvista.DataSet) – An n x 3 numpy.ndarray or pyvista dataset with points.

  • labels (list | str) – List of scalars of labels. Must be the same length as points. If a string name is given with a pyvista.DataSet input for points, then these are fetched.

  • fmt (str, optional) – String formatter used to format numerical data.

  • preamble (str, default: "") – Text before the start of each label.

  • **kwargs (dict, optional) – Keyword arguments passed to pyvista.Plotter.add_point_labels().

Returns:

vtk.vtkActor2D – VTK label actor. Can be used to change properties of the labels.

add_points(points, style='points', **kwargs)#

Add points to a mesh.

Parameters:
  • points (numpy.ndarray or pyvista.DataSet) – Array of points or the points from a pyvista object.

  • style (str, default: 'points') – Visualization style of the mesh. One of the following: style='points', style='points_gaussian'. 'points_gaussian' can be controlled with the emissive and render_points_as_spheres options.

  • **kwargs (dict, optional) – See pyvista.Plotter.add_mesh() for optional keyword arguments.

Returns:

pyvista.Actor – Actor of the mesh.

Examples

Add a numpy array of points to a mesh.

>>> import numpy as np
>>> import pyvista as pv
>>> rng = np.random.default_rng(seed=0)
>>> points = rng.random((10, 3))
>>> pl = pv.Plotter()
>>> actor = pl.add_points(
...     points, render_points_as_spheres=True, point_size=100.0
... )
>>> pl.show()

Plot using the 'points_gaussian' style

>>> points = rng.random((10, 3))
>>> pl = pv.Plotter()
>>> actor = pl.add_points(points, style='points_gaussian')
>>> pl.show()
add_ruler(pointa, pointb, flip_range=False, number_labels=None, show_labels=True, font_size_factor=0.6, label_size_factor=1.0, label_format=None, title='Distance', number_minor_ticks=0, tick_length=5, minor_tick_length=3, show_ticks=True, tick_label_offset=2, label_color=None, tick_color=None, scale=1.0)#

Add ruler.

The ruler is a 2D object that is not occluded by 3D objects. To avoid issues with perspective, it is recommended to use parallel projection, i.e. Plotter.enable_parallel_projection(), and place the ruler orthogonal to the viewing direction.

The title and labels are placed to the right of ruler moving from pointa to pointb. Use flip_range to flip the 0 location, if needed.

Since the ruler is placed in an overlay on the viewing scene, the camera does not automatically reset to include the ruler in the view.

Parameters:
  • pointa (sequence[float]) – Starting point for ruler.

  • pointb (sequence[float]) – Ending point for ruler.

  • flip_range (bool, default: False) – If True, the distance range goes from pointb to pointa.

  • number_labels (int, optional) – Number of labels to place on ruler. If not supplied, the number will be adjusted for “nice” values.

  • show_labels (bool, default: True) – Whether to show labels.

  • font_size_factor (float, default: 0.6) – Factor to scale font size overall.

  • label_size_factor (float, default: 1.0) – Factor to scale label size relative to title size.

  • label_format (str, optional) – A printf style format for labels, e.g. ‘%E’.

  • title (str, default: "Distance") – The title to display.

  • number_minor_ticks (int, default: 0) – Number of minor ticks between major ticks.

  • tick_length (int, default: 5) – Length of ticks in pixels.

  • minor_tick_length (int, default: 3) – Length of minor ticks in pixels.

  • show_ticks (bool, default: True) – Whether to show the ticks.

  • tick_label_offset (int, default: 2) – Offset between tick and label in pixels.

  • label_color (ColorLike, optional) –

    Either a string, rgb list, or hex color string for label and title colors.

    Warning

    This is either white or black.

  • tick_color (ColorLike, optional) – Either a string, rgb list, or hex color string for tick line colors.

  • scale (float, default: 1.0) –

    Scale factor for the ruler.

    Added in version 0.44.0.

Returns:

vtk.vtkActor – VTK actor of the ruler.

Examples

>>> import pyvista as pv
>>> cone = pv.Cone(height=2.0, radius=0.5)
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(cone)

Measure x direction of cone and place ruler slightly below.

>>> _ = plotter.add_ruler(
...     pointa=[cone.bounds[0], cone.bounds[2] - 0.1, 0.0],
...     pointb=[cone.bounds[1], cone.bounds[2] - 0.1, 0.0],
...     title="X Distance",
... )

Measure y direction of cone and place ruler slightly to left. The title and labels are placed to the right of the ruler when traveling from pointa to pointb.

>>> _ = plotter.add_ruler(
...     pointa=[cone.bounds[0] - 0.1, cone.bounds[3], 0.0],
...     pointb=[cone.bounds[0] - 0.1, cone.bounds[2], 0.0],
...     flip_range=True,
...     title="Y Distance",
... )
>>> plotter.enable_parallel_projection()
>>> plotter.view_xy()
>>> plotter.show()
add_scalar_bar(title='', 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=None, interactive=None, fmt=None, use_opacity=True, outline=False, nan_annotation=False, below_label=None, above_label=None, background_color=None, n_colors=None, fill=False, render=False, theme=None, unconstrained_font_size=False)#

Create scalar bar using the ranges as set by the last input mesh.

Parameters:
  • title (str, default: "") – Title of the scalar bar. Default is rendered as an empty title.

  • mapper (vtkMapper, optional) – Mapper used for the scalar bar. Defaults to the last mapper created by the plotter.

  • n_labels (int, default: 5) – Number of labels to use for the scalar bar.

  • italic (bool, default: False) – Italicises title and bar labels.

  • bold (bool, default: False) – Bolds title and bar labels.

  • title_font_size (float, optional) – Sets the size of the title font. Defaults to None and is sized according to pyvista.plotting.themes.Theme.font.

  • label_font_size (float, optional) – Sets the size of the title font. Defaults to None and is sized according to pyvista.plotting.themes.Theme.font.

  • color (ColorLike, optional) –

    Either a string, rgb list, or hex color string. Default set by pyvista.plotting.themes.Theme.font. Can be in one of the following formats:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • font_family ({'courier', 'times', 'arial'}) – Font family. Default is set by pyvista.plotting.themes.Theme.font.

  • shadow (bool, default: False) – Adds a black shadow to the text.

  • width (float, optional) – The percentage (0 to 1) width of the window for the colorbar. Default set by pyvista.plotting.themes.Theme.colorbar_vertical or pyvista.plotting.themes.Theme.colorbar_horizontal depending on the value of vertical.

  • height (float, optional) – The percentage (0 to 1) height of the window for the colorbar. Default set by pyvista.plotting.themes.Theme.colorbar_vertical or pyvista.plotting.themes.Theme.colorbar_horizontal depending on the value of vertical.

  • position_x (float, optional) – The percentage (0 to 1) along the windows’s horizontal direction to place the bottom left corner of the colorbar. Default set by pyvista.plotting.themes.Theme.colorbar_vertical or pyvista.plotting.themes.Theme.colorbar_horizontal depending on the value of vertical.

  • position_y (float, optional) – The percentage (0 to 1) along the windows’s vertical direction to place the bottom left corner of the colorbar. Default set by pyvista.plotting.themes.Theme.colorbar_vertical or pyvista.plotting.themes.Theme.colorbar_horizontal depending on the value of vertical.

  • vertical (bool, optional) – Use vertical or horizontal scalar bar. Default set by pyvista.plotting.themes.Theme.colorbar_orientation.

  • interactive (bool, optional) – Use a widget to control the size and location of the scalar bar. Default set by pyvista.plotting.themes.Theme.interactive.

  • fmt (str, optional) – printf format for labels. Default set by pyvista.plotting.themes.Theme.font.

  • use_opacity (bool, default: True) – Optionally display the opacity mapping on the scalar bar.

  • outline (bool, default: False) – Optionally outline the scalar bar to make opacity mappings more obvious.

  • nan_annotation (bool, default: False) – Annotate the NaN color.

  • below_label (str, optional) – String annotation for values below the scalars range.

  • above_label (str, optional) – String annotation for values above the scalars range.

  • background_color (ColorLike, optional) – The color used for the background in RGB format.

  • n_colors (int, optional) – The maximum number of color displayed in the scalar bar.

  • fill (bool, default: False) – Draw a filled box behind the scalar bar with the background_color.

  • render (bool, default: False) – Force a render when True.

  • theme (pyvista.plotting.themes.Theme, optional) – Plot-specific theme. By default, calling from the Plotter, will use the plotter theme. Setting to None will use the global theme.

  • unconstrained_font_size (bool, default: False) –

    Whether the font size of title and labels is unconstrained. When it is constrained, the size of the scalar bar will constrain the font size. When it is not, the size of the font will always be respected. Using custom labels will force this to be True.

    Added in version 0.44.0.

Returns:

vtk.vtkScalarBarActor – Scalar bar actor.

Notes

Setting title_font_size, or label_font_size disables automatic font sizing for both the title and label.

Examples

Add a custom interactive scalar bar that is horizontal, has an outline, and has a custom formatting.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere['Data'] = sphere.points[:, 2]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere, show_scalar_bar=False)
>>> _ = plotter.add_scalar_bar(
...     'Data',
...     interactive=True,
...     vertical=False,
...     title_font_size=35,
...     label_font_size=30,
...     outline=True,
...     fmt='%10.5f',
... )
>>> plotter.show()
add_silhouette(mesh, color=None, line_width=None, opacity=None, feature_angle=None, decimate=None)#

Add a silhouette of a PyVista or VTK dataset to the scene.

A silhouette can also be generated directly in add_mesh. See also silhouette_example.

Parameters:
  • mesh (pyvista.DataSet | vtk.vtkAlgorithm) – Mesh or mesh-producing algorithm for generating silhouette to plot.

  • color (ColorLike, optional) – Color of the silhouette lines.

  • line_width (float, optional) – Silhouette line width.

  • opacity (float, optional) – Line transparency between 0 and 1.

  • feature_angle (float, optional) – If set, display sharp edges exceeding that angle in degrees.

  • decimate (float, optional) – Level of decimation between 0 and 1. Decimating will improve rendering performance. A good rule of thumb is to try 0.9 first and decrease until the desired rendering performance is achieved.

Returns:

pyvista.Actor – Actor of the silhouette.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> bunny = examples.download_bunny()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(bunny, color='lightblue')
>>> _ = plotter.add_silhouette(bunny, color='red', line_width=8.0)
>>> plotter.view_xy()
>>> plotter.show()
add_slider_widget(callback, rng, value=None, title=None, pointa=(0.4, 0.9), pointb=(0.9, 0.9), color=None, pass_widget=False, interaction_event='end', style=None, title_height=0.03, title_opacity=1.0, title_color=None, fmt=None, slider_width=None, tube_width=None)#

Add a slider bar widget.

This is useless without a callback function. You can pass a callable function that takes a single argument, the value of this slider widget, and performs a task with that value.

Parameters:
  • callback (callable) – Called every time the slider is updated. This should take a single parameter: the float value of the slider. If pass_widget=True, callable should take two parameters: the float value of the slider and the widget itself.

  • rng (tuple(float)) – Length two tuple of the minimum and maximum ranges of the slider.

  • value (float, optional) – The starting value of the slider.

  • title (str, optional) – The string label of the slider widget.

  • pointa (tuple(float), optional) – The relative coordinates of the left point of the slider on the display port.

  • pointb (tuple(float), optional) – The relative coordinates of the right point of the slider on the display port.

  • color (ColorLike, optional) – Either a string, RGB list, or hex color string. Defaults to pyvista.global_theme.font.color.

  • pass_widget (bool, optional) – If True, the widget will be passed as the last argument of the callback.

  • interaction_event (vtk.vtkCommand.EventIds, str, optional) –

    The VTK interaction event to use for triggering the callback. Accepts either the strings 'start', 'end', 'always' or a vtk.vtkCommand.EventIds.

    Changed in version 0.38.0: Changed from event_type to interaction_event and now accepts either strings or vtk.vtkCommand.EventIds.

  • style (str, optional) – The name of the slider style. The list of available styles are in pyvista.global_theme.slider_styles. Defaults to None.

  • title_height (float, optional) – Relative height of the title as compared to the length of the slider.

  • title_opacity (float, optional) – Opacity of title. Defaults to 1.0.

  • title_color (ColorLike, optional) – Either a string, RGB sequence, or hex color string. Defaults to the value given in color.

  • fmt (str, optional) – String formatter used to format numerical data. Defaults to None.

  • slider_width (float, optional) – Normalized width of the slider. Defaults to the theme’s slider width.

  • tube_width (float, optional) – Normalized width of the tube. Defaults to the theme’s tube width.

Returns:

vtk.vtkSliderWidget – Slider widget.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> def create_mesh(value):
...     res = int(value)
...     sphere = pv.Sphere(
...         phi_resolution=res, theta_resolution=res
...     )
...     pl.add_mesh(sphere, name="sphere", show_edges=True)
...
>>> slider = pl.add_slider_widget(
...     create_mesh,
...     [5, 100],
...     title="Resolution",
...     title_opacity=0.5,
...     title_color="red",
...     fmt="%0.9f",
...     title_height=0.08,
... )
>>> pl.show()
add_sphere_widget(callback, center=(0, 0, 0), radius=0.5, theta_resolution=30, phi_resolution=30, color=None, style='surface', selected_color='pink', indices=None, pass_widget=False, test_callback=True, interaction_event=45)#

Add one or many sphere widgets to a scene.

Use a sphere widget to control a vertex location.

Parameters:
  • callback (callable) – The function to call back when the widget is modified. It takes a single argument: the center of the sphere as an XYZ coordinate (a 3-length sequence), unless pass_widget=True, in which case the callback must accept the widget object as the second parameter. If multiple centers are passed in the center parameter, the callback must also accept an index of that widget.

  • center (sequence[float], optional) – The cartesian coordinate of the sphere’s center when placing it in the scene. If more than one location is passed, then that many widgets will be added and the callback will also be passed the integer index of that widget.

  • radius (float, optional) – The radius of the sphere.

  • theta_resolution (int, optional) – Set the number of points in the longitude direction.

  • phi_resolution (int, optional) – Set the number of points in the latitude direction.

  • color (ColorLike, optional) –

    The color of the sphere’s surface. If multiple centers are passed, then this must be a list of colors. Each color is either a string, rgb list, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • style (str, optional) – Representation style: 'surface' or 'wireframe'.

  • selected_color (ColorLike, optional) – Color of the widget when selected during interaction.

  • indices (sequence[int], optional) – Indices to assign the sphere widgets.

  • pass_widget (bool, optional) – If True, the widget will be passed as the last argument of the callback.

  • test_callback (bool, optional) – If True, run the callback function after the widget is created.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

Returns:

vtk.vtkSphereWidget – The sphere widget.

add_spline_widget(callback, bounds=None, factor=1.25, n_handles=5, resolution=25, color='yellow', show_ribbon=False, ribbon_color='pink', ribbon_opacity=0.5, pass_widget=False, closed=False, initial_points=None, interaction_event=45)#

Create and add a spline widget to the scene.

Use the bounds argument to place this widget. Several “handles” are used to control a parametric function for building this spline. Click directly on the line to translate the widget.

Parameters:
  • callback (callable) – The method called every time the spline is updated. This passes a pyvista.PolyData object to the callback function of the generated spline.

  • bounds (sequence[float], optional) – Length 6 sequence of the bounding box where the widget is placed.

  • factor (float, optional) – An inflation factor to expand on the bounds when placing.

  • n_handles (int, optional) – The number of interactive spheres to control the spline’s parametric function.

  • resolution (int, optional) – The number of points in the spline created between all the handles.

  • color (ColorLike, optional) – Either a string, RGB sequence, or hex color string.

  • show_ribbon (bool, optional) – If True, the poly plane used for slicing will also be shown.

  • ribbon_color (ColorLike, optional) – Color of the ribbon. Either a string, RGB sequence, or hex color string.

  • ribbon_opacity (float, optional) – Opacity of ribbon. Defaults to 1.0 and must be between [0, 1].

  • pass_widget (bool, optional) – If True, the widget will be passed as the last argument of the callback.

  • closed (bool, optional) – Make the spline a closed loop.

  • initial_points (sequence, optional) – The points to initialize the widget placement. Must have same number of elements as n_handles. If the first and last point are the same, this will be a closed loop spline.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

Returns:

vtk.vtkSplineWidget – The newly created spline widget.

Notes

This widget has trouble displaying certain colors. Use only simple colors (white, black, yellow).

add_text(text, position='upper_left', font_size=18, color=None, font=None, shadow=False, name=None, viewport=False, orientation=0.0, font_file=None, *, render=True)#

Add text to plot object in the top left corner by default.

Parameters:
  • text (str) – The text to add the rendering.

  • position (str | sequence[float], default: "upper_left") – Position to place the bottom left corner of the text box. If tuple is used, the position of the text uses the pixel coordinate system (default). In this case, it returns a more general vtkOpenGLTextActor. If string name is used, it returns a vtkCornerAnnotation object normally used for fixed labels (like title or xlabel). Default is to find the top left corner of the rendering window and place text box up there. Available position: 'lower_left', 'lower_right', 'upper_left', 'upper_right', 'lower_edge', 'upper_edge', 'right_edge', and 'left_edge'.

  • font_size (float, default: 18) – Sets the size of the title font.

  • color (ColorLike, optional) –

    Either a string, RGB list, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

    Defaults to pyvista.global_theme.font.color.

  • font (str, default: 'arial') – Font name may be 'courier', 'times', or 'arial'. This is ignored if the font_file is set.

  • shadow (bool, default: False) – Adds a black shadow to the text.

  • name (str, optional) – The name for the added 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.

  • viewport (bool, default: False) – If True and position is a tuple of float, uses the normalized viewport coordinate system (values between 0.0 and 1.0 and support for HiDPI).

  • orientation (float, default: 0.0) – Angle orientation of text counterclockwise in degrees. The text is rotated around an anchor point that may be on the edge or corner of the text. The default is horizontal (0.0 degrees).

  • font_file (str, default: None) – The absolute file path to a local file containing a freetype readable font.

  • render (bool, default: True) – Force a render when True.

Returns:

vtk.vtkTextActor – Text actor added to plot.

Examples

Add blue text to the upper right of the plotter.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_text(
...     'Sample Text',
...     position='upper_right',
...     color='blue',
...     shadow=True,
...     font_size=26,
... )
>>> pl.show()

Add text and use a custom freetype readable font file.

>>> pl = pv.Plotter()
>>> actor = pl.add_text(
...     'Text',
...     font_file='/home/user/Mplus2-Regular.ttf',
... )  
add_text_slider_widget(callback, data, value=None, pointa=(0.4, 0.9), pointb=(0.9, 0.9), color=None, interaction_event='end', style=None)#

Add a text slider bar widget.

This is useless without a callback function. You can pass a callable function that takes a single argument, the value of this slider widget, and performs a task with that value.

Parameters:
  • callback (callable) – The method called every time the slider is updated. This should take a single parameter: the float value of the slider.

  • data (list) – The list of possible values displayed on the slider bar.

  • value (float, optional) – The starting value of the slider.

  • pointa (tuple(float), optional) – The relative coordinates of the left point of the slider on the display port.

  • pointb (tuple(float), optional) – The relative coordinates of the right point of the slider on the display port.

  • color (ColorLike, optional) – Either a string, RGB list, or hex color string. Defaults to pyvista.global_theme.font.color.

  • interaction_event (vtk.vtkCommand.EventIds, str, optional) –

    The VTK interaction event to use for triggering the callback. Accepts either the strings 'start', 'end', 'always' or a vtk.vtkCommand.EventIds.

    Changed in version 0.38.0: Changed from event_type to interaction_event and now accepts either strings or vtk.vtkCommand.EventIds.

  • style (str, optional) – The name of the slider style. The list of available styles are in pyvista.global_theme.slider_styles. Defaults to None.

Returns:

vtk.vtkSliderWidget – The VTK slider widget configured to display text.

add_timer_event(max_steps, duration, callback)#

Add a function to callback as timer event.

Parameters:
  • max_steps (int) – Maximum number of steps for integrating a timer.

  • duration (int) – Time (in milliseconds) before the timer emits a TimerEvent and callback is called.

  • callback (callable) – A callable that takes one argument. It will be passed step, which is the number of times the timer event has occurred.

Examples

Add a timer to a Plotter to move a sphere across a scene.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(sphere)
>>> def callback(step):
...     actor.position = [step / 100.0, step / 100.0, 0]
...
>>> pl.add_timer_event(
...     max_steps=200, duration=500, callback=callback
... )
add_title(title, font_size=18, color=None, font=None, shadow=False)#

Add text to the top center of the plot.

This is merely a convenience method that calls add_text with position='upper_edge'.

Parameters:
  • title (str) – The text to add the rendering.

  • font_size (float, default: 18) – Sets the size of the title font.

  • color (ColorLike, optional) –

    Either a string, rgb list, or hex color string. Defaults to white or the value of the global theme if set. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • font (str, optional) – Font name may be 'courier', 'times', or 'arial'.

  • shadow (bool, default: False) – Adds a black shadow to the text.

Returns:

vtk.vtkTextActor – Text actor added to plot.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.background_color = 'grey'
>>> actor = pl.add_title(
...     'Plot Title', font='courier', color='k', font_size=40
... )
>>> pl.show()
add_volume(volume, scalars=None, clim=None, resolution=None, opacity='linear', n_colors=256, cmap=None, flip_scalars=False, reset_camera=None, name=None, ambient=None, categories=False, culling=False, multi_colors=False, blending='composite', mapper=None, scalar_bar_args=None, show_scalar_bar=None, annotations=None, pickable=True, preference='point', opacity_unit_distance=None, shade=False, diffuse=0.7, specular=0.2, specular_power=10.0, render=True, user_matrix=None, log_scale=False, **kwargs)#

Add a volume, rendered using a smart mapper by default.

Requires a 3D data type like numpy.ndarray, pyvista.ImageData, pyvista.RectilinearGrid, or pyvista.UnstructuredGrid.

Parameters:
  • volume (3D numpy.ndarray | pyvista.DataSet) –

    The input volume to visualize. 3D numpy arrays are accepted.

    Warning

    If the input is not numpy.ndarray, pyvista.ImageData, or pyvista.RectilinearGrid, volume rendering will often have poor performance.

  • scalars (str | numpy.ndarray, optional) –

    Scalars used to “color” the mesh. Accepts a string name of an array that is present on the mesh or an array with length equal to the number of cells or the number of points in the mesh. If scalars is None, then the active scalars are used.

    Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional, the scalars will be mapped to the lookup table. If 2 dimensional the scalars will be directly mapped to RGBA values, array should be shaped (N, 4) where N is the number of points, and of datatype np.uint8.

    Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional, the scalars will be mapped to the lookup table. If 2 dimensional the scalars will be directly mapped to RGBA values, array should be shaped (N, 4) where N is the number of points, and of datatype np.uint8.

  • clim (sequence[float] | float, optional) –

    Color bar range for scalars. For example: [-1, 2]. Defaults to minimum and maximum of scalars array if the scalars dtype is not np.uint8. rng is also an accepted alias for this parameter.

    If the scalars datatype is np.uint8, this parameter defaults to [0, 256].

    If a single value is given, the range [-clim, clim] is used.

  • resolution (list, optional) – Block resolution. For example [1, 1, 1]. Resolution must be non-negative. While VTK accepts negative spacing, this results in unexpected behavior. See: pyvista #1967.

  • opacity (str | numpy.ndarray, optional) –

    Opacity mapping for the scalars array.

    A string can also be specified to map the scalars range to a predefined opacity transfer function. Or you can pass a custom made transfer function that is an array either n_colors in length or array, or you can pass a string to select a built in transfer function. If a string, should be one of the following:

    • 'linear' - Linear

    • 'linear_r' - Linear except reversed

    • 'geom' - Evenly spaced on the log scale

    • 'geom_r' - Evenly spaced on the log scale except reversed

    • 'sigmoid' - Linear map between -10.0 and 10.0

    • 'sigmoid_1' - Linear map between -1.0 and 1.0

    • 'sigmoid_2' - Linear map between -2.0 and 2.0

    • 'sigmoid_3' - Linear map between -3.0 and 3.0

    • 'sigmoid_4' - Linear map between -4.0 and 4.0

    • 'sigmoid_5' - Linear map between -5.0 and 5.0

    • 'sigmoid_6' - Linear map between -6.0 and 6.0

    • 'sigmoid_7' - Linear map between -7.0 and 7.0

    • 'sigmoid_8' - Linear map between -8.0 and 8.0

    • 'sigmoid_9' - Linear map between -9.0 and 9.0

    • 'sigmoid_10' - Linear map between -10.0 and 10.0

    • 'sigmoid_15' - Linear map between -15.0 and 15.0

    • 'sigmoid_20' - Linear map between -20.0 and 20.0

    • 'foreground' - Transparent background and opaque foreground.

      Intended for use with segmentation labels. Assumes the smallest scalar value of the array is the background value (e.g. 0).

    If RGBA scalars are provided, this parameter is set to 'linear' to ensure the opacity transfer function has no effect on the input opacity values.

  • n_colors (int, optional) – Number of colors to use when displaying scalars. Defaults to 256. The scalar bar will also have this many colors.

  • cmap (str | list | pyvista.LookupTable, default: pyvista.plotting.themes.Theme.cmap) –

    If a string, this is the name of the matplotlib colormap to use when mapping the scalars. See available Matplotlib colormaps. Only applicable for when displaying scalars. colormap is also an accepted alias for this. If colorcet or cmocean are installed, their colormaps can be specified by name.

    You can also specify a list of colors to override an existing colormap with a custom one. For example, to create a three color colormap you might specify ['green', 'red', 'blue'].

    This parameter also accepts a pyvista.LookupTable. If this is set, all parameters controlling the color map like n_colors will be ignored.

  • flip_scalars (bool, optional) – Flip direction of cmap. Most colormaps allow *_r suffix to do this as well.

  • reset_camera (bool, optional) – Reset the camera after adding this mesh to the scene.

  • name (str, optional) – The name for the added 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.

  • 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.0.

  • categories (bool, optional) – If set to True, then the number of unique values in the scalar array will be used as the n_colors argument.

  • culling (str, optional) – Does not render faces that are culled. Options are 'front' or 'back'. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Defaults False.

  • multi_colors (bool, optional) – Whether or not to use multiple colors when plotting MultiBlock object. Blocks will be colored sequentially as ‘Reds’, ‘Greens’, ‘Blues’, and ‘Grays’.

  • blending (str, optional) – Blending mode for visualisation of the input object(s). Can be one of ‘additive’, ‘maximum’, ‘minimum’, ‘composite’, or ‘average’. Defaults to ‘composite’.

  • mapper (str, optional) –

    Volume mapper to use given by name. Options include: 'fixed_point', 'gpu', 'open_gl', and 'smart'. If None the "volume_mapper" in the self._theme is used. If using 'fixed_point', only ImageData types can be used.

    Note

    If a pyvista.UnstructuredGrid is input, the ‘ugrid’ mapper (vtkUnstructuredGridVolumeRayCastMapper) will be used regardless.

    Note

    The 'smart' mapper chooses one of the other listed mappers based on rendering parameters and available hardware. Most of the time the 'smart' simply checks if a GPU is available and if so, uses the 'gpu' mapper, otherwise using the 'fixed_point' mapper.

    Warning

    The 'fixed_point' mapper is CPU-based and will have lower performance than the 'gpu' or 'open_gl' mappers.

  • scalar_bar_args (dict, optional) – Dictionary of keyword arguments to pass when adding the scalar bar to the scene. For options, see pyvista.Plotter.add_scalar_bar().

  • show_scalar_bar (bool) – If False, a scalar bar will not be added to the scene. Defaults to True.

  • annotations (dict, optional) – Pass a dictionary of annotations. Keys are the float values in the scalars range to annotate on the scalar bar and the values are the string annotations.

  • pickable (bool, optional) – Set whether this mesh is pickable.

  • preference (str, optional) – When mesh.n_points == mesh.n_cells and setting scalars, this parameter sets how the scalars will be mapped to the mesh. Default 'point', causes the scalars will be associated with the mesh points. Can be either 'point' or 'cell'.

  • opacity_unit_distance (float, optional) – Set/Get the unit distance on which the scalar opacity transfer function is defined. Meaning that over that distance, a given opacity (from the transfer function) is accumulated. This is adjusted for the actual sampling distance during rendering. By default, this is the length of the diagonal of the bounding box of the volume divided by the dimensions.

  • shade (bool, default: False) – Default off. If shading is turned on, the mapper may perform shading calculations - in some cases shading does not apply (for example, in a maximum intensity projection) and therefore shading will not be performed even if this flag is on.

  • diffuse (float, default: 0.7) – The diffuse lighting coefficient.

  • specular (float, default: 0.2) – The specular lighting coefficient.

  • specular_power (float, default: 10.0) – The specular power. Between 0.0 and 128.0.

  • render (bool, default: True) – Force a render when True.

  • user_matrix (np.ndarray | vtk.vtkMatrix4x4, default: np.eye(4)) – Matrix passed to the Volume class before rendering. This affects the actor/rendering only, not the input volume itself. The user matrix is the last transformation applied to the actor before rendering. Defaults to the identity matrix.

  • log_scale (bool, default: False) – Use log scale when mapping data to colors. Scalars less than zero are mapped to the smallest representable positive float.

  • **kwargs (dict, optional) – Optional keyword arguments.

Returns:

pyvista.Actor – Actor of the volume.

Examples

Show a built-in volume example with the coolwarm colormap.

>>> from pyvista import examples
>>> import pyvista as pv
>>> bolt_nut = examples.download_bolt_nut()
>>> pl = pv.Plotter()
>>> _ = pl.add_volume(bolt_nut, cmap="coolwarm")
>>> pl.show()

Create a volume from scratch and plot it using single vector of scalars.

>>> import pyvista as pv
>>> grid = pv.ImageData(dimensions=(9, 9, 9))
>>> grid['scalars'] = -grid.x
>>> pl = pv.Plotter()
>>> _ = pl.add_volume(grid, opacity='linear')
>>> pl.show()

Plot a volume from scratch using RGBA scalars

>>> import pyvista as pv
>>> import numpy as np
>>> grid = pv.ImageData(dimensions=(5, 20, 20))
>>> scalars = grid.points - (grid.origin)
>>> scalars /= scalars.max()
>>> opacity = np.linalg.norm(
...     grid.points - grid.center, axis=1
... ).reshape(-1, 1)
>>> opacity /= opacity.max()
>>> scalars = np.hstack((scalars, opacity**3))
>>> scalars *= 255
>>> pl = pv.Plotter()
>>> vol = pl.add_volume(grid, scalars=scalars.astype(np.uint8))
>>> vol.prop.interpolation_type = 'linear'
>>> pl.show()

Plot an UnstructuredGrid.

>>> from pyvista import examples
>>> import pyvista as pv
>>> mesh = examples.download_letter_a()
>>> mesh['scalars'] = mesh.points[:, 1]
>>> pl = pv.Plotter()
>>> _ = pl.add_volume(mesh, opacity_unit_distance=0.1)
>>> pl.show()
add_volume_clip_plane(volume, 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, interaction_event='end', origin=None, outline_opacity=None, **kwargs)#

Clip a volume using a plane widget.

Parameters:
  • volume (pyvista.plotting.volume.Volume or pyvista.ImageData or pyvista.RectilinearGrid) – New dataset of type pyvista.ImageData or pyvista.RectilinearGrid, or the return value from pyvista.plotting.volume.Volume from Plotter.add_volume().

  • normal (str or tuple(float), optional) – The starting normal vector of the plane.

  • invert (bool, optional) – Flag on whether to flip/invert the clip.

  • widget_color (ColorLike, optional) – Either a string, RGB list, or hex color string.

  • value (float, optional) – Set the clipping value along the normal direction. The default value is 0.0.

  • assign_to_axis (str or int, optional) – Assign the normal of the plane to be parallel with a given axis. Options are (0, 'x'), (1, 'y'), or (2, 'z').

  • tubing (bool, optional) – When using an implicit plane wiget, this controls whether or not tubing is shown around the plane’s boundaries.

  • origin_translation (bool, optional) – If False, the plane widget cannot be translated by its origin and is strictly placed at the given origin. Only valid when using an implicit plane.

  • outline_translation (bool, optional) – If False, the box widget cannot be translated and is strictly placed at the given bounds.

  • implicit (bool, optional) – When True, a vtkImplicitPlaneWidget is used and when False, a vtkPlaneWidget is used.

  • normal_rotation (bool, optional) – Set the opacity of the normal vector arrow to 0 such that it is effectively disabled. This prevents the user from rotating the normal. This is forced to False when assign_to_axis is set.

  • interaction_event (vtk.vtkCommand.EventIds, optional) – The VTK interaction event to use for triggering the callback.

  • origin (tuple(float), optional) – The starting coordinate of the center of the plane.

  • outline_opacity (bool or float, optional) –

    Set the visible of outline. Only valid when using an implicit plane. Either a bool or float.

    Added in version 0.44.0.

  • **kwargs (dict, optional) – All additional keyword arguments are passed to Plotter.add_volume() to control how the volume is displayed. Only applicable if volume is either a pyvista.ImageData and pyvista.RectilinearGrid.

Returns:

vtk.vtkPlaneWidget or vtk.vtkImplicitPlaneWidget – The VTK plane widget depending on the value of implicit.

property background_color#

Return the background color of the active render window.

Examples

Set the background color to "pink" and plot it.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube(), show_edges=True)
>>> pl.background_color = "pink"
>>> pl.background_color
Color(name='pink', hex='#ffc0cbff', opacity=255)
>>> pl.show()
property bounds: BoundsLike#

Return the bounds of the active renderer.

Returns:

tuple[numpy.float64, numpy.float64, numpy.float64, numpy.float64, numpy.float64, numpy.float64] – Bounds of the active renderer.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.bounds
(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)
property camera#

Return the active camera of the active renderer.

Returns:

pyvista.Camera – Camera from the active renderer.

property camera_position#

Return camera position of the active render window.

Examples

Return camera’s position and then reposition it via a list of tuples.

>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.download_bunny_coarse()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True, reset_camera=True)
>>> pl.camera_position
[(0.02430, 0.0336, 0.9446),
 (0.02430, 0.0336, -0.02225),
 (0.0, 1.0, 0.0)]
>>> pl.camera_position = [
...     (0.3914, 0.4542, 0.7670),
...     (0.0243, 0.0336, -0.0222),
...     (-0.2148, 0.8998, -0.3796),
... ]
>>> pl.show()

Set the camera position using a string and look at the 'xy' plane.

>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> pl.camera_position = 'xy'
>>> pl.show()

Set the camera position using a string and look at the 'zy' plane.

>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> pl.camera_position = 'zy'
>>> pl.show()

For more examples, see cameras_api.

property camera_set#

Return or set if the camera of the active renderer has been set.

property center: tuple[float, float, float]#

Return the center of the active renderer.

Returns:

list[numpy.float64, numpy.float64, numpy.float64] – Center of the active renderer.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.center
(0.0, 0.0, 0.0)
clear()#

Clear plot by removing all actors and properties.

Examples

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(pv.Sphere())
>>> plotter.clear()
>>> plotter.renderer.actors
{}
clear_actors()#

Clear actors from all renderers.

clear_box_widgets()#

Remove all of the box widgets.

clear_button_widgets()#

Remove all of the button widgets.

clear_camera3d_widgets()#

Remove all of the camera3d widgets.

clear_camera_widgets()#

Remove all of the camera widgets.

clear_events_for_key(key, raise_on_missing=False)#

Remove the callbacks associated to the key.

Parameters:
  • key (str) – Key to clear events for.

  • raise_on_missing (bool, default: False) – Whether to raise a ValueError if there are no events registered for the given key.

clear_line_widgets()#

Remove all of the line widgets.

clear_logo_widgets()#

Remove all of the logo widgets.

clear_measure_widgets()#

Remove all of the measurement widgets.

clear_on_render_callbacks()#

Clear all callback methods previously registered with render().

clear_plane_widgets()#

Remove all of the plane widgets.

clear_slider_widgets()#

Remove all of the slider widgets.

clear_sphere_widgets()#

Remove all of the sphere widgets.

clear_spline_widgets()#

Remove all of the spline widgets.

close()#

Close the render window.

deep_clean()#

Clean the plotter of the memory.

disable()#

Disable this renderer’s camera from being interactive.

disable_3_lights()#

Please use enable_lightkit, this method has been deprecated.

disable_anti_aliasing(all_renderers=True)#

Disable anti-aliasing.

Parameters:

all_renderers (bool, default: True) – If True, applies to all renderers in subplots. If False, then only applies to the active renderer.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.disable_anti_aliasing()
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.show()

See anti_aliasing_example for a full example demonstrating VTK’s anti-aliasing approaches.

disable_depth_of_field()#

Disable depth of field plotting.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter(lighting="three lights")
>>> pl.enable_depth_of_field()
>>> pl.disable_depth_of_field()
disable_depth_peeling()#

Disable depth peeling.

disable_eye_dome_lighting()#

Disable eye dome lighting (EDL).

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.disable_eye_dome_lighting()
disable_hidden_line_removal(all_renderers=True)#

Disable hidden line removal.

Enable again with enable_hidden_line_removal.

Parameters:

all_renderers (bool, default: True) – If True, applies to all renderers in subplots. If False, then only applies to the active renderer.

Examples

Enable and then disable hidden line removal.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.enable_hidden_line_removal()
>>> pl.disable_hidden_line_removal()
disable_parallel_projection()#

Reset the camera to use perspective projection.

Examples

>>> import pyvista as pv
>>> from pyvista import demos
>>> pl = pv.demos.orientation_plotter()
>>> pl.disable_parallel_projection()
>>> pl.show()
disable_picking()#

Disable any active picking and remove observers.

Examples

Enable and then disable picking.

>>> import pyvista as pv
>>> mesh = pv.Sphere(center=(1, 0, 0))
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_mesh_picking()
>>> pl.disable_picking()
disable_shadows()#

Disable shadows.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.disable_shadows()
disable_ssao()#

Disable surface space ambient occlusion (SSAO).

disable_stereo_render()#

Disable anaglyph stereo rendering.

Enable again with enable_stereo_render

Examples

Enable and then disable stereo rendering. It should show a simple cube.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.enable_stereo_render()
>>> pl.disable_stereo_render()
>>> pl.show()
enable()#

Enable this renderer’s camera to be interactive.

enable_2d_style()#

Set the interactive style to 2D.

For a 3-button mouse, the left button pans, the right button dollys, the middle button spins, and the wheel dollys. ctrl + left button spins, shift + left button dollys, ctrl + middle button pans, shift + middle button dollys, ctrl + right button rotates in 3D, and shift + right button dollys.

Recommended to use with pyvista.Plotter.enable_parallel_projection().

See also

pyvista.Plotter.enable_parallel_projection

Set parallel projection, which is useful for 2D views.

pyvista.Plotter.enable_custom_trackball_style

A style that can be customized for mouse actions.

Examples

Create a simple scene with a plotter that has a ParaView-like 2D style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_parallel_projection()
>>> plotter.enable_2d_style()
>>> plotter.show()  
enable_3_lights(only_active=False)#

Enable 3-lights illumination.

This will replace all pre-existing lights in the scene.

Parameters:

only_active (bool, default: False) – If True, only change the active renderer. The default is that every renderer is affected.

Examples

>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.enable_3_lights()
>>> pl.show()

Note how this varies from the default plotting.

>>> pl = demos.orientation_plotter()
>>> pl.show()
enable_anti_aliasing(aa_type='ssaa', multi_samples=None, all_renderers=True)#

Enable anti-aliasing.

This tends to make edges appear softer and less pixelated.

Parameters:
  • aa_type (str, default: "ssaa") –

    Anti-aliasing type. See the notes below. One of the following:

    • "ssaa" - Super-Sample Anti-Aliasing

    • "msaa" - Multi-Sample Anti-Aliasing

    • "fxaa" - Fast Approximate Anti-Aliasing

  • multi_samples (int, optional) – The number of multi-samples when aa_type is "msaa". Note that using this setting automatically enables this for all renderers. Defaults to the theme multi_samples.

  • all_renderers (bool, default: True) – If True, applies to all renderers in subplots. If False, then only applies to the active renderer.

Notes

SSAA, or Super-Sample Anti-Aliasing is a brute force method of anti-aliasing. It results in the best image quality but comes at a tremendous resource cost. SSAA works by rendering the scene at a higher resolution. The final image is produced by downsampling the massive source image using an averaging filter. This acts as a low pass filter which removes the high frequency components that would cause jaggedness.

MSAA, or Multi-Sample Anti-Aliasing is an optimization of SSAA that reduces the amount of pixel shader evaluations that need to be computed by focusing on overlapping regions of the scene. The result is anti-aliasing along edges that is on par with SSAA and less anti-aliasing along surfaces as these make up the bulk of SSAA computations. MSAA is substantially less computationally expensive than SSAA and results in comparable image quality.

FXAA, or Fast Approximate Anti-Aliasing is an Anti-Aliasing technique that is performed entirely in post processing. FXAA operates on the rasterized image rather than the scene geometry. As a consequence, forcing FXAA or using FXAA incorrectly can result in the FXAA filter smoothing out parts of the visual overlay that are usually kept sharp for reasons of clarity as well as smoothing out textures. FXAA is inferior to MSAA but is almost free computationally and is thus desirable on low end platforms.

Examples

Enable super-sample anti-aliasing (SSAA).

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.enable_anti_aliasing('ssaa')
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.show()

See anti_aliasing_example for a full example demonstrating VTK’s anti-aliasing approaches.

enable_block_picking(callback=None, side='left')#

Enable composite block picking.

Use this picker to return the index of a DataSet when using composite dataset like pyvista.MultiBlock and pass it to a callback.

Parameters:
  • callback (callable, optional) – When input, this picker calls this callable after a selection is made. The composite index is passed to callback as the first argument and the dataset as the second argument.

  • side (str, default: "left") – The mouse button to track (either 'left' or 'right'). Also accepts 'r' or 'l'.

Notes

The picked block index can be accessed from picked_block_index attribute.

Examples

Enable block picking with a multiblock dataset. Left clicking will turn blocks blue while right picking will turn the block back to the default color.

>>> import pyvista as pv
>>> multiblock = pv.MultiBlock(
...     [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
... )
>>> pl = pv.Plotter()
>>> actor, mapper = pl.add_composite(multiblock)
>>> def turn_blue(index, dataset):
...     mapper.block_attr[index].color = 'blue'
...
>>> pl.enable_block_picking(callback=turn_blue, side='left')
>>> def clear_color(index, dataset):
...     mapper.block_attr[index].color = None
...
>>> pl.enable_block_picking(callback=clear_color, side='right')
>>> pl.show()
enable_cell_picking(callback=None, through=True, show=True, show_message=True, style='wireframe', line_width=5, color='pink', font_size=18, start=False, show_frustum=False, **kwargs)#

Enable picking of cells with a rectangle selection tool.

Press "r" to enable rectangle based selection. Press "r" again to turn it off. Selection will be saved to self.picked_cells.

All meshes in the scene are available for picking by default. If you would like to only pick a single mesh in the scene, use the pickable=False argument when adding the other meshes to the scene.

When multiple meshes are being picked, the picked cells in self.picked_cells will be a MultiBlock dataset for each mesh’s selection.

Uses last input mesh for input by default.

Warning

Visible cell picking (through=False) will only work if the mesh is displayed with a 'surface' representation style (the default).

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The picked_cells are input as the first parameter to this callable.

  • through (bool, default: True) – When True the picker will select all cells through the mesh(es). When False, the picker will select only visible cells on the selected surface(s).

  • show (bool, default: True) – Show the selection interactively.

  • show_message (bool | str, default: True) – Show the message about how to use the cell picking tool. If this is a string, that will be the message shown.

  • style (str, default: "wireframe") – Visualization style of the selection. One of the following: style='surface', style='wireframe', or style='points'.

  • line_width (float, default: 5.0) – Thickness of selected mesh edges.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • start (bool, default: True) – Automatically start the cell selection tool.

  • show_frustum (bool, default: False) – Show the frustum in the scene.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the selection is interactively displayed.

Examples

Add a mesh and a cube to a plot and enable cell picking.

>>> import pyvista as pv
>>> mesh = pv.Sphere(center=(1, 0, 0))
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_cell_picking()
enable_custom_trackball_style(left='rotate', shift_left='pan', control_left='spin', middle='pan', shift_middle='pan', control_middle='pan', right='dolly', shift_right='environment_rotate', control_right='dolly')#

Set the interactive style to a custom style based on Trackball Camera.

For each choice of button, control-button, and shift-button, the behavior when the mouse is moved can be chosen by passing the following strings:

  • "dolly"

  • "environment_rotate"

  • "pan"

  • "rotate"

  • "spin"

None can also be passed, which also results in the default behavior.

Added in version 0.44.0.

Parameters:
  • left (str, default: "rotate") – Action when the left button is clicked and the mouse is moved.

  • shift_left (str, default: "pan") – Action when the left button is clicked with the shift key and the mouse is moved.

  • control_left (str, default: "spin") – Action when the left button is clicked with the control key and mouse moved.

  • middle (str, default: "pan") – Action when the middle button is clicked and the mouse is moved.

  • shift_middle (str, default: "pan") – Action when the middle button is clicked with the shift key and the mouse is moved.

  • control_middle (str, default: "pan") – Action when the middle button is clicked with the control key and mouse moved.

  • right (str, default: "dolly") – Action when the right button is clicked and the mouse is moved.

  • shift_right (str, default: "environment_rotate") – Action when the right button is clicked with the shift key and the mouse is moved.

  • control_right (str, default: "dolly") – Action when the right button is clicked with the control key and the mouse is moved.

See also

pyvista.Plotter.enable_trackball_style

Base style.

Examples

Create a simple scene with a plotter that has the left button dolly.

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_custom_trackball_style(left="dolly")
>>> plotter.show()  
enable_depth_of_field(automatic_focal_distance=True)#

Enable depth of field plotting.

Parameters:

automatic_focal_distance (bool, default: True) – Use automatic focal distance calculation. When enabled, the center of the viewport will always be in focus regardless of where the focal point is.

Examples

Create five spheres and demonstrate the effect of depth of field.

>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter(lighting="three lights")
>>> pl.background_color = "w"
>>> for i in range(5):
...     mesh = pv.Sphere(center=(-i * 4, 0, 0))
...     color = [0, 255 - i * 20, 30 + i * 50]
...     _ = pl.add_mesh(
...         mesh,
...         show_edges=False,
...         pbr=True,
...         metallic=1.0,
...         color=color,
...     )
...
>>> pl.camera.zoom(1.8)
>>> pl.camera_position = [
...     (4.74, 0.959, 0.525),
...     (0.363, 0.3116, 0.132),
...     (-0.088, -0.0075, 0.996),
... ]
>>> pl.enable_depth_of_field()
>>> pl.show()

See depth_of_field_example for a full example using this method.

enable_depth_peeling(number_of_peels=None, occlusion_ratio=None)#

Enable depth peeling to improve rendering of translucent geometry.

Parameters:
  • number_of_peels (int, optional) – The maximum number of peeling layers. Initial value is 4 and is set in the pyvista.global_theme. A special value of 0 means no maximum limit. It has to be a positive value.

  • occlusion_ratio (float, optional) – The threshold under which the depth peeling algorithm stops to iterate over peel layers. This is the ratio of the number of pixels that have been touched by the last layer over the total number of pixels of the viewport area. Initial value is 0.0, meaning rendering has to be exact. Greater values may speed up the rendering with small impact on the quality.

Returns:

bool – If depth peeling is supported.

enable_element_picking(callback=None, mode='cell', show=True, show_message=True, font_size=18, color='pink', tolerance=0.025, pickable_window=False, left_clicking=False, picker=PickerType.CELL, **kwargs)#

Select individual elements on a mesh.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The mesh is input as the first parameter to this callable.

  • mode (str | ElementType, default: "cell") – The picking mode. Either "mesh", "cell", "face", "edge", or "point".

  • show (bool, default: True) – Show the selection interactively.

  • show_message (bool | str, default: True) – Show the message about how to use the mesh picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • tolerance (float, default: 0.025) –

    Specify tolerance for performing pick operation. Tolerance is specified as fraction of rendering window size. Rendering window size is measured across diagonal.

    Warning

    This is ignored with the 'hardware' picker.

  • pickable_window (bool, default: False) – When True, points in the 3D window are pickable.

  • left_clicking (bool, default: False) –

    When True, meshes can be picked by clicking the left mousebutton.

    Note

    If enabled, left-clicking will not display the bounding box around the picked mesh.

  • picker (str | PickerType, optional) –

    Choice of VTK picker class type:

    • 'hardware': Uses vtkHardwarePicker which is more performant for large geometries (default).

    • 'cell': Uses vtkCellPicker.

    • 'point': Uses vtkPointPicker which will snap to points on the surface of the mesh.

    • 'volume': Uses vtkVolumePicker.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the picked path is interactively displayed.

enable_eye_dome_lighting()#

Enable eye dome lighting (EDL).

Returns:

vtk.vtkOpenGLRenderer – VTK renderer with eye dome lighting pass.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.enable_eye_dome_lighting()
enable_fly_to_right_click(callback=None)#

Set the camera to track right click positions.

A convenience method to track right click positions and fly to the picked point in the scene. The callback will be passed the point in 3D space.

Parameters:

callback (callable) – Callback to call immediately after right clicking.

enable_geodesic_picking(callback=None, show_message=True, font_size=18, color='pink', point_size=10, line_width=5, tolerance=0.025, show_path=True, keep_order=True, **kwargs)#

Enable picking at geodesic paths.

This is a convenience method for enable_point_picking to keep track of the picked points and create a geodesic path using those points.

The geodesic path is saved to the .picked_geodesic attribute of this plotter.

Parameters:
  • callback (callable, optional) – When given, calls this callable after a pick is made. The entire picked, geodesic path is passed as the only parameter to this callable.

  • show_message (bool | str, default: True) – Show the message about how to use the point picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the size of the message.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • point_size (int, default: 10) – Size of picked points if show_path is True.

  • line_width (float, default: 5.0) – Thickness of path representation if show_path is True.

  • tolerance (float, default: 0.025) – Specify tolerance for performing pick operation. Tolerance is specified as fraction of rendering window size. Rendering window size is measured across diagonal.

  • show_path (bool, default: True) – Show the picked path interactively.

  • keep_order (bool, default: True) –

    If True, the created geodesic path is a single ordered and cleaned line from the first point to the last.

    Note

    In older versions there were apparent discontinuities in the resulting path due to the behavior of the underlying VTK filter which corresponds to keep_order=False.

    Added in version 0.32.0.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the picked path is interactively displayed.

enable_hidden_line_removal(all_renderers=True)#

Enable hidden line removal.

Wireframe geometry will be drawn using hidden line removal if the rendering engine supports it.

Disable this with disable_hidden_line_removal.

Parameters:

all_renderers (bool, default: True) – If True, applies to all renderers in subplots. If False, then only applies to the active renderer.

Examples

Create a side-by-side plotter and render a sphere in wireframe with hidden line removal enabled on the left and disabled on the right.

>>> import pyvista as pv
>>> sphere = pv.Sphere(theta_resolution=20, phi_resolution=20)
>>> pl = pv.Plotter(shape=(1, 2))
>>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
>>> _ = pl.add_text("With hidden line removal")
>>> pl.enable_hidden_line_removal(all_renderers=False)
>>> pl.subplot(0, 1)
>>> pl.disable_hidden_line_removal(all_renderers=False)
>>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
>>> _ = pl.add_text("Without hidden line removal")
>>> pl.show()
enable_horizon_picking(callback=None, normal=(0.0, 0.0, 1.0), width=None, show_message=True, font_size=18, color='pink', point_size=10, line_width=5, show_path=True, opacity=0.75, show_horizon=True, **kwargs)#

Enable horizon picking.

Helper for the enable_path_picking method to also show a ribbon surface along the picked path. Ribbon is saved under .picked_horizon.

Parameters:
  • callback (callable, optional) – When given, calls this callable after a pick is made. The entire picked path is passed as the only parameter to this callable.

  • normal (sequence[float], default: (0.0, 0.0, 1.0)) – The normal to the horizon surface’s projection plane.

  • width (float, optional) – The width of the horizon surface. Default behaviour will dynamically change the surface width depending on its length.

  • show_message (bool | str, default: True) – Show the message about how to use the horizon picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • color (ColorLike, default: "pink") – The color of the horizon surface if shown.

  • point_size (int, default: 10) – Size of picked points if show_horizon is True.

  • line_width (float, default: 5.0) – Thickness of path representation if show_horizon is True.

  • show_path (bool, default: True) – Show the picked path that the horizon is built from interactively.

  • opacity (float, default: 0.75) – The opacity of the horizon surface if shown.

  • show_horizon (bool, default: True) – Show the picked horizon surface interactively.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the picked path is interactively displayed.

enable_image_style()#

Set 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 dollies (a positional zoom) the camera

  • Middle mouse button pans the camera

  • Right mouse button dollies the camera

  • SHIFT Right Mouse triggers pick events

Examples

Create a simple scene with a plotter that has the Image interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_image_style()
>>> plotter.show()  
enable_joystick_actor_style()#

Set the interactive style to Joystick Actor.

Similar to the Joystick Camera interaction style, however in case of the Joystick Actor style the objects in the scene rather than the camera can be moved (rotated, panned, etc.). The position of the mouse relative to the center of the object determines the speed at which the object moves, so the object continues to move even if the mouse is 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.)

Examples

Create a simple scene with a plotter that has the Joystick Actor interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_joystick_actor_style()
>>> plotter.show()  
enable_joystick_style()#

Set the interactive style to Joystick Camera.

It 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, 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.)

Examples

Create a simple scene with a plotter that has the Joystick Camera interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_joystick_style()
>>> plotter.show()  
enable_lightkit(only_active=False)#

Enable the default light-kit lighting.

See: https://www.researchgate.net/publication/2926068_LightKit_A_lighting_system_for_effective_visualization

This will replace all pre-existing lights in the renderer.

Parameters:

only_active (bool, default: False) – If True, only change the active renderer. The default is that every renderer is affected.

Examples

Create a plotter without any lights and then enable the default light kit.

>>> import pyvista as pv
>>> pl = pv.Plotter(lighting=None)
>>> pl.enable_lightkit()
>>> actor = pl.add_mesh(pv.Cube(), show_edges=True)
>>> pl.show()
enable_mesh_picking(callback=None, show=True, show_message=True, style='wireframe', line_width=5, color='pink', font_size=18, left_clicking=False, use_actor=False, picker=PickerType.CELL, **kwargs)#

Enable picking of a mesh.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The mesh is input as the first parameter to this callable.

  • show (bool, default: True) – Show the selection interactively. Best when combined with left_clicking.

  • show_message (bool | str, default: True) – Show the message about how to use the mesh picking tool. If this is a string, that will be the message shown.

  • style (str, default: "wireframe") –

    Visualization style of the selection. One of the following:

    • 'surface'

    • 'wireframe'

    • 'points'

  • line_width (float, default: 5.0) – Thickness of selected mesh edges.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • left_clicking (bool, default: False) –

    When True, meshes can be picked by clicking the left mousebutton.

    Note

    If enabled, left-clicking will not display the bounding box around the picked point.

  • use_actor (bool, default: False) – If True, the callback will be passed the picked actor instead of the mesh object.

  • picker (str | PickerType, optional) –

    Choice of VTK picker class type:

    • 'hardware': Uses vtkHardwarePicker which is more performant for large geometries (default).

    • 'cell': Uses vtkCellPicker.

    • 'point': Uses vtkPointPicker which will snap to points on the surface of the mesh.

    • 'volume': Uses vtkVolumePicker.

**kwargsdict, optional

All remaining keyword arguments are used to control how the picked path is interactively displayed.

Returns:

vtk.vtkPropPicker – Property picker.

Examples

Add a sphere and a cube to a plot and enable mesh picking. Enable left_clicking to immediately start picking on the left click and disable showing the box. You can still press the p key to select meshes.

>>> import pyvista as pv
>>> mesh = pv.Sphere(center=(1, 0, 0))
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_mesh_picking()

See mesh_picking_example for a full example using this method.

enable_parallel_projection()#

Enable parallel projection.

The camera will have a parallel projection. Parallel projection is often useful when viewing images or 2D datasets.

See also

pyvista.Plotter.enable_2d_style

Examples

>>> import pyvista as pv
>>> from pyvista import demos
>>> pl = pv.demos.orientation_plotter()
>>> pl.enable_parallel_projection()
>>> pl.show()
enable_path_picking(callback=None, show_message=True, font_size=18, color='pink', point_size=10, line_width=5, show_path=True, tolerance=0.025, **kwargs)#

Enable picking at paths.

This is a convenience method for enable_point_picking to keep track of the picked points and create a line using those points.

The line is saved to the .picked_path attribute of this plotter

Parameters:
  • callback (callable, optional) – When given, calls this callable after a pick is made. The entire picked path is passed as the only parameter to this callable.

  • show_message (bool | str, default: True) – Show the message about how to use the point picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the size of the message.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • point_size (int, default: 10) – Size of picked points if show_path is True.

  • line_width (float, default: 5.0) – Thickness of path representation if show_path is True.

  • show_path (bool, default: True) – Show the picked path interactively.

  • tolerance (float, default: 0.025) – Specify tolerance for performing pick operation. Tolerance is specified as fraction of rendering window size. Rendering window size is measured across diagonal.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the picked path is interactively displayed.

enable_point_picking(callback=None, tolerance=0.025, left_clicking=False, picker=PickerType.POINT, show_message=True, font_size=18, color='pink', point_size=10, show_point=True, use_picker=False, pickable_window=False, clear_on_no_selection=True, **kwargs)#

Enable picking at points under the cursor.

Enable picking a point at the mouse location in the render view using the right mouse button. This point is saved to the .picked_point attribute on the plotter. Pass a callback that takes that point as an argument. The picked point can either be a point on the first intersecting mesh, or a point in the 3D window.

The picker choice will help determine how the point picking is performed.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a pick is made. The picked point is input as the first parameter to this callable.

  • tolerance (float, tolerance: 0.025) – Specify tolerance for performing pick operation. Tolerance is specified as fraction of rendering window size. Rendering window size is measured across diagonal. This is only valid for some choices of picker.

  • left_clicking (bool, default: False) – When True, points can be picked by clicking the left mouse button. Default is to use the right mouse button.

  • picker (str | PickerType, optional) –

    Choice of VTK picker class type:

    • 'hardware': Uses vtkHardwarePicker which is more performant for large geometries (default).

    • 'cell': Uses vtkCellPicker.

    • 'point': Uses vtkPointPicker which will snap to points on the surface of the mesh.

    • 'volume': Uses vtkVolumePicker.

  • show_message (bool | str, default: True) – Show the message about how to use the point picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the size of the message.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • point_size (int, default: 10) – Size of picked points if show_point is True.

  • show_point (bool, default: True) – Show the picked point after clicking.

  • use_picker (bool, default: False) – When True, the callback will also be passed the picker.

  • pickable_window (bool, default: False) – When True and the chosen picker supports it, points in the 3D window are pickable.

  • clear_on_no_selection (bool, default: True) – Clear the selections when no point is selected.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the picked point is interactively displayed.

Examples

Enable point picking with a custom message.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> _ = pl.add_mesh(pv.Cube(), pickable=False)
>>> pl.enable_point_picking(show_message='Pick a point')

See point_picking_example for a full example using this method.

enable_rectangle_picking(callback=None, show_message=True, font_size=18, start=False, show_frustum=False, style='wireframe', color='pink', **kwargs)#

Enable rectangle based picking at cells.

Press "r" to enable rectangle based selection. Press "r" again to turn it off.

Picking with the rectangle selection tool provides two values that are passed as the RectangleSelection object in the callback:

  1. RectangleSelection.viewport: the viewport coordinates of the selection rectangle.

  2. RectangleSelection.frustum: the full frustum made from the selection rectangle into the scene.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The RectangleSelection is the only passed argument containing the viewport coordinates of the selection and the projected frustum.

  • show_message (bool | str, default: True) – Show the message about how to use the cell picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • start (bool, default: True) – Automatically start the cell selection tool.

  • show_frustum (bool, default: False) – Show the frustum in the scene.

  • style (str, default: "wireframe") – Visualization style of the selection frustum. One of the following: style='surface', style='wireframe', or style='points'.

  • color (ColorLike, default: "pink") – The color of the selected frustum when shown.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the selection frustum is interactively displayed.

Examples

Add a mesh and a cube to a plot and enable cell picking.

>>> import pyvista as pv
>>> mesh = pv.Sphere(center=(1, 0, 0))
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_rectangle_picking()
enable_rectangle_through_picking(callback=None, show=True, style='wireframe', line_width=5, color='pink', show_message=True, font_size=18, start=False, show_frustum=False, **kwargs)#

Enable rectangle based cell picking through the scene.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The picked cells is the only passed argument.

  • show (bool, default: True) – Show the selection interactively.

  • style (str, default: "wireframe") – Visualization style of the selection frustum. One of the following: style='surface', style='wireframe', or style='points'.

  • line_width (float, default: 5.0) – Thickness of selected mesh edges.

  • color (ColorLike, default: "pink") – The color of the selected frustum when shown.

  • show_message (bool | str, default: True) – Show the message about how to use the cell picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • start (bool, default: True) – Automatically start the cell selection tool.

  • show_frustum (bool, default: False) – Show the frustum in the scene.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the selection frustum is interactively displayed.

enable_rectangle_visible_picking(callback=None, show=True, style='wireframe', line_width=5, color='pink', show_message=True, font_size=18, start=False, show_frustum=False, **kwargs)#

Enable rectangle based cell picking on visible surfaces.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The picked cells is the only passed argument.

  • show (bool, default: True) – Show the selection interactively.

  • style (str, default: "wireframe") – Visualization style of the selection frustum. One of the following: style='surface', style='wireframe', or style='points'.

  • line_width (float, default: 5.0) – Thickness of selected mesh edges.

  • color (ColorLike, default: "pink") – The color of the selected frustum when shown.

  • show_message (bool | str, default: True) – Show the message about how to use the cell picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • start (bool, default: True) – Automatically start the cell selection tool.

  • show_frustum (bool, default: False) – Show the frustum in the scene.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the selection frustum is interactively displayed.

enable_rubber_band_2d_style()#

Set the interactive style to Rubber Band 2D.

Camera rotation is not enabled with this interactor style. Zooming affects the camera’s parallel scale only, and assumes that the camera is in parallel projection mode. The style also allows to draw a rubber band using the left mouse button. All camera changes invoke StartInteractionEvent when the button is pressed, InteractionEvent when the mouse (or wheel) is moved, and EndInteractionEvent when the button is released. The bindings are as follows:

  • Left mouse: Select (invokes a SelectionChangedEvent).

  • Right mouse: Zoom.

  • Middle mouse: Pan.

  • Scroll wheel: Zoom.

Examples

Create a simple scene with a plotter that has the Rubber Band 2D interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_rubber_band_2d_style()
>>> plotter.show()  
enable_rubber_band_style()#

Set 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 the Trackball Camera style.

Examples

Create a simple scene with a plotter that has the Rubber Band Pick interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_rubber_band_style()
>>> plotter.show()  
enable_shadows()#

Enable shadows.

Examples

First, plot without shadows enabled (default)

>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> pl = pv.Plotter(lighting='none', window_size=(1000, 1000))
>>> light = pv.Light()
>>> light.set_direction_angle(20, -20)
>>> pl.add_light(light)
>>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
>>> _ = pl.add_mesh(pv.Box((-1.2, -1, -1, 1, -1, 1)))
>>> pl.show()

Now, enable shadows.

>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> pl = pv.Plotter(lighting='none', window_size=(1000, 1000))
>>> light = pv.Light()
>>> light.set_direction_angle(20, -20)
>>> pl.add_light(light)
>>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
>>> _ = pl.add_mesh(pv.Box((-1.2, -1, -1, 1, -1, 1)))
>>> pl.enable_shadows()
>>> pl.show()
enable_ssao(radius=0.5, bias=0.005, kernel_size=256, blur=True)#

Enable surface space ambient occlusion (SSAO).

SSAO can approximate shadows more efficiently than ray-tracing and produce similar results. Use this when you wish to plot the occlusion effect that nearby meshes have on each other by blocking nearby light sources.

See Kitware: Screen-Space Ambient Occlusion for more details

Parameters:
  • radius (float, default: 0.5) – Neighbor pixels considered when computing the occlusion.

  • bias (float, default: 0.005) – Tolerance factor used when comparing pixel depth.

  • kernel_size (int, default: 256) – Number of samples used. This controls the quality where a higher number increases the quality at the expense of computation time.

  • blur (bool, default: True) – Controls if occlusion buffer should be blurred before combining it with the color buffer.

Examples

Generate a pyvista.UnstructuredGrid with many tetrahedrons nearby each other and plot it without SSAO.

>>> import pyvista as pv
>>> ugrid = pv.ImageData(dimensions=(3, 2, 2)).to_tetrahedra(12)
>>> exploded = ugrid.explode()
>>> exploded.plot()

Enable SSAO with the default parameters.

>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(exploded)
>>> pl.enable_ssao()
>>> pl.show()
enable_stereo_render()#

Enable anaglyph stereo rendering.

Disable this with disable_stereo_render

Examples

Enable stereo rendering to show a cube as an anaglyph image.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.enable_stereo_render()
>>> pl.show()
enable_surface_point_picking(callback=None, show_message=True, font_size=18, color='pink', show_point=True, point_size=10, tolerance=0.025, pickable_window=False, left_clicking=False, picker=PickerType.CELL, use_picker=False, clear_on_no_selection=True, **kwargs)#

Enable picking of a point on the surface of a mesh.

Parameters:
  • callback (callable, optional) – When input, calls this callable after a selection is made. The mesh is input as the first parameter to this callable.

  • show_message (bool | str, default: True) – Show the message about how to use the mesh picking tool. If this is a string, that will be the message shown.

  • font_size (int, default: 18) – Sets the font size of the message.

  • color (ColorLike, default: "pink") – The color of the selected mesh when shown.

  • show_point (bool, default: True) – Show the selection interactively.

  • point_size (int, default: 10) – Size of picked points if show_point is True.

  • tolerance (float, default: 0.025) –

    Specify tolerance for performing pick operation. Tolerance is specified as fraction of rendering window size. Rendering window size is measured across diagonal.

    Warning

    This is ignored with the 'hardware' picker.

  • pickable_window (bool, default: False) – When True, points in the 3D window are pickable.

  • left_clicking (bool, default: False) –

    When True, meshes can be picked by clicking the left mousebutton.

    Note

    If enabled, left-clicking will not display the bounding box around the picked mesh.

  • picker (str | PickerType, optional) –

    Choice of VTK picker class type:

    • 'hardware': Uses vtkHardwarePicker which is more performant for large geometries (default).

    • 'cell': Uses vtkCellPicker.

    • 'point': Uses vtkPointPicker which will snap to points on the surface of the mesh.

    • 'volume': Uses vtkVolumePicker.

  • use_picker (bool, default: False) – When True, the callback will also be passed the picker.

  • clear_on_no_selection (bool, default: True) – Clear the selections when no point is selected.

  • **kwargs (dict, optional) – All remaining keyword arguments are used to control how the picked path is interactively displayed.

Notes

Picked point can be accessed from picked_point attribute.

Examples

Add a cube to a plot and enable cell picking.

>>> import pyvista as pv
>>> cube = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(cube)
>>> _ = pl.enable_surface_point_picking()

See surface_point_picking_example for a full example using this method.

enable_terrain_style(mouse_wheel_zooms=False, shift_pans=False)#

Set 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). Similar to the default Trackball Camera style and in contrast to the Joystick Camera style, movements of the mouse translate to movements of the camera.

Left mouse click rotates the camera around the focal point using both elevation and azimuth invocations on the camera. Left mouse motion in the horizontal direction results in azimuth motion; left mouse motion in the vertical direction results in elevation motion. Therefore, diagonal motion results in a combination of azimuth and elevation. (If the shift key is held during motion, then only one of elevation or azimuth is invoked, depending on the whether the mouse motion is primarily horizontal or vertical.) Middle mouse button pans the camera across the scene (again the shift key has a similar effect on limiting the motion to the vertical or horizontal direction. The right mouse is used to dolly towards or away from the focal point (zoom in or out). Panning and zooming behavior can be overridden to match the Trackball Camera style.

The class also supports some keypress events. The r key resets the camera. The e key invokes the exit callback and closes the plotter. The f key sets a new camera focal point and flies towards that point. The u key invokes the user event. The 3 key toggles between stereo and non-stero mode. The l key toggles on/off latitude/longitude markers that can be used to estimate/control position.

Parameters:
  • mouse_wheel_zooms (bool, default: False) – Whether to use the mouse wheel for zooming. By default zooming can be performed with right click and drag.

  • shift_pans (bool, default: False) – Whether shift + left mouse button pans the scene. By default shift + left mouse button rotates the view restricted to only horizontal or vertical movements, and panning is done holding down the middle mouse button.

Examples

Create a simple scene with a plotter that has the Terrain interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_terrain_style()
>>> plotter.show()  

Use controls that are closer to the default style:

>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_terrain_style(
...     mouse_wheel_zooms=True, shift_pans=True
... )
>>> plotter.show()  
enable_trackball_actor_style()#

Set the interactive style to Trackball Actor.

This allows to rotate actors around the scene. The controls are similar to the default Trackball Camera style, but movements transform specific objects under the mouse cursor.

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 objects around the axis connecting the camera with the their center. Alternatively, shift + left button pans.

Examples

Create a simple scene with a plotter that has the Trackball Actor interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_trackball_actor_style()
>>> plotter.show()  
enable_trackball_style()#

Set the interactive style to Trackball Camera.

The trackball camera is the default interactor style. Moving the mouse moves the camera around, leaving the scene intact.

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 the view around the viewing axis of the camera. Alternatively, ctrl + shift + left button or mouse wheel zooms, and shift + left button pans.

See also

pyvista.Plotter.enable_custom_trackball_style

A style that can be customized for mouse actions.

Examples

Create a simple scene with a plotter that has the Trackball Camera interactive style (which is also the default):

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_trackball_style()
>>> plotter.show()  
enable_zoom_style()#

Set 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.

Examples

Create a simple scene with a plotter that has the Rubber Band Zoom interactive style:

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Cube(center=(1, 0, 0)))
>>> _ = plotter.add_mesh(pv.Cube(center=(0, 1, 0)))
>>> plotter.show_axes()
>>> plotter.enable_zoom_style()
>>> plotter.show()  
export_gltf(filename, inline_data=True, rotate_scene=True, save_normals=True)#

Export the current rendering scene as a glTF file.

Visit https://gltf-viewer.donmccurdy.com/ for an online viewer.

See https://vtk.org/doc/nightly/html/classvtkGLTFExporter.html for limitations regarding the exporter.

Parameters:
  • filename (str) – Path to export the gltf file to.

  • inline_data (bool, default: True) – Sets if the binary data be included in the json file as a base64 string. When True, only one file is exported.

  • rotate_scene (bool, default: True) – Rotate scene to be compatible with the glTF specifications.

  • save_normals (bool, default: True) – Saves the point array 'Normals' as 'NORMAL' in the outputted scene.

Notes

The VTK exporter only supports pyvista.PolyData datasets. If the plotter contains any non-PolyData datasets, these will be converted in the plotter, leading to a copy of the data internally.

Examples

Output a simple point cloud represented as balls.

>>> import numpy as np
>>> import pyvista as pv
>>> rng = np.random.default_rng(seed=0)
>>> point_cloud = rng.random((100, 3))
>>> pdata = pv.PolyData(point_cloud)
>>> pdata['orig_sphere'] = np.arange(100)
>>> sphere = pv.Sphere(radius=0.02)
>>> pc = pdata.glyph(scale=False, geom=sphere, orient=False)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(
...     pc,
...     cmap='reds',
...     smooth_shading=True,
...     show_scalar_bar=False,
... )
>>> pl.export_gltf('balls.gltf')  
>>> pl.show()

Output the orientation plotter.

>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.export_gltf('orientation_plotter.gltf')  
>>> pl.show()
export_html(filename)#

Export this plotter as an interactive scene to a HTML file.

Parameters:

filename (str | Path) – Path to export the html file to.

Returns:

StringIO – If filename is None, returns the HTML as a StringIO object.

Notes

You will need trame installed.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.load_uniform()
>>> pl = pv.Plotter(shape=(1, 2))
>>> _ = pl.add_mesh(
...     mesh, scalars='Spatial Point Data', show_edges=True
... )
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(
...     mesh, scalars='Spatial Cell Data', show_edges=True
... )
>>> pl.export_html('pv.html')  
export_obj(filename)#

Export scene to OBJ format.

Parameters:

filename (str | Path) – Filename to export the scene to. Must end in '.obj'.

Examples

Export the scene to “scene.obj”

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.export_obj('scene.obj')  
export_vrml(filename)#

Export the current rendering scene as a VRML file.

See vtk.VRMLExporter for limitations regarding the exporter.

Parameters:

filename (str | Path) – Filename to export the scene to.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(examples.load_hexbeam())
>>> pl.export_vrml("sample")  
export_vtksz(filename='scene-export.vtksz', format='zip')#

Export this plotter as a VTK.js OfflineLocalView file.

The exported file can be viewed with the OfflineLocalView viewer available at https://kitware.github.io/vtk-js/examples/OfflineLocalView.html

Parameters:
  • filename (str | Path, optional) – Path to export the file to. Defaults to 'scene-export.vtksz'.

  • format (str, optional) – The format of the exported file. Defaults to 'zip'. Can be either 'zip' or 'json'.

Returns:

str – The exported filename.

fly_to(point)#

Move the current camera’s focal point to a position point.

The movement is animated over the number of frames specified in NumberOfFlyFrames. The LOD desired frame rate is used.

Parameters:

point (sequence[float]) – Point to fly to in the form of (x, y, z).

fly_to_mouse_position(focus=False)#

Focus on last stored mouse position.

generate_orbital_path(factor=3.0, n_points=20, viewup=None, shift=0.0)#

Generate an orbital path around the data scene.

Parameters:
  • factor (float, default: 3.0) – A scaling factor when building the orbital extent.

  • n_points (int, default: 20) – Number of points on the orbital path.

  • viewup (sequence[float], optional) – The normal to the orbital plane.

  • shift (float, default: 0.0) – Shift the plane up/down from the center of the scene by this amount.

Returns:

pyvista.PolyData – PolyData containing the orbital path.

Examples

Generate an orbital path around a sphere.

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Sphere())
>>> viewup = [0, 0, 1]
>>> orbit = plotter.generate_orbital_path(
...     factor=2.0, n_points=50, shift=0.0, viewup=viewup
... )

See orbiting_example for a full example using this method.

get_default_cam_pos(negative=False)#

Return the default focal points and viewup.

Uses ResetCamera to make a useful view.

Parameters:

negative (bool, default: False) – View from the opposite direction.

Returns:

list – List of camera position:

  • Position

  • Focal point

  • View up

get_image_depth(fill_value=nan, reset_camera_clipping_range=True)#

Return a depth image representing current render window.

Parameters:
  • fill_value (float, default: numpy.nan) – Fill value for points in image that do not include objects in scene. To not use a fill value, pass None.

  • reset_camera_clipping_range (bool, default: True) – Reset the camera clipping range to include data in view.

Returns:

pyvista.pyvista_ndarray – Image of depth values from camera orthogonal to image plane.

Notes

Values in image_depth are negative to adhere to a right-handed coordinate system.

Examples

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(pv.Sphere())
>>> plotter.show()
>>> zval = plotter.get_image_depth()
get_pick_position()#

Get the pick position or area.

Returns:

sequence – Picked position or area as (x0, y0, x1, y1).

hide_axes()#

Hide the axes orientation widget.

See also

show_axes

Show the axes orientation widget.

axes_enabled

Check if the axes orientation widget is enabled.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.hide_axes()
hide_axes_all()#

Hide the axes orientation widget in all renderers.

property image#

Return an image array of current render window.

Returns:

pyvista.pyvista_ndarray – Image array of current render window.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter(off_screen=True)
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.show()
>>> pl.image  
property image_depth#

Return a depth image representing current render window.

Helper attribute for get_image_depth.

property image_scale: int#

Get or set the scale factor when saving a screenshot.

This will scale up the screenshots taken of the render window to save a higher resolution image than what is rendered on screen.

Image sizes will be the window_size multiplied by this scale factor.

Returns:

int – Image scale factor.

Examples

Double the resolution of a screenshot.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.image_scale = 2
>>> pl.screenshot('screenshot.png')  

Set the image scale from Plotter.

>>> import pyvista as pv
>>> pl = pv.Plotter(image_scale=2)
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.screenshot('screenshot.png')  
image_scale_context(scale: int | None = None)#

Set the image scale in an isolated context.

Parameters:

scale (int, optional) – Integer scale factor. Defaults to pyvista.Plotter.image_scale.

import_3ds(filename)#

Import a 3DS file into the plotter.

Added in version 0.44.0.

Parameters:

filename (str | Path) – Path to the 3DS file.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> download_3ds_file = examples.download_3ds.download_iflamigm()
>>> pl = pv.Plotter()
>>> pl.import_3ds(download_3ds_file)
>>> pl.show()
import_gltf(filename, set_camera=True)#

Import a glTF file into the plotter.

See https://www.khronos.org/gltf/ for more information.

Parameters:
  • filename (str | Path) – Path to the glTF file.

  • set_camera (bool, default: True) – Set the camera viewing angle to one compatible with the default three.js perspective ('xy').

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> helmet_file = (
...     examples.gltf.download_damaged_helmet()
... )  
>>> texture = (
...     examples.hdr.download_dikhololo_night()
... )  
>>> pl = pv.Plotter()  
>>> pl.import_gltf(helmet_file)  
>>> pl.set_environment_texture(cubemap)  
>>> pl.camera.zoom(1.8)  
>>> pl.show()  

See load_gltf for a full example using this method.

import_obj(filename, filename_mtl=None)#

Import from .obj wavefront files.

Added in version 0.44.0.

Parameters:
  • filename (str | Path) – Path to the .obj file.

  • filename_mtl (str, optional) – Path to the .mtl file.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> download_obj_file = examples.download_room_surface_mesh(
...     load=False
... )
>>> pl = pv.Plotter()
>>> pl.import_obj(download_obj_file)
>>> pl.show()

Import an .obj file with a texture.

>>> from pathlib import Path
>>> filename = examples.download_doorman(load=False)
>>> pl = pv.Plotter()
>>> pl.import_obj(filename)
>>> pl.show(cpos="xy")
import_vrml(filename)#

Import a VRML file into the plotter.

Parameters:

filename (str | Path) – Path to the VRML file.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> sextant_file = (
...     examples.vrml.download_sextant()
... )  
>>> pl = pv.Plotter()  
>>> pl.import_vrml(sextant_file)  
>>> pl.show()  

See load_vrml_example for a full example using this method.

increment_point_size_and_line_width(increment)#

Increment point size and line width of all actors.

For every actor in the scene, increment both its point size and line width by the given value.

Parameters:

increment (float) – Amount to increment point size and line width.

isometric_view()#

Reset the camera to a default isometric view.

DEPRECATED: Please use view_isometric.

isometric_view_interactive()#

Set the current interactive render window to isometric view.

key_press_event(*args)#

Listen for key press event.

left_button_down(*args)#

Register the event for a left button down click.

property legend#

Legend actor.

There can only be one legend actor per renderer. If legend is None, there is no legend actor.

Returns:

vtk.vtkLegendBoxActor – Legend actor.

property length#

Return the length of the diagonal of the bounding box of the scene.

Link the views’ cameras.

Parameters:

views (int | tuple | list, default: 0) – If views is int, link the views to the given view index or if views is a tuple or a list, link the given views cameras.

Examples

Not linked view case.

>>> import pyvista as pv
>>> from pyvista import demos
>>> ocube = demos.orientation_cube()
>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.camera_position = 'yz'
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.show_axes()
>>> pl.show()

Linked view case.

>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.camera_position = 'yz'
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.show_axes()
>>> pl.link_views()
>>> pl.show()
property meshes#

Return plotter meshes.

Returns:

list[pyvista.DataSet | pyvista.MultiBlock] – List of mesh objects such as pyvista.PolyData, pyvista.UnstructuredGrid, etc.

open_gif(filename, loop=0, fps=10, palettesize=256, subrectangles=False, **kwargs)#

Open a gif file.

Requires imageio to be installed.

Parameters:
  • filename (str | Path) – Filename of the gif to open. Filename must end in "gif".

  • loop (int, default: 0) – The number of iterations. Default value of 0 loops indefinitely.

  • fps (float, default: 10) – The number of frames per second. If duration is not given, the duration for each frame is set to 1/fps.

  • palettesize (int, default: 256) – The number of colors to quantize the image to. Is rounded to the nearest power of two. Must be between 2 and 256.

  • subrectangles (bool, default: False) –

    If True, will try and optimize the GIF by storing only the rectangular parts of each frame that change with respect to the previous.

    Note

    Setting this to True may help reduce jitter in colorbars.

  • **kwargs (dict, optional) – See the documentation for imageio.get_writer() for additional kwargs.

Notes

Consider using pygifsicle to reduce the final size of the gif. See Optimizing a GIF using pygifsicle.

Examples

Open a gif file, setting the framerate to 8 frames per second and reducing the colorspace to 64.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.open_gif(
...     'movie.gif', fps=8, palettesize=64
... )  

See gif_movie_example for a full example using this method.

open_movie(filename, framerate=24, quality=5, **kwargs)#

Establish a connection to the ffmpeg writer.

Requires imageio to be installed.

Parameters:
  • filename (str | Path) – Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See imageio.get_writer().

  • framerate (int, default: 24) – Frames per second.

  • quality (int, default: 5) – Quality 10 is the top possible quality for any codec. The range is 0 - 10. Higher quality leads to a larger file.

  • **kwargs (dict, optional) – See the documentation for imageio.get_writer() for additional kwargs.

Notes

See the documentation for imageio.get_writer().

Examples

Open a MP4 movie and set the quality to maximum.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.open_movie('movie.mp4', quality=10)  
orbit_on_path(path=None, focus=None, step=0.5, viewup=None, write_frames=False, threaded=False, progress_bar=False)#

Orbit on the given path focusing on the focus point.

Parameters:
  • path (pyvista.PolyData) – Path of orbital points. The order in the points is the order of travel.

  • focus (sequence[float], optional) – The point of focus the camera. For example (0.0, 0.0, 0.0).

  • step (float, default: 0.5) – The timestep between flying to each camera position. Ignored when plotter.off_screen = True.

  • viewup (sequence[float], optional) – The normal to the orbital plane.

  • write_frames (bool, default: False) – Assume a file is open and write a frame on each camera view during the orbit.

  • threaded (bool, default: False) – Run this as a background thread. Generally used within a GUI (i.e. PyQt).

  • progress_bar (bool, default: False) – Show the progress bar when proceeding through the path. This can be helpful to show progress when generating movies with off_screen=True.

Examples

Plot an orbit around the earth. Save the gif as a temporary file.

>>> from pathlib import Path
>>> from tempfile import mkdtemp
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.load_globe()
>>> texture = examples.load_globe_texture()
>>> filename = Path(mkdtemp()) / 'orbit.gif'
>>> plotter = pv.Plotter(window_size=[300, 300])
>>> _ = plotter.add_mesh(
...     mesh, texture=texture, smooth_shading=True
... )
>>> plotter.open_gif(filename)
>>> viewup = [0, 0, 1]
>>> orbit = plotter.generate_orbital_path(
...     factor=2.0, n_points=24, shift=0.0, viewup=viewup
... )
>>> plotter.orbit_on_path(
...     orbit, write_frames=True, viewup=viewup, step=0.02
... )

See orbiting_example for a full example using this method.

property parallel_projection#

Return or set parallel projection state of active render window.

property parallel_scale#

Return or set parallel scale of active render window.

pick_click_position()#

Get corresponding click location in the 3D plot.

Returns:

tuple – Three item tuple with the 3D picked position.

pick_mouse_position()#

Get corresponding mouse location in the 3D plot.

Returns:

tuple – Three item tuple with the 3D picked position.

property pickable_actors#

Return or set the pickable actors.

When setting, this will be the list of actors to make pickable. All actors not in the list will be made unpickable. If actors is None, all actors will be made unpickable.

Returns:

list[pyvista.Actor] – List of actors.

Examples

Add two actors to a pyvista.Plotter, make one pickable, and then list the pickable actors.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> sphere_actor = pl.add_mesh(pv.Sphere())
>>> cube_actor = pl.add_mesh(
...     pv.Cube(), pickable=False, style='wireframe'
... )
>>> len(pl.pickable_actors)
1

Set the pickable actors to both actors.

>>> pl.pickable_actors = [sphere_actor, cube_actor]
>>> len(pl.pickable_actors)
2

Set the pickable actors to None.

>>> pl.pickable_actors = None
>>> len(pl.pickable_actors)
0
property picked_actor#

Return the picked mesh.

This returns the picked actor after selecting a mesh with enable_surface_point_picking or enable_mesh_picking.

Returns:

pyvista.Actor or None – Picked actor if available.

property picked_block_index#

Return the picked block index.

This returns the picked block index after selecting a point with enable_point_picking.

Returns:

int or None – Picked block if available. If -1, then a non-composite dataset was selected.

property picked_cell#

Return the picked cell.

This returns the picked cell after selecting a cell.

Returns:

pyvista.Cell or None – Picked cell if available.

property picked_cells#

Return the picked cells.

This returns the picked cells after selecting cells.

Returns:

pyvista.Cell or None – Picked cell if available.

property picked_mesh#

Return the picked mesh.

This returns the picked mesh after selecting a mesh with enable_surface_point_picking or enable_mesh_picking.

Returns:

pyvista.DataSet or None – Picked mesh if available.

property picked_point#

Return the picked point.

This returns the picked point after selecting a point.

Returns:

numpy.ndarray or None – Picked point if available.

plot_surface(geological_feature: BaseFeature, value: float | int | None = None, paint_with: BaseFeature | None = None, colour: str | None = 'red', cmap: str | None = None, opacity: float | None = None, vmin: float | None = None, vmax: float | None = None, pyvista_kwargs: dict = {'clim': [-156.0419960579127, 477.14689892134817]}, scalar_bar: bool = False, slicer: bool = False)#

Add an isosurface of a geological feature to the model

Parameters:
  • geological_feature (BaseFeature) – The geological feature to plot

  • value (Optional[Union[float, int, List[float]]], optional) – isosurface value, or list of values, by default average value of feature

  • paint_with (Optional[BaseFeature], optional) – Paint the surface with the value of another geological feature, by default None

  • colour (Optional[str], optional) – colour of the surface, by default “red”

  • cmap (Optional[str], optional) – matplotlib colourmap, by default None

  • opacity (Optional[float], optional) – opacity of the surface, by default None

  • vmin (Optional[float], optional) – minimum value of the colourmap, by default None

  • vmax (Optional[float], optional) – maximum value of the colourmap, by default None

  • pyvista_kwargs (dict, optional) – other parameters passed to Plotter.add_mesh, by default {}

remove_actor(actor, reset_camera=False, render=True)#

Remove an actor from the Renderer.

Parameters:
  • actor (str, vtk.vtkActor, list or tuple) – If the type is str, removes the previously added actor with the given name. If the type is vtk.vtkActor, removes the actor if it’s previously added to the Renderer. If list or tuple, removes iteratively each actor.

  • reset_camera (bool, optional) – Resets camera so all actors can be seen.

  • render (bool, optional) – Render upon actor removal. Set this to False to stop the render window from rendering when an actor is removed.

Returns:

boolTrue when actor removed. False when actor has not been removed.

Examples

Add two meshes to a plotter and then remove the sphere actor.

>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> pl = pv.Plotter()
>>> cube_actor = pl.add_mesh(pv.Cube(), show_edges=True)
>>> sphere_actor = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> _ = pl.remove_actor(cube_actor)
>>> pl.show()
remove_all_lights(only_active=False)#

Remove all lights from the scene.

Parameters:

only_active (bool, default: False) – If True, only remove lights from the active renderer. The default is that lights are stripped from every renderer.

Examples

Create a plotter and remove all lights after initialization. Note how the mesh rendered is completely flat

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> plotter.remove_all_lights()
>>> plotter.renderer.lights
[]
>>> _ = plotter.add_mesh(pv.Sphere(), show_edges=True)
>>> plotter.show()

Note how this differs from a plot with default lighting

>>> pv.Sphere().plot(show_edges=True, lighting=True)
remove_background_image()#

Remove the background image at the current renderer.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> actor = pl.add_mesh(pv.Sphere())
>>> pl.add_background_image(examples.mapfile, as_global=False)
>>> pl.subplot(0, 1)
>>> actor = pl.add_mesh(pv.Cube())
>>> pl.add_background_image(examples.mapfile, as_global=False)
>>> pl.remove_background_image()
>>> pl.show()
remove_blurring()#

Remove a single blurring pass.

You will need to run this multiple times to remove all blurring passes.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.add_blurring()
>>> pl.remove_blurring()
>>> pl.show()
remove_bounding_box(render=True)#

Remove bounding box.

Parameters:

render (bool, default: True) – Trigger a render once the bounding box is removed.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_bounding_box()
>>> pl.remove_bounding_box()
remove_bounds_axes()#

Remove bounds axes.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.show_bounds(grid='front', location='outer')
>>> pl.subplot(0, 1)
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.show_bounds(grid='front', location='outer')
>>> actor = pl.remove_bounds_axes()
>>> pl.show()
remove_chart(chart_or_index)#

Remove a chart from this renderer.

Parameters:

chart_or_index (Chart or int) – Either the chart to remove from this renderer or its index in the collection of charts.

Examples

First define a function to add two charts to a renderer.

>>> import pyvista as pv
>>> def plotter_with_charts():
...     pl = pv.Plotter()
...     pl.background_color = 'w'
...     chart_left = pv.Chart2D(size=(0.5, 1))
...     _ = chart_left.line([0, 1, 2], [2, 1, 3])
...     pl.add_chart(chart_left)
...     chart_right = pv.Chart2D(size=(0.5, 1), loc=(0.5, 0))
...     _ = chart_right.line([0, 1, 2], [3, 1, 2])
...     pl.add_chart(chart_right)
...     return pl, chart_left, chart_right
...
>>> pl, *_ = plotter_with_charts()
>>> pl.show()

Now reconstruct the same plotter but remove the right chart by index.

>>> pl, *_ = plotter_with_charts()
>>> pl.remove_chart(1)
>>> pl.show()

Finally, remove the left chart by reference.

>>> pl, chart_left, chart_right = plotter_with_charts()
>>> pl.remove_chart(chart_left)
>>> pl.show()
remove_environment_texture()#

Remove the environment texture.

Examples

>>> from pyvista import examples
>>> import pyvista as pv
>>> pl = pv.Plotter(lighting=None)
>>> cubemap = examples.download_sky_box_cube_map()
>>> _ = pl.add_mesh(
...     pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
... )
>>> pl.set_environment_texture(cubemap)
>>> pl.remove_environment_texture()
>>> pl.camera_position = 'xy'
>>> pl.show()
remove_floors(clear_kwargs=True, render=True)#

Remove all floor actors.

Parameters:
  • clear_kwargs (bool, default: True) – Clear default floor arguments.

  • render (bool, default: True) – Render upon removing the floor.

Examples

Add a floor below a sphere, remove it, and then plot it.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.add_floor()
>>> pl.remove_floors()
>>> pl.show()
remove_legend(render=True)#

Remove the legend actor.

Parameters:

render (bool, default: True) – Render upon actor removal. Set this to False to stop the render window from rendering when a the legend is removed.

Examples

>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, label='sphere')
>>> _ = pl.add_legend()
>>> pl.remove_legend()
remove_scalar_bar(title=None, render=True)#

Remove a scalar bar.

Parameters:
  • title (str, optional) – Title of the scalar bar to remove. Required if there is more than one scalar bar.

  • render (bool, default: True) – Render upon scalar bar removal. Set this to False to stop the render window from rendering when a scalar bar is removed.

Examples

Remove a scalar bar from a plotter.

>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> mesh['data'] = mesh.points[:, 2]
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, cmap='coolwarm')
>>> pl.remove_scalar_bar()
>>> pl.show()
render()#

Render the main window.

Will not render until show has been called.

Any render callbacks added with add_on_render_callback() and the render_event=False option set will still execute on any call.

property render_window#

Access the vtkRenderWindow attached to this plotter.

If the plotter is closed, this will return None.

Returns:

vtk.vtkRenderWindow or None – Render window if the plotter is not closed.

Notes

Subclass must set ren_win on initialization.

property renderer#

Return the active renderer.

Returns:

pyvista.Renderer – Active render.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.renderer
<Renderer(...) at ...>
reset_camera(render=True, bounds=None)#

Reset the camera of the active render window.

The camera slides along the vector defined from camera position to focal point until all of the actors can be seen.

Parameters:
  • render (bool, default: True) – Trigger a render after resetting the camera.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

Add a mesh and place the camera position too close to the mesh. Then reset the camera and show the mesh.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.set_position((0, 0.1, 0.1))
>>> pl.reset_camera()
>>> pl.show()
reset_camera_clipping_range()#

Reset camera clipping planes.

reset_key_events()#

Reset all of the key press events to their defaults.

rotate(angles: ndarray)#

Rotate the camera by the given angles order is roll, azimuth, elevation as defined by pyvista

Parameters:

angles (np.ndarray) – roll, azimuth, elevation

save_graphic(filename, title='PyVista Export', raster=True, painter=True)#

Save a screenshot of the rendering window as a graphic file.

This can be helpful for publication documents.

The supported formats are:

  • '.svg'

  • '.eps'

  • '.ps'

  • '.pdf'

  • '.tex'

Parameters:
  • filename (str) – Path to fsave the graphic file to.

  • title (str, default: "PyVista Export") – Title to use within the file properties.

  • raster (bool, default: True) – Attempt to write 3D properties as a raster image.

  • painter (bool, default: True) – Configure the exporter to expect a painter-ordered 2D rendering, that is, a rendering at a fixed depth where primitives are drawn from the bottom up.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(examples.load_airplane(), smooth_shading=True)
>>> _ = pl.add_background_image(examples.mapfile)
>>> pl.save_graphic("img.svg")  
property scalar_bar#

First scalar bar (kept for backwards compatibility).

Returns:

vtk.vtkScalarBarActor – First scalar bar actor.

property scalar_bars#

Scalar bars.

Returns:

pyvista.ScalarBars – Scalar bar object.

Examples

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere['Data'] = sphere.points[:, 2]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere)
>>> plotter.scalar_bars
Scalar Bar Title     Interactive
"Data"               False

Select a scalar bar actor based on the title of the bar.

>>> plotter.scalar_bars['Data']
<vtkmodules.vtkRenderingAnnotation.vtkScalarBarActor(...) at ...>
property scale#

Return the scaling of the active renderer.

screenshot(filename=None, transparent_background=None, return_img=True, window_size=None, scale=None)#

Take screenshot at current camera position.

Parameters:
  • filename (str | Path | io.BytesIO, optional) – Location to write image to. If None, no image is written.

  • transparent_background (bool, optional) – Whether to make the background transparent. The default is looked up on the plotter’s theme.

  • return_img (bool, default: True) – If True, a numpy.ndarray of the image will be returned.

  • window_size (sequence[int], optional) – Set the plotter’s size to this (width, height) before taking the screenshot.

  • scale (int, optional) – Set the factor to scale the window size to make a higher resolution image. If None this will use the image_scale property on this plotter which defaults to one.

Returns:

pyvista.pyvista_ndarray – Array containing pixel RGB and alpha. Sized:

  • [Window height x Window width x 3] if transparent_background is set to False.

  • [Window height x Window width x 4] if transparent_background is set to True.

Examples

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plotter = pv.Plotter(off_screen=True)
>>> actor = plotter.add_mesh(sphere)
>>> plotter.screenshot('screenshot.png')  
set_background(color, top=None, right=None, side=None, corner=None, all_renderers=True)#

Set the background color.

Parameters:
  • color (ColorLike, optional) –

    Either a string, rgb list, or hex color string. Defaults to current theme parameters. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • top (ColorLike, optional) – If given, this will enable a gradient background where the color argument is at the bottom and the color given in top will be the color at the top of the renderer.

  • right (ColorLike, optional) – If given, this will enable a gradient background where the color argument is at the left and the color given in right will be the color at the right of the renderer.

  • side (ColorLike, optional) – If given, this will enable a gradient background where the color argument is at the center and the color given in side will be the color at the side of the renderer.

  • corner (ColorLike, optional) – If given, this will enable a gradient background where the color argument is at the center and the color given in corner will be the color at the corner of the renderer.

  • all_renderers (bool, default: True) – If True, applies to all renderers in subplots. If False, then only applies to the active renderer.

Examples

Set the background color to black.

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> plotter.set_background('black')
>>> plotter.background_color
Color(name='black', hex='#000000ff', opacity=255)
>>> plotter.close()

Set the background color at the bottom to black and white at the top. Display a cone as well.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Cone())
>>> pl.set_background('black', top='white')
>>> pl.show()
set_chart_interaction(interactive, toggle=False)#

Set or toggle interaction with charts for the active renderer.

Interaction with other charts in other renderers is disabled. Interaction with other charts in the active renderer is only disabled when toggle is False.

Parameters:
  • interactive (bool | Chart | int | sequence[Chart] | sequence[int]) –

    Following parameter values are accepted:

    • A boolean to enable (True) or disable (False) interaction with all charts in the active renderer.

    • The chart or its index to enable interaction with. Interaction with multiple charts can be enabled by passing a list of charts or indices.

  • toggle (bool, default: False) – Instead of enabling interaction with the provided chart(s), interaction with the provided chart(s) is toggled. Only applicable when interactive is not a boolean.

Returns:

list of Chart – The list of all interactive charts for the active renderer.

set_color_cycler(color_cycler, all_renderers=True)#

Set or reset the color cycler.

This color cycler is iterated over by each sequential add_mesh() call to set the default color of the dataset being plotted.

When setting, the value must be either a list of color-like objects, or a cycler of color-like objects. If the value passed is a single string, it must be one of:

  • 'default' - Use the default color cycler (matches matplotlib’s default)

  • 'matplotlib - Dynamically get matplotlib’s current theme’s color cycler.

  • 'all' - Cycle through all of the available colors in pyvista.plotting.colors.hexcolors

Setting to None will disable the use of the color cycler on this renderer.

Parameters:
  • color_cycler (str | cycler.Cycler | sequence[ColorLike]) – The colors to cycle through.

  • all_renderers (bool, default: True) – If True, applies to all renderers in subplots. If False, then only applies to the active renderer.

Examples

Set the default color cycler to iterate through red, green, and blue.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.set_color_cycler(['red', 'green', 'blue'])
>>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0)))  # red
>>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))  # green
>>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0)))  # blue
>>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0)))  # red again
>>> pl.show()
set_environment_texture(texture, is_srgb=False)#

Set the environment texture used for image based lighting.

This texture is supposed to represent the scene background. If it is not a cubemap, the texture is supposed to represent an equirectangular projection. If used with raytracing backends, the texture must be an equirectangular projection and must be constructed with a valid vtk.vtkImageData.

Parameters:
  • texture (pyvista.Texture) – Texture.

  • is_srgb (bool, default: False) – If the texture is in sRGB color space, set the color flag on the texture or set this parameter to True. Textures are assumed to be in linear color space by default.

Examples

Add a skybox cubemap as an environment texture and show that the lighting from the texture is mapped on to a sphere dataset. Note how even when disabling the default lightkit, the scene lighting will still be mapped onto the actor.

>>> from pyvista import examples
>>> import pyvista as pv
>>> pl = pv.Plotter(lighting=None)
>>> cubemap = examples.download_sky_box_cube_map()
>>> _ = pl.add_mesh(
...     pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
... )
>>> pl.set_environment_texture(cubemap)
>>> pl.camera_position = 'xy'
>>> pl.show()
set_focus(point)#

Set focus to a point.

Parameters:

point (sequence[float]) – Cartesian point to focus on in the form of [x, y, z].

Examples

>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> _ = pl.add_point_labels([mesh.points[1]], ["Focus"])
>>> _ = pl.camera  # this initializes the camera
>>> pl.set_focus(mesh.points[1])
>>> pl.show()
set_position(point, reset=False, render=True)#

Set camera position to a point.

Parameters:
  • point (sequence) – Cartesian point to focus on in the form of [x, y, z].

  • reset (bool, default: False) – Whether to reset the camera after setting the camera position.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the position.

Examples

Move the camera far away to [7, 7, 7].

>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> pl.set_position([7, 7, 7])
>>> pl.show()
set_scale(xscale=None, yscale=None, zscale=None, reset_camera=True, render=True)#

Scale all the actors in the scene.

Scaling in performed independently on the X, Y and z-axis. A scale of zero is illegal and will be replaced with one.

Warning

Setting the scale on the renderer is a convenience method to individually scale each of the actors in the scene. If a scale was set on an actor previously, it will be reset to the scale of this Renderer.

Parameters:
  • xscale (float, optional) – Scaling in the x direction. Default is None, which does not change existing scaling.

  • yscale (float, optional) – Scaling in the y direction. Default is None, which does not change existing scaling.

  • zscale (float, optional) – Scaling in the z direction. Default is None, which does not change existing scaling.

  • reset_camera (bool, default: True) – Resets camera so all actors can be seen.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the scale.

Examples

Set the scale in the z direction to be 2 times that of nominal. Leave the other axes unscaled.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.set_scale(zscale=2)
>>> _ = pl.add_mesh(pv.Sphere())  # perfect sphere
>>> pl.show()
set_viewup(vector, reset=True, render=True)#

Set camera viewup vector.

Parameters:
  • vector (sequence[float]) – New camera viewup vector.

  • reset (bool, default: True) – Whether to reset the camera after setting the camera position.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the viewup.

Examples

Look from the top down by setting view up to [0, 1, 0]. Notice how the y-axis appears vertical.

>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.set_viewup([0, 1, 0])
>>> pl.show()
property shape: tuple[int] | tuple[int, int]#

Return the shape of the plotter.

Returns:

tuple[int] | tuple[int, int] – Shape of the plotter.

Examples

Return the plotter shape.

>>> import pyvista as pv
>>> plotter = pv.Plotter(shape=(2, 2))
>>> plotter.shape
(2, 2)
show(title=None, window_size=None, interactive=True, auto_close=None, interactive_update=False, full_screen=None, screenshot=False, return_img=False, cpos=None, jupyter_backend=None, return_viewer=False, return_cpos=None, before_close_callback=None, **kwargs)#

Display the plotting window.

Parameters:
  • title (str, optional) – Title of plotting window. Defaults to pyvista.global_theme.title.

  • window_size (list, optional) – Window size in pixels. Defaults to pyvista.global_theme.window_size.

  • interactive (bool, optional) – Enabled by default. Allows user to pan and move figure. Defaults to pyvista.global_theme.interactive.

  • auto_close (bool, optional) – Exits plotting session when user closes the window when interactive is True. Defaults to pyvista.global_theme.auto_close.

  • interactive_update (bool, default: False) – Allows user to non-blocking draw, user should call Plotter.update() in each iteration.

  • full_screen (bool, optional) – Opens window in full screen. When enabled, ignores window_size. Defaults to pyvista.global_theme.full_screen.

  • screenshot (str | Path | io.BytesIO | bool, default: False) – Take a screenshot of the initial state of the plot. If a string, it specifies the path to which the screenshot is saved. If True, the screenshot is returned as an array. For interactive screenshots it’s recommended to first call show() with auto_close=False to set the scene, then save the screenshot in a separate call to show() or Plotter.screenshot(). See also the before_close_callback parameter for an alternative.

  • return_img (bool, default: False) – Returns a numpy array representing the last image along with the camera position.

  • cpos (sequence[sequence[float]], optional) – The camera position. You can also set this with Plotter.camera_position.

  • jupyter_backend (str, optional) –

    Jupyter notebook plotting backend to use. One of the following:

    • 'none' : Do not display in the notebook.

    • 'static' : Display a static figure.

    • 'trame' : Display a dynamic figure with Trame.

    • 'html' : Use an ebeddable HTML scene.

    This can also be set globally with pyvista.set_jupyter_backend().

    A dictionary jupyter_kwargs can also be passed to further configure how the backend displays.

  • return_viewer (bool, default: False) – Return the jupyterlab viewer, scene, or display object when plotting with Jupyter notebook. When False and within a Jupyter environment, the scene will be immediately shown within the notebook. Set this to True to return the scene instead.

  • return_cpos (bool, optional) – Return the last camera position from the render window when enabled. Default based on theme setting. See pyvista.plotting.themes.Theme.return_cpos.

  • before_close_callback (Callable, optional) –

    Callback that is called before the plotter is closed. The function takes a single parameter, which is the plotter object before it closes. An example of use is to capture a screenshot after interaction:

    def fun(plotter):
        plotter.screenshot('file.png')
    

  • **kwargs (dict, optional) – Developer keyword arguments.

Returns:

  • cpos (list) – List of camera position, focal point, and view up. Returned only when return_cpos=True or set in the default global or plot theme.

  • image (np.ndarray) – Numpy array of the last image when either return_img=True or screenshot=True is set. Optionally contains alpha values. Sized:

    • [Window height x Window width x 3] if the theme sets transparent_background=False.

    • [Window height x Window width x 4] if the theme sets transparent_background=True.

  • widget (ipywidgets.Widget) – IPython widget when return_viewer=True.

Notes

Please use the q-key to close the plotter as some operating systems (namely Windows) will experience issues saving a screenshot if the exit button in the GUI is pressed.

Examples

Simply show the plot of a mesh.

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.show()

Take a screenshot interactively. Screenshot will be of the first image shown, so use the first call with auto_close=False to set the scene before taking the screenshot.

>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.show(auto_close=False)  
>>> pl.show(screenshot='my_image.png')  

Obtain the camera position when using show.

>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.show(return_cpos=True)  
[(2.223005211686484, -0.3126909484828709, 2.4686209867735065),
(0.0, 0.0, 0.0),
(-0.6839951597283509, -0.47207319712073137, 0.5561452310578585)]
show_axes()#

Show the axes orientation widget.

See also

add_axes

Similar method with additional options.

hide_axes

Hide the axes orientation widget.

axes_enabled

Check if the axes orientation widget is enabled.

add_axes_at_origin

Add a pyvista.AxesActor to the origin of a scene.

Examples

>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.show_axes()
show_axes_all()#

Show the axes orientation widget in all renderers.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>>
>>> mesh = examples.load_globe()
>>> texture = examples.load_globe_texture()
>>>
>>> # create multi-window plot (1 row, 2 columns)
>>> pl = pv.Plotter(shape=(1, 2))
>>>
>>> # activate subplot 1 and add a mesh
>>> pl.subplot(0, 0)
>>> _ = pl.add_mesh(mesh, texture=texture)
>>>
>>> # activate subplot 2 and add a mesh
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(examples.load_airplane())
>>>
>>> # show the axes orientation widget in all subplots
>>> pl.show_axes_all()
>>>
>>> # display the window
>>> pl.show()
show_bounds(mesh=None, bounds=None, axes_ranges=None, show_xaxis=True, show_yaxis=True, show_zaxis=True, show_xlabels=True, show_ylabels=True, show_zlabels=True, bold=True, font_size=None, font_family=None, color=None, xtitle='X Axis', ytitle='Y Axis', ztitle='Z Axis', n_xlabels=5, n_ylabels=5, n_zlabels=5, use_2d=False, grid=None, location='closest', ticks=None, all_edges=False, corner_factor=0.5, fmt=None, minor_ticks=False, padding=0.0, use_3d_text=True, render=None, **kwargs)#

Add bounds axes.

Shows the bounds of the most recent input mesh unless mesh is specified.

Parameters:
  • mesh (pyvista.DataSet | pyvista.MultiBlock, optional) – Input mesh to draw bounds axes around.

  • bounds (sequence[float], optional) – Bounds to override mesh bounds in the form [xmin, xmax, ymin, ymax, zmin, zmax].

  • axes_ranges (sequence[float], optional) –

    When set, these values override the values that are shown on the axes. This can be useful when plotting scaled datasets or if you wish to manually display different values. These values must be in the form:

    [xmin, xmax, ymin, ymax, zmin, zmax].

  • show_xaxis (bool, default: True) – Makes x-axis visible.

  • show_yaxis (bool, default: True) – Makes y-axis visible.

  • show_zaxis (bool, default: True) – Makes z-axis visible.

  • show_xlabels (bool, default: True) – Shows X labels.

  • show_ylabels (bool, default: True) – Shows Y labels.

  • show_zlabels (bool, default: True) – Shows Z labels.

  • bold (bool, default: True) – Bolds axis labels and numbers.

  • font_size (float, optional) – Sets the size of the label font. Defaults to pyvista.global_theme.font.size.

  • font_family (str, optional) – Font family. Must be either 'courier', 'times', or 'arial'. Defaults to pyvista.global_theme.font.family.

  • color (ColorLike, optional) –

    Color of all labels and axis titles. Defaults to pyvista.global_theme.font.color.

    Either a string, RGB list, or hex color string. For example:

    • color='white'

    • color='w'

    • color=[1.0, 1.0, 1.0]

    • color='#FFFFFF'

  • xtitle (str, default: "X Axis") – Title of the x-axis. Default "X Axis".

  • ytitle (str, default: "Y Axis") – Title of the y-axis. Default "Y Axis".

  • ztitle (str, default: "Z Axis") – Title of the z-axis. Default "Z Axis".

  • n_xlabels (int, default: 5) – Number of labels for the x-axis.

  • n_ylabels (int, default: 5) – Number of labels for the y-axis.

  • n_zlabels (int, default: 5) – Number of labels for the z-axis.

  • use_2d (bool, default: False) – This can be enabled for smoother plotting.

  • grid (bool or str, optional) – Add grid lines to the backface (True, 'back', or 'backface') or to the frontface ('front', 'frontface') of the axes actor.

  • location (str, default: "closest") – Set how the axes are drawn: either static ('all'), closest triad ('front', 'closest', 'default'), furthest triad ('back', 'furthest'), static closest to the origin ('origin'), or outer edges ('outer') in relation to the camera position.

  • ticks (str, optional) – Set how the ticks are drawn on the axes grid. Options include: 'inside', 'outside', 'both'.

  • all_edges (bool, default: False) – Adds an unlabeled and unticked box at the boundaries of plot. Useful for when wanting to plot outer grids while still retaining all edges of the boundary.

  • corner_factor (float, default: 0.5) – If all_edges, this is the factor along each axis to draw the default box. Default shows the full box.

  • fmt (str, optional) – A format string defining how tick labels are generated from tick positions. A default is looked up on the active theme.

  • minor_ticks (bool, default: False) – If True, also plot minor ticks on all axes.

  • padding (float, default: 0.0) – An optional percent padding along each axial direction to cushion the datasets in the scene from the axes annotations. Defaults no padding.

  • use_3d_text (bool, default: True) – Use vtkTextActor3D for titles and labels.

  • render (bool, optional) – If the render window is being shown, trigger a render after showing bounds.

  • **kwargs (dict, optional) – Deprecated keyword arguments.

Returns:

vtk.vtkCubeAxesActor – Bounds actor.

Examples

>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = pv.Sphere()
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(mesh)
>>> actor = plotter.show_bounds(
...     grid='front',
...     location='outer',
...     all_edges=True,
... )
>>> plotter.show()

Control how many labels are displayed.

>>> mesh = examples.load_random_hills()
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(
...     mesh, cmap='terrain', show_scalar_bar=False
... )
>>> actor = plotter.show_bounds(
...     grid='back',
...     location='outer',
...     ticks='both',
...     n_xlabels=2,
...     n_ylabels=2,
...     n_zlabels=2,
...     xtitle='Easting',
...     ytitle='Northing',
...     ztitle='Elevation',
... )
>>> plotter.show()

Hide labels, but still show axis titles.

>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(
...     mesh, cmap='terrain', show_scalar_bar=False
... )
>>> actor = plotter.show_bounds(
...     grid='back',
...     location='outer',
...     ticks='both',
...     show_xlabels=False,
...     show_ylabels=False,
...     show_zlabels=False,
...     xtitle='Easting',
...     ytitle='Northing',
...     ztitle='Elevation',
... )
>>> plotter.show()
show_grid(**kwargs)#

Show grid lines and bounds axes labels.

A wrapped implementation of show_bounds() to change default behavior to use grid lines and showing the axes labels on the outer edges.

This is intended to be similar to matplotlib.pyplot.grid().

Parameters:

**kwargs (dict, optional) – See Renderer.show_bounds() for additional keyword arguments.

Returns:

vtk.vtkAxesActor – Bounds actor.

Examples

>>> import pyvista as pv
>>> mesh = pv.Cone()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.show_grid()
>>> pl.show()
store_click_position(*args)#

Store click position in viewport coordinates.

store_mouse_position(*args)#

Store mouse position.

subplot(index_row, index_column=None)#

Set the active subplot.

Parameters:
  • index_row (int) – Index of the subplot to activate along the rows.

  • index_column (int, optional) – Index of the subplot to activate along the columns.

Examples

Create a 2 wide plot and set the background of right-hand plot to orange. Add a cube to the left plot and a sphere to the right.

>>> import pyvista as pv
>>> pl = pv.Plotter(shape=(1, 2))
>>> actor = pl.add_mesh(pv.Cube())
>>> pl.subplot(0, 1)
>>> actor = pl.add_mesh(pv.Sphere())
>>> pl.set_background('orange', all_renderers=False)
>>> pl.show()
property suppress_rendering#

Get or set whether to suppress render calls.

Returns:

boolTrue when rendering is suppressed.

property theme#

Return or set the theme used for this plotter.

Returns:

pyvista.Theme – Theme of this plotter.

Examples

Use the dark theme for a plotter.

>>> import pyvista as pv
>>> from pyvista import themes
>>> pl = pv.Plotter()
>>> pl.theme = themes.DarkTheme()
>>> actor = pl.add_mesh(pv.Sphere())
>>> pl.show()
track_click_position(callback=None, side='right', double=False, viewport=False)#

Keep track of the click position.

By default, it only tracks right clicks.

Parameters:
  • callback (callable, optional) – A callable method that will use the click position. Passes the click position as a length two tuple.

  • side (str, default: "right") – The mouse button to track (either 'left' or 'right'). Also accepts 'r' or 'l'.

  • double (bool, default: False) – Track single clicks if False, double clicks if True. Defaults to single clicks.

  • viewport (bool, default: False) – If True, uses the normalized viewport coordinate system (values between 0.0 and 1.0 and support for HiDPI) when passing the click position to the callback.

track_mouse_position()#

Keep track of the mouse position.

This will potentially slow down the interactor. No callbacks supported here - use pyvista.Plotter.track_click_position() instead.

Unlink the views’ cameras.

Parameters:

views (int | tuple | list, optional) – If views is None unlink all the views, if views is int unlink the selected view’s camera or if views is a tuple or a list, unlink the given views cameras.

untrack_click_position(side='right')#

Stop tracking the click position.

Parameters:

side (str, optional) – The mouse button to stop tracking (either 'left' or 'right'). Default is 'right'. Also accepts 'r' or 'l'.

untrack_mouse_position()#

Stop tracking the mouse position.

update(stime=1, force_redraw=True)#

Update window, redraw, process messages query.

Parameters:
  • stime (int, default: 1) – Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds.

  • force_redraw (bool, default: True) – Call render immediately.

update_bounds_axes()#

Update the bounds axes of the render window.

update_coordinates(points, mesh=None, render=True)#

Update the points of an object in the plotter.

Deprecated since version 0.43.0: This method is deprecated and will be removed in a future version of PyVista. It is functionally equivalent to directly modifying the points of a mesh in-place.

# Modify the points in place
mesh.points = points
# Explicitly call render if needed
plotter.render()
Parameters:
  • points (np.ndarray) – Points to replace existing points.

  • mesh (vtk.PolyData | vtk.UnstructuredGrid, optional) – Object that has already been added to the Plotter. If None, uses last added mesh.

  • render (bool, default: True) – Force a render when True.

update_scalar_bar_range(clim, name=None)#

Update the value range of the active or named scalar bar.

Parameters:
  • clim (sequence[float]) – The new range of scalar bar. For example [-1, 2].

  • name (str, optional) – The title of the scalar bar to update.

update_scalars(scalars, mesh=None, render=True)#

Update scalars of an object in the plotter.

Deprecated since version 0.43.0: This method is deprecated and will be removed in a future version of PyVista. It is functionally equivalent to directly modifying the scalars of a mesh in-place.

# Modify the points in place
mesh["my scalars"] = values
# Explicitly call render if needed
plotter.render()
Parameters:
  • scalars (sequence) – Scalars to replace existing scalars.

  • mesh (vtk.PolyData | vtk.UnstructuredGrid, optional) – Object that has already been added to the Plotter. If None, uses last added mesh.

  • render (bool, default: True) – Force a render when True.

view_isometric(negative=False, render=True, bounds=None)#

Reset the camera to a default isometric view.

The view will show all the actors in the scene.

Parameters:
  • negative (bool, default: False) – View from the other isometric direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

Isometric view.

>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.view_isometric()
>>> pl.show()

Negative isometric view.

>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.view_isometric(negative=True)
>>> pl.show()
view_vector(vector, viewup=None, render=True, bounds=None)#

Point the camera in the direction of the given vector.

Parameters:
  • vector (sequence[float]) – Direction to point the camera in.

  • viewup (sequence[float], optional) – Sequence describing the view up of the camera.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

view_xy(negative=False, render=True, bounds=None)#

View the XY plane.

Parameters:
  • negative (bool, default: False) – View from the opposite direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

View the XY plane of a built-in mesh example.

>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_xy()
>>> pl.show()
view_xz(negative=False, render=True, bounds=None)#

View the XZ plane.

Parameters:
  • negative (bool, default: False) – View from the opposite direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

View the XZ plane of a built-in mesh example.

>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_xz()
>>> pl.show()
view_yx(negative=False, render=True, bounds=None)#

View the YX plane.

Parameters:
  • negative (bool, default: False) – View from the opposite direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

View the YX plane of a built-in mesh example.

>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_yx()
>>> pl.show()
view_yz(negative=False, render=True, bounds=None)#

View the YZ plane.

Parameters:
  • negative (bool, default: False) – View from the opposite direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

View the YZ plane of a built-in mesh example.

>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_yz()
>>> pl.show()
view_zx(negative=False, render=True, bounds=None)#

View the ZX plane.

Parameters:
  • negative (bool, default: False) – View from the opposite direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

View the ZX plane of a built-in mesh example.

>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_zx()
>>> pl.show()
view_zy(negative=False, render=True, bounds=None)#

View the ZY plane.

Parameters:
  • negative (bool, default: False) – View from the opposite direction.

  • render (bool, default: True) – If the render window is being shown, trigger a render after setting the camera position.

  • bounds (iterable(int), optional) – Automatically set up the camera based on a specified bounding box (xmin, xmax, ymin, ymax, zmin, zmax).

Examples

View the ZY plane of a built-in mesh example.

>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_zy()
>>> pl.show()
where_is(name)#

Return the subplot coordinates of a given actor.

Parameters:

name (str) – Actor’s name.

Returns:

list[tuple[int, int]] – A list with the subplot coordinates of the actor.

Examples

>>> import pyvista as pv
>>> plotter = pv.Plotter(shape=(2, 2))
>>> plotter.subplot(0, 0)
>>> _ = plotter.add_mesh(pv.Box(), name='box')
>>> plotter.subplot(0, 1)
>>> _ = plotter.add_mesh(pv.Sphere(), name='sphere')
>>> plotter.subplot(1, 0)
>>> _ = plotter.add_mesh(pv.Box(), name='box')
>>> plotter.subplot(1, 1)
>>> _ = plotter.add_mesh(pv.Cone(), name='cone')
>>> plotter.where_is('box')
[(0, 0), (1, 0)]
>>> plotter.show()
property window_size#

Return the render window size in (width, height).

Examples

Change the window size from 200 x 200 to 400 x 400.

>>> import pyvista as pv
>>> pl = pv.Plotter(window_size=[200, 200])
>>> pl.window_size
[200, 200]
>>> pl.window_size = [400, 400]
>>> pl.window_size
[400, 400]
window_size_context(window_size=None)#

Set the render window size in an isolated context.

Parameters:

window_size (sequence[int], optional) – Window size in pixels. Defaults to pyvista.Plotter.window_size.

Examples

Take two different screenshots with two different window sizes.

>>> import pyvista as pv
>>> pl = pv.Plotter(off_screen=True)
>>> _ = pl.add_mesh(pv.Cube())
>>> with pl.window_size_context((400, 400)):
...     pl.screenshot('/tmp/small_screenshot.png')  
...
>>> with pl.window_size_context((1000, 1000)):
...     pl.screenshot('/tmp/big_screenshot.png')  
...
write_frame()#

Write a single frame to the movie file.

Examples

>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> plotter.open_movie(filename)  
>>> plotter.add_mesh(pv.Sphere())  
>>> plotter.write_frame()  

See movie_example for a full example using this method.

zoom_camera(value)#

Zoom of the camera and render.

Parameters:

value (float or str) – Zoom of the camera. If a float, must be greater than 0. Otherwise, if a string, must be "tight". If tight, the plot will be zoomed such that the actors fill the entire viewport.