Filters

These classes hold methods to apply general filters to any data type.

By inheriting these classes into the wrapped VTK data structures, a user can easily apply common filters in an intuitive manner.

Example

>>> import pyvista
>>> from pyvista import examples
>>> dataset = examples.load_uniform()
>>> # Threshold
>>> thresh = dataset.threshold([100, 500])
>>> # Slice
>>> slc = dataset.slice()
>>> # Clip
>>> clp = dataset.clip(invert=True)
>>> # Contour
>>> iso = dataset.contour()

Dataset Filters

The pyvista.DataSetFilters is inherited by pyvista.Common making all the following filters available as callable methods directly from any PyVista dataset.

Methods

cell_centers([vertex])

Generate points at the center of the cells in this dataset.

cell_data_to_point_data([pass_cell_data])

Transform cell data into point data.

clip([normal, origin, invert, value, inplace])

Clip a dataset by a plane by specifying the origin and normal.

clip_box([bounds, invert, factor])

Clip a dataset by a bounding box defined by the bounds.

clip_scalar([scalars, invert, value, inplace])

Clip a dataset by a scalar.

clip_surface(surface[, invert, value, …])

Clip any mesh type using a pyvista.PolyData surface mesh.

compute_cell_quality([quality_measure, …])

Compute a function of (geometric) quality for each cell of a mesh.

compute_cell_sizes([length, area, volume, …])

Compute sizes for 1D (length), 2D (area) and 3D (volume) cells.

compute_derivative([scalars, gradient, …])

Compute derivative-based quantities of point/cell scalar field.

compute_gradient([scalars, gradient_name, …])

Compute per cell gradient of point/cell scalar field.

compute_implicit_distance(surface[, inplace])

Compute the implicit distance from the points to a surface.

connectivity([largest])

Find and label connected bodies/volumes.

contour([isosurfaces, scalars, …])

Contour an input dataset by an array.

ctp([pass_cell_data])

Transform cell data into point data.

decimate_boundary([target_reduction])

Return a decimated version of a triangulation of the boundary.

delaunay_3d([alpha, tol, offset, progress_bar])

Construct a 3D Delaunay triangulation of the mesh.

elevation([low_point, high_point, …])

Generate scalar values on a dataset.

extract_all_edges([progress_bar])

Extract all the internal/external edges of the dataset as PolyData.

extract_cells(ind)

Return a subset of the grid.

extract_edges([feature_angle, …])

Extract edges from the surface of the mesh.

extract_feature_edges([feature_angle, …])

Extract edges from the surface of the mesh.

extract_geometry()

Extract the outer surface of a volume or structured grid dataset as PolyData.

extract_largest([inplace])

Extract largest connected set in mesh.

extract_points(ind)

Return a subset of the grid (with cells) that contains any of the given point indices.

extract_selection_points(ind)

Return a subset of the grid (with cells) that contains any of the given point indices.

extract_surface([pass_pointid, pass_cellid, …])

Extract surface mesh of the grid.

glyph([orient, scale, factor, geom, …])

Copy a geometric representation (called a glyph) to every point in the input dataset.

interpolate(target[, sharpness, radius, …])

Interpolate values onto this mesh from a given dataset.

merge([grid, merge_points, inplace, …])

Join one or many other grids to this grid.

outline([generate_faces])

Produce an outline of the full extent for the input dataset.

outline_corners([factor])

Produce an outline of the corners for the input dataset.

plot_over_line(pointa, pointb[, resolution, …])

Sample a dataset along a high resolution line and plot.

point_data_to_cell_data([pass_point_data])

Transform point data into cell data.

probe(points[, tolerance, pass_cell_arrays, …])

Sample data values at specified point locations.

ptc([pass_point_data])

Transform point data into cell data.

sample(target[, tolerance, …])

Resample array data from a passed mesh onto this mesh.

sample_over_line(pointa, pointb[, …])

Sample a dataset onto a line.

select_enclosed_points(surface[, tolerance, …])

Mark points as to whether they are inside a closed surface.

slice([normal, origin, generate_triangles, …])

Slice a dataset by a plane at the specified origin and normal vector orientation.

slice_along_axis([n, axis, tolerance, …])

Create many slices of the input dataset along a specified axis.

slice_along_line(line[, generate_triangles, …])

Slice a dataset using a polyline/spline as the path.

slice_orthogonal([x, y, z, …])

Create three orthogonal slices through the dataset on the three cartesian planes.

split_bodies([label])

Find, label, and split connected bodies/volumes.

streamlines([vectors, source_center, …])

Integrate a vector field to generate streamlines.

surface_indices()

Return the surface indices of a grid.

texture_map_to_plane([origin, point_u, …])

Texture map this dataset to a user defined plane.

threshold([value, scalars, invert, …])

Apply a vtkThreshold filter to the input dataset.

threshold_percent([percent, scalars, …])

Threshold the dataset by a percentage of its range on the active scalars array or as specified.

triangulate([inplace])

Return an all triangle mesh.

warp_by_scalar([scalars, factor, normal, …])

Warp the dataset’s points by a point data scalars array’s values.

warp_by_vector([vectors, factor, inplace])

Warp the dataset’s points by a point data vectors array’s values.

wireframe([progress_bar])

Extract all the internal/external edges of the dataset as PolyData.

class pyvista.DataSetFilters(*args, **kwargs)

A set of common filters that can be applied to any vtkDataSet.

cell_centers(vertex=True)

Generate points at the center of the cells in this dataset.

These points can be used for placing glyphs / vectors.

Parameters

vertex (bool) – Enable/disable the generation of vertex cells.

cell_data_to_point_data(pass_cell_data=False)

Transform cell data into point data.

Point data are specified per node and cell data specified within cells. Optionally, the input point data can be passed through to the output.

The method of transformation is based on averaging the data values of all cells using a particular point. Optionally, the input cell data can be passed through to the output as well.

See also: pyvista.DataSetFilters.point_data_to_cell_data()

Parameters

pass_cell_data (bool) – If enabled, pass the input cell data through to the output

clip(normal='x', origin=None, invert=True, value=0.0, inplace=False)

Clip a dataset by a plane by specifying the origin and normal.

If no parameters are given the clip will occur in the center of that dataset.

Parameters
  • normal (tuple(float) or str) – Length 3 tuple for the normal vector direction. Can also be specified as a string conventional direction such as 'x' for (1,0,0) or '-x' for (-1,0,0), etc.

  • origin (tuple(float), optional) – The center (x,y,z) coordinate of the plane on which the clip occurs. The default is the center of the dataset.

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

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

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Clipped mesh when inplace=False. When inplace=True, None

Return type

pyvista.PolyData

Examples

Clip a cube along the +X direction. triangulate is used as the cube is initially composed of quadrilateral faces and subdivide only works on triangles.

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip()

Clip a cube in the +Z direction. This leaves half a cube below the XY plane.

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip('z')
clip_box(bounds=None, invert=True, factor=0.35)

Clip a dataset by a bounding box defined by the bounds.

If no bounds are given, a corner of the dataset bounds will be removed.

Parameters
  • bounds (tuple(float)) – Length 6 sequence of floats: (xmin, xmax, ymin, ymax, zmin, zmax). Length 3 sequence of floats: distances from the min coordinate of of the input mesh. Single float value: uniform distance from the min coordinate. Length 12 sequence of length 3 sequence of floats: a plane collection (normal, center, …). pyvista.PolyData: if a poly mesh is passed that represents a box with 6 faces that all form a standard box, then planes will be extracted from the box to define the clipping region.

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

  • factor (float, optional) – If bounds are not given this is the factor along each axis to extract the default box.

Examples

Clip a corner of a cube. The bounds of a cube are normally [-0.5, 0.5, -0.5, 0.5, -0.5, 0.5], and this removes 1/8 of the cube’s surface.

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip_box([0, 1, 0, 1, 0, 1])
clip_scalar(scalars=None, invert=True, value=0.0, inplace=False)

Clip a dataset by a scalar.

Parameters
  • scalars (str, optional) – Name of scalars to clip on. Defaults to currently active scalars.

  • invert (bool, optional) – Flag on whether to flip/invert the clip. When True, only the mesh below value will be kept. When False, only values above value will be kept.

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

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

pdata – Clipped dataset.

Return type

pyvista.PolyData

Examples

Remove the part of the mesh with “sample_point_scalars” above 100.

>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> clipped = dataset.clip_scalar(scalars="sample_point_scalars", value=100)

Remove the part of the mesh with “sample_point_scalars” below 100. Since these scalars are already active, there’s no need to specify scalars=

>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> clipped = dataset.clip_scalar(value=100, invert=False)
clip_surface(surface, invert=True, value=0.0, compute_distance=False)

Clip any mesh type using a pyvista.PolyData surface mesh.

This will return a pyvista.UnstructuredGrid of the clipped mesh. Geometry of the input dataset will be preserved where possible - geometries near the clip intersection will be triangulated/tessellated.

Parameters
  • surface (pyvista.PolyData) – The PolyData surface mesh to use as a clipping function. If this mesh is not PolyData, the external surface will be extracted.

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

  • value (float:) – Set the clipping value of the implicit function (if clipping with implicit function) or scalar value (if clipping with scalars). The default value is 0.0.

  • compute_distance (bool, optional) – Compute the implicit distance from the mesh onto the input dataset. A new array called 'implicit_distance' will be added to the output clipped mesh.

compute_cell_quality(quality_measure='scaled_jacobian', null_value=- 1.0)

Compute a function of (geometric) quality for each cell of a mesh.

The per-cell quality is added to the mesh’s cell data, in an array named “CellQuality”. Cell types not supported by this filter or undefined quality of supported cell types will have an entry of -1.

Defaults to computing the scaled jacobian.

Options for cell quality measure:

  • 'area'

  • 'aspect_beta'

  • 'aspect_frobenius'

  • 'aspect_gamma'

  • 'aspect_ratio'

  • 'collapse_ratio'

  • 'condition'

  • 'diagonal'

  • 'dimension'

  • 'distortion'

  • 'jacobian'

  • 'max_angle'

  • 'max_aspect_frobenius'

  • 'max_edge_ratio'

  • 'med_aspect_frobenius'

  • 'min_angle'

  • 'oddy'

  • 'radius_ratio'

  • 'relative_size_squared'

  • 'scaled_jacobian'

  • 'shape'

  • 'shape_and_size'

  • 'shear'

  • 'shear_and_size'

  • 'skew'

  • 'stretch'

  • 'taper'

  • 'volume'

  • 'warpage'

Parameters
  • quality_measure (str) – The cell quality measure to use

  • null_value (float) – Float value for undefined quality. Undefined quality are qualities that could be addressed by this filter but is not well defined for the particular geometry of cell in question, e.g. a volume query for a triangle. Undefined quality will always be undefined. The default value is -1.

compute_cell_sizes(length=True, area=True, volume=True, progress_bar=False)

Compute sizes for 1D (length), 2D (area) and 3D (volume) cells.

Parameters
  • length (bool) – Specify whether or not to compute the length of 1D cells.

  • area (bool) – Specify whether or not to compute the area of 2D cells.

  • volume (bool) – Specify whether or not to compute the volume of 3D cells.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

compute_derivative(scalars=None, gradient=True, divergence=None, vorticity=None, qcriterion=None, faster=False, preference='point')

Compute derivative-based quantities of point/cell scalar field.

Utilize vtkGradientFilter to compute derivative-based quantities, such as gradient, divergence, vorticity, and Q-criterion, of the selected point or cell scalar field.

Parameters
  • scalars (str, optional) – String name of the scalars array to use when computing the derivative quantities.

  • gradient (bool, str, optional) – Calculate gradient. If a string is passed, the string will be used for the resulting array name. Otherwise, array name will be ‘gradient’. Default: True

  • divergence (bool, str, optional) – Calculate divergence. If a string is passed, the string will be used for the resulting array name. Otherwise, array name will be ‘divergence’. Default: None

  • vorticity (bool, str, optional) – Calculate vorticity. If a string is passed, the string will be used for the resulting array name. Otherwise, array name will be ‘vorticity’. Default: None

  • qcriterion (bool, str, optional) – Calculate qcriterion. If a string is passed, the string will be used for the resulting array name. Otherwise, array name will be ‘qcriterion’. Default: None

  • faster (bool, optional) – Use faster algorithm for computing derivative quantities. Result is less accurate and performs fewer derivative calculations, increasing computation speed. The error will feature smoothing of the output and possibly errors at boundaries. Option has no effect if DataSet is not UnstructuredGrid. Default: False

  • preference (str, optional) – Data type preference. Either ‘point’ or ‘cell’.

compute_gradient(scalars=None, gradient_name='gradient', preference='point')

Compute per cell gradient of point/cell scalar field.

DEPRECATED: Use compute_derivative instead.

Parameters
  • scalars (str, optional) – String name of the scalars array to use when computing gradient.

  • gradient_name (str, optional) – The name of the output array of the computed gradient.

  • preference (str, optional) – Data type preference. Either ‘point’ or ‘cell’.

compute_implicit_distance(surface, inplace=False)

Compute the implicit distance from the points to a surface.

This filter will comput the implicit distance from all of the nodes of this mesh to a given surface. This distance will be added as a point array called 'implicit_distance'.

Parameters
  • surface (pyvista.Common) – The surface used to compute the distance

  • inplace (bool) – If True, a new scalar array will be added to the point_arrays of this mesh. Otherwise a copy of this mesh is returned with that scalar field.

Examples

Compute the distance between all the points on a sphere and a plane.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plane = pv.Plane()
>>> sphere.compute_implicit_distance(plane, inplace=True)
>>> dist = sphere['implicit_distance']
>>> print(type(dist))
<class 'numpy.ndarray'>

Plot these distances as a heatmap

>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(sphere, scalars='implicit_distance', cmap='bwr')
>>> _ = pl.add_mesh(plane, color='w', style='wireframe')
>>> pl.show()  
connectivity(largest=False)

Find and label connected bodies/volumes.

This adds an ID array to the point and cell data to distinguish separate connected bodies. This applies a vtkConnectivityFilter filter which extracts cells that share common points and/or meet other connectivity criterion. (Cells that share vertices and meet other connectivity criterion such as scalar range are known as a region.)

Parameters

largest (bool) – Extract the largest connected part of the mesh.

contour(isosurfaces=10, scalars=None, compute_normals=False, compute_gradients=False, compute_scalars=True, rng=None, preference='point', method='contour', progress_bar=False)

Contour an input dataset by an array.

isosurfaces can be an integer specifying the number of isosurfaces in the data range or a sequence of values for explicitly setting the isosurfaces.

Parameters
  • isosurfaces (int or sequence) – Number of isosurfaces to compute across valid data range or a sequence of float values to explicitly use as the isosurfaces.

  • scalars (str, optional) – Name of scalars to threshold on. Defaults to currently active scalars.

  • compute_normals (bool, optional) –

  • compute_gradients (bool, optional) – Desc

  • compute_scalars (bool, optional) – Preserves the scalar values that are being contoured

  • rng (tuple(float), optional) – If an integer number of isosurfaces is specified, this is the range over which to generate contours. Default is the scalars arrays’ full data range.

  • preference (str, optional) – When scalars is specified, this is the preferred array type to search for in the dataset. Must be either 'point' or 'cell'

  • method (str, optional) – Specify to choose which vtk filter is used to create the contour. Must be one of 'contour', 'marching_cubes' and 'flying_edges'. Defaults to 'contour'.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

ctp(pass_cell_data=False)

Transform cell data into point data.

Point data are specified per node and cell data specified within cells. Optionally, the input point data can be passed through to the output.

An alias/shortcut for cell_data_to_point_data.

decimate_boundary(target_reduction=0.5)

Return a decimated version of a triangulation of the boundary.

Only the outer surface of the input dataset will be considered.

Parameters

target_reduction (float) – Fraction of the original mesh to remove. Default is 0.5 TargetReduction is set to 0.9, this filter will try to reduce the data set to 10% of its original size and will remove 90% of the input triangles.

delaunay_3d(alpha=0, tol=0.001, offset=2.5, progress_bar=False)

Construct a 3D Delaunay triangulation of the mesh.

This helps smooth out a rugged mesh.

Parameters
  • alpha (float, optional) – Distance value to control output of this filter. For a non-zero alpha value, only verts, edges, faces, or tetra contained within the circumsphere (of radius alpha) will be output. Otherwise, only tetrahedra will be output.

  • tol (float, optional) – tolerance to control discarding of closely spaced points. This tolerance is specified as a fraction of the diagonal length of the bounding box of the points.

  • offset (float, optional) – multiplier to control the size of the initial, bounding Delaunay triangulation.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

elevation(low_point=None, high_point=None, scalar_range=None, preference='point', set_active=True, progress_bar=False)

Generate scalar values on a dataset.

The scalar values lie within a user specified range, and are generated by computing a projection of each dataset point onto a line. The line can be oriented arbitrarily. A typical example is to generate scalars based on elevation or height above a plane.

Parameters
  • low_point (tuple(float), optional) – The low point of the projection line in 3D space. Default is bottom center of the dataset. Otherwise pass a length 3 tuple(float).

  • high_point (tuple(float), optional) – The high point of the projection line in 3D space. Default is top center of the dataset. Otherwise pass a length 3 tuple(float).

  • scalar_range (str or tuple(float), optional) – The scalar range to project to the low and high points on the line that will be mapped to the dataset. If None given, the values will be computed from the elevation (Z component) range between the high and low points. Min and max of a range can be given as a length 2 tuple(float). If str name of scalara array present in the dataset given, the valid range of that array will be used.

  • preference (str, optional) – When an array name is specified for scalar_range, this is the preferred array type to search for in the dataset. Must be either ‘point’ or ‘cell’.

  • set_active (bool, optional) – A boolean flag on whether or not to set the new Elevation scalar as the active scalars array on the output dataset.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Warning

This will create a scalars array named Elevation on the point data of the input dataset and overasdf write an array named Elevation if present.

extract_all_edges(progress_bar=False)

Extract all the internal/external edges of the dataset as PolyData.

This produces a full wireframe representation of the input dataset.

Parameters

progress_bar (bool, optional) – Display a progress bar to indicate progress.

extract_cells(ind)

Return a subset of the grid.

Parameters

ind (np.ndarray) – Numpy array of cell indices to be extracted.

Returns

subgrid – Subselected grid

Return type

pyvista.UnstructuredGrid

extract_edges(feature_angle=30, boundary_edges=True, non_manifold_edges=True, feature_edges=True, manifold_edges=True, inplace=False)

Extract edges from the surface of the mesh.

If the given mesh is not PolyData, the external surface of the given mesh is extracted and used. From vtk documentation, the edges are one of the following

  1. boundary (used by one polygon) or a line cell

  2. non-manifold (used by three or more polygons)

  3. feature edges (edges used by two triangles and whose dihedral angle > feature_angle)

  4. manifold edges (edges used by exactly two polygons).

Parameters
  • feature_angle (float, optional) – Defaults to 30 degrees.

  • boundary_edges (bool, optional) – Defaults to True

  • non_manifold_edges (bool, optional) – Defaults to True

  • feature_edges (bool, optional) – Defaults to True

  • manifold_edges (bool, optional) – Defaults to True

  • inplace (bool, optional) – Return new mesh or overwrite input.

Returns

edges – Extracted edges. None if inplace=True.

Return type

pyvista.vtkPolyData

extract_feature_edges(feature_angle=30, boundary_edges=True, non_manifold_edges=True, feature_edges=True, manifold_edges=True, inplace=False)

Extract edges from the surface of the mesh.

If the given mesh is not PolyData, the external surface of the given mesh is extracted and used. From vtk documentation, the edges are one of the following

  1. boundary (used by one polygon) or a line cell

  2. non-manifold (used by three or more polygons)

  3. feature edges (edges used by two triangles and whose dihedral angle > feature_angle)

  4. manifold edges (edges used by exactly two polygons).

Parameters
  • feature_angle (float, optional) – Defaults to 30 degrees.

  • boundary_edges (bool, optional) – Defaults to True

  • non_manifold_edges (bool, optional) – Defaults to True

  • feature_edges (bool, optional) – Defaults to True

  • manifold_edges (bool, optional) – Defaults to True

  • inplace (bool, optional) – Return new mesh or overwrite input.

Returns

edges – Extracted edges. None if inplace=True.

Return type

pyvista.vtkPolyData

extract_geometry()

Extract the outer surface of a volume or structured grid dataset as PolyData.

This will extract all 0D, 1D, and 2D cells producing the boundary faces of the dataset.

extract_largest(inplace=False)

Extract largest connected set in mesh.

Can be used to reduce residues obtained when generating an isosurface. Works only if residues are not connected (share at least one point with) the main component of the image.

Parameters

inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Largest connected set in mesh

Return type

pyvista.PolyData

extract_points(ind)

Return a subset of the grid (with cells) that contains any of the given point indices.

Parameters

ind (np.ndarray, list, or sequence) – Numpy array of point indices to be extracted.

Returns

subgrid – Subselected grid.

Return type

pyvista.UnstructuredGrid

extract_selection_points(ind)

Return a subset of the grid (with cells) that contains any of the given point indices.

DEPRECATED: Please use extract_points instead.

extract_surface(pass_pointid=True, pass_cellid=True, inplace=False)

Extract surface mesh of the grid.

Parameters
  • pass_pointid (bool, optional) – Adds a point array “vtkOriginalPointIds” that idenfities which original points these surface points correspond to

  • pass_cellid (bool, optional) – Adds a cell array “vtkOriginalPointIds” that idenfities which original cells these surface cells correspond to

Returns

extsurf – Surface mesh of the grid

Return type

pyvista.PolyData

glyph(orient=True, scale=True, factor=1.0, geom=None, tolerance=None, absolute=False, clamping=False, rng=None, progress_bar=False)

Copy a geometric representation (called a glyph) to every point in the input dataset.

The glyph may be oriented along the input vectors, and it may be scaled according to scalar data or vector magnitude.

Parameters
  • orient (bool) – Use the active vectors array to orient the glyphs

  • scale (bool) – Use the active scalars to scale the glyphs

  • factor (float) – Scale factor applied to scaling array

  • geom (vtk.vtkDataSet) – The geometry to use for the glyph

  • tolerance (float, optional) – Specify tolerance in terms of fraction of bounding box length. Float value is between 0 and 1. Default is None. If absolute is True then the tolerance can be an absolute distance. If None, points merging as a preprocessing step is disabled.

  • absolute (bool, optional) – Control if tolerance is an absolute distance or a fraction.

  • clamping (bool) – Turn on/off clamping of “scalar” values to range.

  • rng (tuple(float), optional) – Set the range of values to be considered by the filter when scalars values are provided.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

interpolate(target, sharpness=2, radius=1.0, strategy='null_value', null_value=0.0, n_points=None, pass_cell_arrays=True, pass_point_arrays=True, progress_bar=False)

Interpolate values onto this mesh from a given dataset.

The input dataset is typically a point cloud.

This uses a gaussian interpolation kernel. Use the sharpness and radius parameters to adjust this kernel. You can also switch this kernel to use an N closest points approach.

Parameters
  • target (pyvista.Common) – The vtk data object to sample from - point and cell arrays from this object are interpolated onto this mesh.

  • sharpness (float) – Set / Get the sharpness (i.e., falloff) of the Gaussian. By default Sharpness=2. As the sharpness increases the effects of distant points are reduced.

  • radius (float) – Specify the radius within which the basis points must lie.

  • n_points (int, optional) – If given, specifies the number of the closest points used to form the interpolation basis. This will invalidate the radius and sharpness arguments in favor of an N closest points approach. This typically has poorer results.

  • strategy (str, optional) – Specify a strategy to use when encountering a “null” point during the interpolation process. Null points occur when the local neighborhood (of nearby points to interpolate from) is empty. If the strategy is set to 'mask_points', then an output array is created that marks points as being valid (=1) or null (invalid =0) (and the NullValue is set as well). If the strategy is set to 'null_value' (this is the default), then the output data value(s) are set to the null_value (specified in the output point data). Finally, the strategy 'closest_point' is to simply use the closest point to perform the interpolation.

  • null_value (float, optional) – Specify the null point value. When a null point is encountered then all components of each null tuple are set to this value. By default the null value is set to zero.

  • pass_cell_arrays (bool, optional) – Preserve input mesh’s original cell data arrays

  • pass_point_arrays (bool, optional) – Preserve input mesh’s original point data arrays

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

merge(grid=None, merge_points=True, inplace=False, main_has_priority=True)

Join one or many other grids to this grid.

Grid is updated in-place by default.

Can be used to merge points of adjacent cells when no grids are input.

Parameters
  • grid (vtk.UnstructuredGrid or list of vtk.UnstructuredGrids) – Grids to merge to this grid.

  • merge_points (bool, optional) – Points in exactly the same location will be merged between the two meshes. Warning: this can leave degenerate point data.

  • inplace (bool, optional) – Updates grid inplace when True if the input type is an pyvista.UnstructuredGrid.

  • main_has_priority (bool, optional) – When this parameter is true and merge_points is true, the arrays of the merging grids will be overwritten by the original main mesh.

Returns

merged_grid – Merged grid. Returned when inplace is False.

Return type

vtk.UnstructuredGrid

Notes

When two or more grids are joined, the type and name of each array must match or the arrays will be ignored and not included in the final merged mesh.

outline(generate_faces=False)

Produce an outline of the full extent for the input dataset.

Parameters

generate_faces (bool, optional) – Generate solid faces for the box. This is off by default

outline_corners(factor=0.2)

Produce an outline of the corners for the input dataset.

Parameters

factor (float, optional) – controls the relative size of the corners to the length of the corresponding bounds

plot_over_line(pointa, pointb, resolution=None, scalars=None, title=None, ylabel=None, figsize=None, figure=True, show=True, tolerance=None)

Sample a dataset along a high resolution line and plot.

Plot the variables of interest in 2D where the X-axis is distance from Point A and the Y-axis is the variable of interest. Note that this filter returns None.

Parameters
  • pointa (np.ndarray or list) – Location in [x, y, z].

  • pointb (np.ndarray or list) – Location in [x, y, z].

  • resolution (int) – number of pieces to divide line into. Defaults to number of cells in the input mesh. Must be a positive integer.

  • scalars (str) – The string name of the variable in the input dataset to probe. The active scalar is used by default.

  • title (str) – The string title of the matplotlib figure

  • ylabel (str) – The string label of the Y-axis. Defaults to variable name

  • figsize (tuple(int)) – the size of the new figure

  • figure (bool) – flag on whether or not to create a new figure

  • show (bool) – Shows the matplotlib figure

  • tolerance (float, optional) – Tolerance used to compute whether a point in the source is in a cell of the input. If not given, tolerance is automatically generated.

point_data_to_cell_data(pass_point_data=False)

Transform point data into cell data.

Point data are specified per node and cell data specified within cells. Optionally, the input point data can be passed through to the output.

See also: pyvista.DataSetFilters.cell_data_to_point_data()

Parameters

pass_point_data (bool) – If enabled, pass the input point data through to the output

probe(points, tolerance=None, pass_cell_arrays=True, pass_point_arrays=True, categorical=False)

Sample data values at specified point locations.

This uses vtk.vtkProbeFilter.

Parameters
  • dataset (pyvista.Common) – The mesh to probe from - point and cell arrays from this object are probed onto the nodes of the points mesh

  • points (pyvista.Common) – The points to probe values on to. This should be a PyVista mesh or something pyvista.wrap() can handle.

  • tolerance (float, optional) – Tolerance used to compute whether a point in the source is in a cell of the input. If not given, tolerance is automatically generated.

  • pass_cell_arrays (bool, optional) – Preserve source mesh’s original cell data arrays

  • pass_point_arrays (bool, optional) – Preserve source mesh’s original point data arrays

  • categorical (bool, optional) – Control whether the source point data is to be treated as categorical. If the data is categorical, then the resultant data will be determined by a nearest neighbor interpolation scheme.

Examples

Probe the active scalars in grid at the points in mesh

>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = pyvista.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)
>>> grid = examples.load_uniform()
>>> result = grid.probe(mesh)
>>> 'Spatial Point Data' in result.point_arrays
True
ptc(pass_point_data=False)

Transform point data into cell data.

Point data are specified per node and cell data specified within cells. Optionally, the input point data can be passed through to the output.

An alias/shortcut for point_data_to_cell_data.

sample(target, tolerance=None, pass_cell_arrays=True, pass_point_arrays=True, categorical=False)

Resample array data from a passed mesh onto this mesh.

This uses vtk.vtkResampleWithDataSet.

Parameters
  • dataset (pyvista.Common) – The source vtk data object as the mesh to sample values on to

  • target (pyvista.Common) – The vtk data object to sample from - point and cell arrays from this object are sampled onto the nodes of the dataset mesh

  • tolerance (float, optional) – Tolerance used to compute whether a point in the source is in a cell of the input. If not given, tolerance is automatically generated.

  • pass_cell_arrays (bool, optional) – Preserve source mesh’s original cell data arrays

  • pass_point_arrays (bool, optional) – Preserve source mesh’s original point data arrays

  • categorical (bool, optional) – Control whether the source point data is to be treated as categorical. If the data is categorical, then the resultant data will be determined by a nearest neighbor interpolation scheme.

sample_over_line(pointa, pointb, resolution=None, tolerance=None)

Sample a dataset onto a line.

Parameters
  • pointa (np.ndarray or list) – Location in [x, y, z].

  • pointb (np.ndarray or list) – Location in [x, y, z].

  • resolution (int) – Number of pieces to divide line into. Defaults to number of cells in the input mesh. Must be a positive integer.

  • tolerance (float, optional) – Tolerance used to compute whether a point in the source is in a cell of the input. If not given, tolerance is automatically generated.

Returns

sampled_line – Line object with sampled data from dataset.

Return type

pv.PolyData

select_enclosed_points(surface, tolerance=0.001, inside_out=False, check_surface=True)

Mark points as to whether they are inside a closed surface.

This evaluates all the input points to determine whether they are in an enclosed surface. The filter produces a (0,1) mask (in the form of a vtkDataArray) that indicates whether points are outside (mask value=0) or inside (mask value=1) a provided surface. (The name of the output vtkDataArray is “SelectedPoints”.)

This filter produces and output data array, but does not modify the input dataset. If you wish to extract cells or poinrs, various threshold filters are available (i.e., threshold the output array).

Warning

The filter assumes that the surface is closed and manifold. A boolean flag can be set to force the filter to first check whether this is true. If false, all points will be marked outside. Note that if this check is not performed and the surface is not closed, the results are undefined.

Parameters
  • surface (pyvista.PolyData) – Set the surface to be used to test for containment. This must be a pyvista.PolyData object.

  • tolerance (float) – The tolerance on the intersection. The tolerance is expressed as a fraction of the bounding box of the enclosing surface.

  • inside_out (bool) – By default, points inside the surface are marked inside or sent to the output. If inside_out is True, then the points outside the surface are marked inside.

  • check_surface (bool) – Specify whether to check the surface for closure. If on, then the algorithm first checks to see if the surface is closed and manifold. If the surface is not closed and manifold, a runtime error is raised.

slice(normal='x', origin=None, generate_triangles=False, contour=False)

Slice a dataset by a plane at the specified origin and normal vector orientation.

If no origin is specified, the center of the input dataset will be used.

Parameters
  • normal (tuple(float) or str) – Length 3 tuple for the normal vector direction. Can also be specified as a string conventional direction such as 'x' for (1,0,0) or '-x' for (-1,0,0)`, etc.

  • origin (tuple(float)) – The center (x,y,z) coordinate of the plane on which the slice occurs

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

slice_along_axis(n=5, axis='x', tolerance=None, generate_triangles=False, contour=False, bounds=None, center=None)

Create many slices of the input dataset along a specified axis.

Parameters
  • n (int) – The number of slices to create

  • axis (str or int) – The axis to generate the slices along. Perpendicular to the slices. Can be string name ('x', 'y', or 'z') or axis index (0, 1, or 2).

  • tolerance (float, optional) – The tolerance to the edge of the dataset bounds to create the slices

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

slice_along_line(line, generate_triangles=False, contour=False)

Slice a dataset using a polyline/spline as the path.

This also works for lines generated with pyvista.Line()

Parameters
  • line (pyvista.PolyData) – A PolyData object containing one single PolyLine cell.

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

slice_orthogonal(x=None, y=None, z=None, generate_triangles=False, contour=False)

Create three orthogonal slices through the dataset on the three cartesian planes.

Yields a MutliBlock dataset of the three slices.

Parameters
  • x (float) – The X location of the YZ slice

  • y (float) – The Y location of the XZ slice

  • z (float) – The Z location of the XY slice

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

split_bodies(label=False)

Find, label, and split connected bodies/volumes.

This splits different connected bodies into blocks in a MultiBlock dataset.

Parameters

label (bool) – A flag on whether to keep the ID arrays given by the connectivity filter.

streamlines(vectors=None, source_center=None, source_radius=None, n_points=100, integrator_type=45, integration_direction='both', surface_streamlines=False, initial_step_length=0.5, step_unit='cl', min_step_length=0.01, max_step_length=1.0, max_steps=2000, terminal_speed=1e-12, max_error=1e-06, max_time=None, compute_vorticity=True, rotation_scale=1.0, interpolator_type='point', start_position=0.0, 0.0, 0.0, return_source=False, pointa=None, pointb=None)

Integrate a vector field to generate streamlines.

The integration is performed using a specified integrator, by default Runge-Kutta2. This supports integration through any type of dataset. Thus if the dataset contains 2D cells like polygons or triangles, the integration is constrained to lie on the surface defined by 2D cells.

This produces polylines as the output, with each cell (i.e., polyline) representing a streamline. The attribute values associated with each streamline are stored in the cell data, whereas those associated with streamline-points are stored in the point data.

This uses a Sphere as the source - set it’s location and radius via the source_center and source_radius keyword arguments. You can retrieve the source as pyvista.PolyData by specifying return_source=True.

Parameters
  • vectors (str) – The string name of the active vector field to integrate across

  • source_center (tuple(float)) – Length 3 tuple of floats defining the center of the source particles. Defaults to the center of the dataset

  • source_radius (float) – Float radius of the source particle cloud. Defaults to one-tenth of the diagonal of the dataset’s spatial extent

  • n_points (int) – Number of particles present in source sphere

  • integrator_type (int) – The integrator type to be used for streamline generation. The default is Runge-Kutta45. The recognized solvers are: RUNGE_KUTTA2 (2), RUNGE_KUTTA4 (4), and RUNGE_KUTTA45 (45). Options are 2, 4, or 45. Default is 45.

  • integration_direction (str) – Specify whether the streamline is integrated in the upstream or downstream directions (or both). Options are 'both', 'backward', or 'forward'.

  • surface_streamlines (bool) – Compute streamlines on a surface. Default False

  • initial_step_length (float) – Initial step size used for line integration, expressed ib length unitsL or cell length units (see step_unit parameter). either the starting size for an adaptive integrator, e.g., RK45, or the constant / fixed size for non-adaptive ones, i.e., RK2 and RK4)

  • step_unit (str) – Uniform integration step unit. The valid unit is now limited to only LENGTH_UNIT ('l') and CELL_LENGTH_UNIT ('cl'). Default is CELL_LENGTH_UNIT: 'cl'.

  • min_step_length (float) – Minimum step size used for line integration, expressed in length or cell length units. Only valid for an adaptive integrator, e.g., RK45

  • max_step_length (float) – Maximum step size used for line integration, expressed in length or cell length units. Only valid for an adaptive integrator, e.g., RK45

  • max_steps (int) – Maximum number of steps for integrating a streamline. Defaults to 2000

  • terminal_speed (float) – Terminal speed value, below which integration is terminated.

  • max_error (float) – Maximum error tolerated throughout streamline integration.

  • max_time (float) – Specify the maximum length of a streamline expressed in LENGTH_UNIT.

  • compute_vorticity (bool) – Vorticity computation at streamline points (necessary for generating proper stream-ribbons using the vtkRibbonFilter.

  • interpolator_type (str) – Set the type of the velocity field interpolator to locate cells during streamline integration either by points or cells. The cell locator is more robust then the point locator. Options are 'point' or 'cell' (abbreviations of 'p' and 'c' are also supported).

  • rotation_scale (float) – This can be used to scale the rate with which the streamribbons twist. The default is 1.

  • start_position (tuple(float)) – Set the start position. Default is (0.0, 0.0, 0.0)

  • return_source (bool) – Return the source particles as pyvista.PolyData as well as the streamlines. This will be the second value returned if True.

  • pointa (tuple(float)) – The coordinates of a start and end point for a line source. This will override the sphere point source.

  • pointb (tuple(float)) – The coordinates of a start and end point for a line source. This will override the sphere point source.

surface_indices()

Return the surface indices of a grid.

Returns

surf_ind – Indices of the surface points.

Return type

np.ndarray

texture_map_to_plane(origin=None, point_u=None, point_v=None, inplace=False, name='Texture Coordinates', use_bounds=False)

Texture map this dataset to a user defined plane.

This is often used to define a plane to texture map an image to this dataset. The plane defines the spatial reference and extent of that image.

Parameters
  • origin (tuple(float)) – Length 3 iterable of floats defining the XYZ coordinates of the BOTTOM LEFT CORNER of the plane

  • point_u (tuple(float)) – Length 3 iterable of floats defining the XYZ coordinates of the BOTTOM RIGHT CORNER of the plane

  • point_v (tuple(float)) – Length 3 iterable of floats defining the XYZ coordinates of the TOP LEFT CORNER of the plane

  • inplace (bool, optional) – If True, the new texture coordinates will be added to the dataset inplace. If False (default), a new dataset is returned with the textures coordinates

  • name (str, optional) – The string name to give the new texture coordinates if applying the filter inplace.

  • use_bounds (bool, optional) – Use the bounds to set the mapping plane by default (bottom plane of the bounding box).

threshold(value=None, scalars=None, invert=False, continuous=False, preference='cell', all_scalars=True)

Apply a vtkThreshold filter to the input dataset.

This filter will apply a vtkThreshold filter to the input dataset and return the resulting object. This extracts cells where the scalar value in each cell satisfies threshold criterion. If scalars is None, the inputs active scalars is used.

Parameters
  • value (float or sequence, optional) – Single value or (min, max) to be used for the data threshold. If a sequence, then length must be 2. If no value is specified, the non-NaN data range will be used to remove any NaN values.

  • scalars (str, optional) – Name of scalars to threshold on. Defaults to currently active scalars.

  • invert (bool, optional) – If value is a single value, when invert is True cells are kept when their values are below parameter “value”. When invert is False cells are kept when their value is above the threshold “value”. Default is False: yielding above the threshold “value”.

  • continuous (bool, optional) – When True, the continuous interval [minimum cell scalar, maximum cell scalar] will be used to intersect the threshold bound, rather than the set of discrete scalar values from the vertices.

  • preference (str, optional) – When scalars is specified, this is the preferred array type to search for in the dataset. Must be either 'point' or 'cell'

  • all_scalars (bool, optional) – If using scalars from point data, all scalars for 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.

Examples

>>> import pyvista
>>> import numpy as np
>>> volume = np.zeros([10, 10, 10])
>>> volume[:3] = 1
>>> v = pyvista.wrap(volume)
>>> threshed = v.threshold(0.1)
threshold_percent(percent=0.5, scalars=None, invert=False, continuous=False, preference='cell')

Threshold the dataset by a percentage of its range on the active scalars array or as specified.

Parameters
  • percent (float or tuple(float), optional) – The percentage (0,1) to threshold. If value is out of 0 to 1 range, then it will be divided by 100 and checked to be in that range.

  • scalars (str, optional) – Name of scalars to threshold on. Defaults to currently active scalars.

  • invert (bool, optional) – When invert is True cells are kept when their values are below the percentage of the range. When invert is False, cells are kept when their value is above the percentage of the range. Default is False: yielding above the threshold “value”.

  • continuous (bool, optional) – When True, the continuous interval [minimum cell scalar, maximum cell scalar] will be used to intersect the threshold bound, rather than the set of discrete scalar values from the vertices.

  • preference (str, optional) – When scalars is specified, this is the preferred array type to search for in the dataset. Must be either 'point' or 'cell'

triangulate(inplace=False)

Return an all triangle mesh.

More complex polygons will be broken down into triangles.

Parameters

inplace (bool, optional) – Updates mesh in-place while returning None.

Returns

mesh – Mesh containing only triangles. None when inplace=True

Return type

pyvista.UnstructuredGrid

warp_by_scalar(scalars=None, factor=1.0, normal=None, inplace=False, **kwargs)

Warp the dataset’s points by a point data scalars array’s values.

This modifies point coordinates by moving points along point normals by the scalar amount times the scale factor.

Parameters
  • scalars (str, optional) – Name of scalars to warp by. Defaults to currently active scalars.

  • factor (float, optional) – A scaling factor to increase the scaling effect. Alias scale_factor also accepted - if present, overrides factor.

  • normal (np.array, list, tuple of length 3) – User specified normal. If given, data normals will be ignored and the given normal will be used to project the warp.

  • inplace (bool) – If True, the points of the give dataset will be updated.

warp_by_vector(vectors=None, factor=1.0, inplace=False)

Warp the dataset’s points by a point data vectors array’s values.

This modifies point coordinates by moving points along point vectors by the local vector times the scale factor.

A classical application of this transform is to visualize eigenmodes in mechanics.

Parameters
  • vectors (str, optional) – Name of vector to warp by. Defaults to currently active vector.

  • factor (float, optional) – A scaling factor that multiplies the vectors to warp by. Can be used to enhance the warping effect.

  • inplace (bool, optional) – If True, the function will update the mesh in-place and return None.

Returns

warped_mesh – The warped mesh resulting from the operation.

Return type

mesh

wireframe(progress_bar=False)

Extract all the internal/external edges of the dataset as PolyData.

This produces a full wireframe representation of the input dataset.

Parameters

progress_bar (bool, optional) – Display a progress bar to indicate progress.

PolyData Filters

The pyvista.PolyDataFilters is inherited by pyvista.PolyData making all the following filters available as callable methods directly from any PolyData mesh.

Methods

boolean_add(mesh[, inplace])

Add a mesh to the current mesh.

boolean_cut(cut[, tolerance, inplace])

Perform a Boolean cut using another mesh.

boolean_difference(mesh[, inplace])

Combine two meshes and retains only the volume in common between the meshes.

boolean_union(mesh[, inplace])

Combine two meshes and attempts to create a manifold mesh.

clean([point_merging, tolerance, …])

Clean the mesh.

clip_closed_surface([normal, origin, …])

Clip a closed polydata surface with a plane.

clip_with_plane(origin, normal[, value, …])

Clip a dataset by a plane by specifying the origin and normal.

compute_arc_length()

Compute the arc length over the length of the probed line.

compute_normals([cell_normals, …])

Compute point and/or cell normals for a mesh.

curvature([curv_type])

Return the pointwise curvature of a mesh.

decimate(target_reduction[, …])

Reduce the number of triangles in a triangular mesh using vtkQuadricDecimation.

decimate_pro(reduction[, feature_angle, …])

Reduce the number of triangles in a triangular mesh.

delaunay_2d([tol, alpha, offset, bound, …])

Apply a delaunay 2D filter along the best fitting plane.

delauney_2d()

Apply a delaunay 2D filter along the best fitting plane.

edge_mask(angle)

Return a mask of the points of a surface mesh that has a surface angle greater than angle.

extrude(vector[, inplace, progress_bar])

Sweep polygonal data creating a “skirt” from free edges.

fill_holes(hole_size[, inplace, progress_bar])

Fill holes in a pyvista.PolyData or vtk.vtkPolyData object.

flip_normals()

Flip normals of a triangular mesh by reversing the point ordering.

geodesic(start_vertex, end_vertex[, inplace])

Calculate the geodesic path between two vertices using Dijkstra’s algorithm.

geodesic_distance(start_vertex, end_vertex)

Calculate the geodesic distance between two vertices using Dijkstra’s algorithm.

plot_boundaries([edge_color])

Plot boundaries of a mesh.

plot_curvature([curv_type])

Plot the curvature.

plot_normals([show_mesh, mag, flip, use_every])

Plot the point normals of a mesh.

project_points_to_plane([origin, normal, …])

Project points of this mesh to a plane.

ray_trace(origin, end_point[, first_point, …])

Perform a single ray trace calculation.

remove_points(remove[, mode, keep_scalars, …])

Rebuild a mesh by removing points.

ribbon([width, scalars, angle, factor, …])

Create a ribbon of the lines in this dataset.

smooth([n_iter, relaxation_factor, …])

Adjust point coordinates using Laplacian smoothing.

strip([join, max_length, pass_cell_data, …])

Strip poly data cells.

subdivide(nsub[, subfilter, inplace])

Increase the number of triangles in a single, connected triangular mesh.

tri_filter([inplace])

Return an all triangle mesh.

triangulate([inplace])

Return an all triangle mesh.

tube([radius, scalars, capping, n_sides, …])

Generate a tube around each input line.

class pyvista.PolyDataFilters(*args, **kwargs)

Bases: pyvista.core.filters.DataSetFilters

An internal class to manage filtes/algorithms for polydata datasets.

boolean_add(mesh, inplace=False)

Add a mesh to the current mesh.

Does not attempt to “join” the meshes.

Parameters
  • mesh (pyvista.PolyData) – The mesh to add.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

joinedmesh – Initial mesh and the new mesh when inplace=False.

Return type

pyvista.PolyData

boolean_cut(cut, tolerance=1e-05, inplace=False)

Perform a Boolean cut using another mesh.

Parameters
  • cut (pyvista.PolyData) – Mesh making the cut

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – The cut mesh when inplace=False

Return type

pyvista.PolyData

boolean_difference(mesh, inplace=False)

Combine two meshes and retains only the volume in common between the meshes.

Parameters
  • mesh (pyvista.PolyData) – The mesh to perform a union against.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

union – The union mesh when inplace=False.

Return type

pyvista.PolyData

boolean_union(mesh, inplace=False)

Combine two meshes and attempts to create a manifold mesh.

Parameters
  • mesh (pyvista.PolyData) – The mesh to perform a union against.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

union – The union mesh when inplace=False.

Return type

pyvista.PolyData

clean(point_merging=True, tolerance=None, lines_to_points=True, polys_to_lines=True, strips_to_polys=True, inplace=False, absolute=True, progress_bar=False, **kwargs)

Clean the mesh.

This merges duplicate points, removes unused points, and/or removes degenerate cells.

Parameters
  • point_merging (bool, optional) – Enables point merging. On by default.

  • tolerance (float, optional) – Set merging tolerance. When enabled merging is set to absolute distance. If absolute is False, then the merging tolerance is a fraction of the bounding box length. The alias merge_tol is also excepted.

  • lines_to_points (bool, optional) – Turn on/off conversion of degenerate lines to points. Enabled by default.

  • polys_to_lines (bool, optional) – Turn on/off conversion of degenerate polys to lines. Enabled by default.

  • strips_to_polys (bool, optional) – Turn on/off conversion of degenerate strips to polys.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing. Default True.

  • absolute (bool, optional) – Control if tolerance is an absolute distance or a fraction.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Returns

mesh – Cleaned mesh. None when inplace=True

Return type

pyvista.PolyData

Examples

Create a mesh with a degenerate face and then clean it, removing the degenerate face

>>> import pyvista as pv
>>> points = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0]])
>>> faces = np.array([3, 0, 1, 2, 3, 0, 3, 3])
>>> mesh = pv.PolyData(points, faces)
>>> mout = mesh.clean()
>>> print(mout.faces)
[3 0 1 2]
clip_closed_surface(normal='x', origin=None, tolerance=1e-06, inplace=False)

Clip a closed polydata surface with a plane.

This currently only supports one plane but could be implemented to handle a plane collection.

It will produce a new closed surface by creating new polygonal faces where the input data was clipped.

Non-manifold surfaces should not be used as input for this filter. The input surface should have no open edges, and must not have any edges that are shared by more than two faces. In addition, the input surface should not self-intersect, meaning that the faces of the surface should only touch at their edges.

Parameters
  • normal (str, list, optional) – Plane normal to clip with. Plane is centered at origin. Normal can be either a 3 member list (e.g. [0, 0, 1]) or one of the following strings: 'x', 'y', 'z', '-x', '-y', or '-z'.

  • origin (list, optional) – Coordinate of the origin (e.g. [1, 0, 0]). Defaults to [0, 0, 0]`

  • tolerance (float, optional) – The tolerance for creating new points while clipping. If the tolerance is too small, then degenerate triangles might be produced.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing. Defaults to False.

Returns

clipped_mesh – The clipped mesh resulting from this operation when inplace==False. Otherwise, None.

Return type

pyvista.PolyData

Examples

Clip a sphere in the X direction centered at the origin. This will leave behind half a sphere in the positive X direction.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> clipped_mesh = sphere.clip_closed_surface()

Clip the sphere at the xy plane and leave behind half the sphere in the positive Z direction. Shift the clip upwards to leave a smaller mesh behind.

>>> clipped_mesh = sphere.clip_closed_surface('z', origin=[0, 0, 0.3])
clip_with_plane(origin, normal, value=0, invert=False, inplace=False)

Clip a dataset by a plane by specifying the origin and normal.

DEPRECATED: Please use .clip instead.

compute_arc_length()

Compute the arc length over the length of the probed line.

It adds a new point-data array named “arc_length” with the computed arc length for each of the polylines in the input. For all other cell types, the arc length is set to 0.

Returns

arc_length – Arc length of the length of the probed line

Return type

float

Examples

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> path = sphere.geodesic(0, 100)
>>> length = path.compute_arc_length()['arc_length'][-1]
>>> print('Length is %.3f' % length)
Length is 0.812

This is identical to the geodesic_distance

>>> length = sphere.geodesic_distance(0, 100)
>>> print('Length is %.3f' % length)
Length is 0.812

You can also plot the arc_length

>>> arc = path.compute_arc_length()
>>> arc.plot(scalars="arc_length")  
compute_normals(cell_normals=True, point_normals=True, split_vertices=False, flip_normals=False, consistent_normals=True, auto_orient_normals=False, non_manifold_traversal=True, feature_angle=30.0, inplace=False)

Compute point and/or cell normals for a mesh.

The filter can reorder polygons to insure consistent orientation across polygon neighbors. Sharp edges can be split and points duplicated with separate normals to give crisp (rendered) surface definition. It is also possible to globally flip the normal orientation.

The algorithm works by determining normals for each polygon and then averaging them at shared points. When sharp edges are present, the edges are split and new points generated to prevent blurry edges (due to Gouraud shading).

Parameters
  • cell_normals (bool, optional) – Calculation of cell normals. Defaults to True.

  • point_normals (bool, optional) – Calculation of point normals. Defaults to True.

  • split_vertices (bool, optional) – Splitting of sharp edges. Defaults to False.

  • flip_normals (bool, optional) – Set global flipping of normal orientation. Flipping modifies both the normal direction and the order of a cell’s points. Defaults to False.

  • consistent_normals (bool, optional) – Enforcement of consistent polygon ordering. Defaults to True.

  • auto_orient_normals (bool, optional) – Turn on/off the automatic determination of correct normal orientation. NOTE: This assumes a completely closed surface (i.e. no boundary edges) and no non-manifold edges. If these constraints do not hold, all bets are off. This option adds some computational complexity, and is useful if you don’t want to have to inspect the rendered image to determine whether to turn on the FlipNormals flag. However, this flag can work with the FlipNormals flag, and if both are set, all the normals in the output will point “inward”. Defaults to False.

  • non_manifold_traversal (bool, optional) – Turn on/off traversal across non-manifold edges. Changing this may prevent problems where the consistency of polygonal ordering is corrupted due to topological loops. Defaults to True.

  • feature_angle (float, optional) – The angle that defines a sharp edge. If the difference in angle across neighboring polygons is greater than this value, the shared edge is considered “sharp”. Defaults to 30.0.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing. Defaults to False.

Returns

mesh – Updated mesh with cell and point normals if inplace=False

Return type

pyvista.PolyData

Examples

Compute the point normals of the surface of a sphere

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere.compute_normals(cell_normals=False, inplace=True)
>>> normals = sphere['Normals']
>>> normals.shape
(842, 3)

Alternatively, create a new mesh when computing the normals and compute both cell and point normals.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere_with_norm = sphere.compute_normals()
>>> sphere_with_norm.point_arrays['Normals'].shape
(842, 3)
>>> sphere_with_norm.cell_arrays['Normals'].shape
(1680, 3)

Notes

Previous arrays named “Normals” will be overwritten.

Normals are computed only for polygons and triangle strips. Normals are not computed for lines or vertices.

Triangle strips are broken up into triangle polygons. You may want to restrip the triangles.

May be easier to run mesh.point_normals or mesh.cell_normals

curvature(curv_type='mean')

Return the pointwise curvature of a mesh.

Parameters
  • mesh (vtk.polydata) – vtk polydata mesh

  • string (curvature) – One of the following strings Mean Gaussian Maximum Minimum

  • optional – One of the following strings Mean Gaussian Maximum Minimum

Returns

curvature – Curvature values

Return type

np.ndarray

decimate(target_reduction, volume_preservation=False, attribute_error=False, scalars=True, vectors=True, normals=False, tcoords=True, tensors=True, scalars_weight=0.1, vectors_weight=0.1, normals_weight=0.1, tcoords_weight=0.1, tensors_weight=0.1, inplace=False, progress_bar=False)

Reduce the number of triangles in a triangular mesh using vtkQuadricDecimation.

Parameters
  • mesh (vtk.PolyData) – Mesh to decimate

  • target_reduction (float) – Fraction of the original mesh to remove. TargetReduction is set to 0.9, this filter will try to reduce the data set to 10% of its original size and will remove 90% of the input triangles.

  • volume_preservation (bool, optional) – Decide whether to activate volume preservation which greatly reduces errors in triangle normal direction. If off, volume preservation is disabled and if AttributeErrorMetric is active, these errors can be large. Defaults to False.

  • attribute_error (bool, optional) – Decide whether to include data attributes in the error metric. If off, then only geometric error is used to control the decimation. Defaults to False.

  • scalars (bool, optional) – If attribute errors are to be included in the metric (i.e., AttributeErrorMetric is on), then the following flags control which attributes are to be included in the error calculation. Defaults to True.

  • vectors (bool, optional) – See scalars parameter. Defaults to True.

  • normals (bool, optional) – See scalars parameter. Defaults to False.

  • tcoords (bool, optional) – See scalars parameter. Defaults to True.

  • tensors (bool, optional) – See scalars parameter. Defaults to True.

  • scalars_weight (float, optional) – The scaling weight contribution of the scalar attribute. These values are used to weight the contribution of the attributes towards the error metric. Defaults to 0.1.

  • vectors_weight (float, optional) – See scalars weight parameter. Defaults to 0.1.

  • normals_weight (float, optional) – See scalars weight parameter. Defaults to 0.1.

  • tcoords_weight (float, optional) – See scalars weight parameter. Defaults to 0.1.

  • tensors_weight (float, optional) – See scalars weight parameter. Defaults to 0.1.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Returns

outmesh – Decimated mesh. None when inplace=True.

Return type

pyvista.PolyData

Examples

Decimate a sphere while preserving its volume

>>> import pyvista as pv
>>> sphere = pv.Sphere(theta_resolution=90, phi_resolution=90)
>>> print(sphere.n_cells)
15840
>>> dec_sphere = sphere.decimate(0.9, volume_preservation=True)
>>> print(dec_sphere.n_cells)
1584

Notes

If you encounter a segmentation fault or other error, consider using clean to remove any invalid cells before using this filter.

decimate_pro(reduction, feature_angle=45.0, split_angle=75.0, splitting=True, pre_split_mesh=False, preserve_topology=False, inplace=False)

Reduce the number of triangles in a triangular mesh.

It forms a good approximation to the original geometry. Based on the algorithm originally described in “Decimation of Triangle Meshes”, Proc Siggraph 92.

Parameters
  • reduction (float) – Reduction factor. A value of 0.9 will leave 10 % of the original number of vertices.

  • feature_angle (float, optional) – Angle used to define what an edge is (i.e., if the surface normal between two adjacent triangles is >= feature_angle, an edge exists).

  • split_angle (float, optional) – Angle used to control the splitting of the mesh. A split line exists when the surface normals between two edge connected triangles are >= split_angle.

  • splitting (bool, optional) – Controls the splitting of the mesh at corners, along edges, at non-manifold points, or anywhere else a split is required. Turning splitting off will better preserve the original topology of the mesh, but may not necessarily give the exact requested decimation.

  • pre_split_mesh (bool, optional) – Separates the mesh into semi-planar patches, which are disconnected from each other. This can give superior results in some cases. If pre_split_mesh is set to True, the mesh is split with the specified split_angle. Otherwise mesh splitting is deferred as long as possible.

  • preserve_topology (bool, optional) – Controls topology preservation. If on, mesh splitting and hole elimination will not occur. This may limit the maximum reduction that may be achieved.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Decimated mesh. None when inplace=True.

Return type

pyvista.PolyData

delaunay_2d(tol=1e-05, alpha=0.0, offset=1.0, bound=False, inplace=False, edge_source=None, progress_bar=False)

Apply a delaunay 2D filter along the best fitting plane.

Parameters
  • tol (float) – Specify a tolerance to control discarding of closely spaced points. This tolerance is specified as a fraction of the diagonal length of the bounding box of the points.

  • alpha (float) – Specify alpha (or distance) value to control output of this filter. For a non-zero alpha value, only edges or triangles contained within a sphere centered at mesh vertices will be output. Otherwise, only triangles will be output.

  • offset (float) – Specify a multiplier to control the size of the initial, bounding Delaunay triangulation.

  • bound (bool) – Boolean controls whether bounding triangulation points (and associated triangles) are included in the output. (These are introduced as an initial triangulation to begin the triangulation process. This feature is nice for debugging output.)

  • inplace (bool) – If True, overwrite this mesh with the triangulated mesh.

  • edge_source (pyvista.PolyData, optional) – Specify the source object used to specify constrained edges and loops. (This is optional.) If set, and lines/polygons are defined, a constrained triangulation is created. The lines/polygons are assumed to reference points in the input point set (i.e. point ids are identical in the input and source). Note that this method does not connect the pipeline. See SetSourceConnection for connecting the pipeline.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Examples

Extract the points of a sphere and then convert the point cloud to a surface mesh. Note that only the bottom half is converted to a mesh.

>>> import pyvista as pv
>>> points = pv.PolyData(pv.Sphere().points)
>>> mesh = points.delaunay_2d()
>>> mesh.is_all_triangles()
True
delauney_2d()

Apply a delaunay 2D filter along the best fitting plane.

DEPRECATED. Please see pyvista.PolyData.delaunay_2d().

edge_mask(angle)

Return a mask of the points of a surface mesh that has a surface angle greater than angle.

Parameters

angle (float) – Angle to consider an edge.

extrude(vector, inplace=False, progress_bar=False)

Sweep polygonal data creating a “skirt” from free edges.

This will create a line from vertices.

This takes polygonal data as input and generates polygonal data on output. The input dataset is swept according to some extrusion function and creates new polygonal primitives. These primitives form a “skirt” or swept surface. For example, sweeping a line results in a quadrilateral, and sweeping a triangle creates a “wedge”.

There are a number of control parameters for this filter. You can control whether the sweep of a 2D object (i.e., polygon or triangle strip) is capped with the generating geometry via the “Capping” parameter.

The skirt is generated by locating certain topological features. Free edges (edges of polygons or triangle strips only used by one polygon or triangle strips) generate surfaces. This is true also of lines or polylines. Vertices generate lines.

This filter can be used to create 3D fonts, 3D irregular bar charts, or to model 2 1/2D objects like punched plates. It also can be used to create solid objects from 2D polygonal meshes.

Parameters
  • mesh (pyvista.PolyData) – Mesh to extrude.

  • vector (np.ndarray or list) – Direction and length to extrude the mesh in.

  • inplace (bool, optional) – Overwrites the original mesh inplace.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Examples

Extrude a half arc circle

>>> import pyvista
>>> arc = pyvista.CircularArc([-1, 0, 0], [1, 0, 0], [0, 0, 0])
>>> mesh = arc.extrude([0, 0, 1])
>>> mesh.plot()  
fill_holes(hole_size, inplace=False, progress_bar=False)

Fill holes in a pyvista.PolyData or vtk.vtkPolyData object.

Holes are identified by locating boundary edges, linking them together into loops, and then triangulating the resulting loops. Note that you can specify an approximate limit to the size of the hole that can be filled.

Parameters
  • hole_size (float) – Specifies the maximum hole size to fill. This is represented as a radius to the bounding circumsphere containing the hole. Note that this is an approximate area; the actual area cannot be computed without first triangulating the hole.

  • inplace (bool, optional) – Return new mesh or overwrite input.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Returns

mesh – Mesh with holes filled. None when inplace=True

Return type

pyvista.PolyData

Examples

Create a partial sphere with a hole and then fill it

>>> import pyvista as pv
>>> sphere_with_hole = pv.Sphere(end_theta=330)
>>> sphere_with_hole.fill_holes(1000, inplace=True)
>>> edges = sphere_with_hole.extract_feature_edges(feature_edges=False, manifold_edges=False)
>>> assert edges.n_cells is 0
flip_normals()

Flip normals of a triangular mesh by reversing the point ordering.

Examples

Flip the normals of a sphere and plot the normals before and after the flip.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere.plot_normals(mag=0.1)  
>>> sphere.flip_normals()
>>> sphere.plot_normals(mag=0.1)  
geodesic(start_vertex, end_vertex, inplace=False)

Calculate the geodesic path between two vertices using Dijkstra’s algorithm.

This will add an array titled vtkOriginalPointIds of the input mesh’s point ids to the output mesh.

Parameters
  • start_vertex (int) – Vertex index indicating the start point of the geodesic segment.

  • end_vertex (int) – Vertex index indicating the end point of the geodesic segment.

Returns

output – PolyData object consisting of the line segment between the two given vertices.

Return type

pyvista.PolyData

Examples

Plot the path between two points on a sphere

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> path = sphere.geodesic(0, 100)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(sphere)
>>> _ = pl.add_mesh(path, line_width=5, color='k')
>>> pl.show()  
geodesic_distance(start_vertex, end_vertex)

Calculate the geodesic distance between two vertices using Dijkstra’s algorithm.

Parameters
  • start_vertex (int) – Vertex index indicating the start point of the geodesic segment.

  • end_vertex (int) – Vertex index indicating the end point of the geodesic segment.

Returns

length – Length of the geodesic segment.

Return type

float

Examples

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> length = sphere.geodesic_distance(0, 100)
>>> print('Length is %.3f' % length)
Length is 0.812
plot_boundaries(edge_color='red', **kwargs)

Plot boundaries of a mesh.

Parameters
  • edge_color (str, etc.) – The color of the edges when they are added to the plotter.

  • kwargs (optional) – All additional keyword arguments will be passed to pyvista.BasePlotter.add_mesh()

plot_curvature(curv_type='mean', **kwargs)

Plot the curvature.

Parameters
  • curvtype (str, optional) –

    One of the following strings indicating curvature type

    • Mean

    • Gaussian

    • Maximum

    • Minimum

  • **kwargs (optional) – See pyvista.plot()

Returns

cpos – List of camera position, focal point, and view up

Return type

list

plot_normals(show_mesh=True, mag=1.0, flip=False, use_every=1, **kwargs)

Plot the point normals of a mesh.

project_points_to_plane(origin=None, normal=0, 0, 1, inplace=False)

Project points of this mesh to a plane.

Parameters
  • origin (np.ndarray or collections.abc.Sequence, optional) – Plane origin. Defaults the approximate center of the input mesh minus half the length of the input mesh in the direction of the normal.

  • normal (np.ndarray or collections.abc.Sequence, optional) – Plane normal. Defaults to +Z [0, 0, 1]

  • inplace (bool, optional) – Overwrite the original mesh with the projected points

Examples

Flatten a sphere to the XY plane

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> projected = sphere.project_points_to_plane([0, 0, 0])
ray_trace(origin, end_point, first_point=False, plot=False, off_screen=False)

Perform a single ray trace calculation.

This requires a mesh and a line segment defined by an origin and end_point.

Parameters
  • origin (np.ndarray or list) – Start of the line segment.

  • end_point (np.ndarray or list) – End of the line segment.

  • first_point (bool, optional) – Returns intersection of first point only.

  • plot (bool, optional) – Plots ray trace results

  • off_screen (bool, optional) – Plots off screen when plot=True. Used for unit testing.

Returns

  • intersection_points (np.ndarray) – Location of the intersection points. Empty array if no intersections.

  • intersection_cells (np.ndarray) – Indices of the intersection cells. Empty array if no intersections.

Examples

Compute the intersection between a ray from the origin and [1, 0, 0] and a sphere with radius 0.5 centered at the origin

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> point, cell = sphere.ray_trace([0, 0, 0], [1, 0, 0], first_point=True)
>>> print('Intersected at %.3f %.3f %.3f' % (point[0], point[1], point[2]))
Intersected at 0.499 0.000 0.000
remove_points(remove, mode='any', keep_scalars=True, inplace=False)

Rebuild a mesh by removing points.

Only valid for all-triangle meshes.

Parameters
  • remove (np.ndarray) – If remove is a bool array, points that are True will be removed. Otherwise, it is treated as a list of indices.

  • mode (str, optional) – When ‘all’, only faces containing all points flagged for removal will be removed. Default ‘all’

  • keep_scalars (bool, optional) – When True, point and cell scalars will be passed on to the new mesh.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

  • mesh (pyvista.PolyData) – Mesh without the points flagged for removal. Not returned when inplace=False.

  • ridx (np.ndarray) – Indices of new points relative to the original mesh. Not returned when inplace=False.

Examples

Remove the first 100 points from a sphere

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> reduced_sphere = sphere.remove_points(range(100))
ribbon(width=None, scalars=None, angle=0.0, factor=2.0, normal=None, tcoords=False, preference='points')

Create a ribbon of the lines in this dataset.

Note

If there are no lines in the input dataset, then the output will be an empty PolyData mesh.

Parameters
  • width (float) – Set the “half” width of the ribbon. If the width is allowed to vary, this is the minimum width. The default is 10% the length

  • scalars (str, optional) – String name of the scalars array to use to vary the ribbon width. This is only used if a scalars array is specified.

  • angle (float) – Set the offset angle of the ribbon from the line normal. (The angle is expressed in degrees.) The default is 0.0

  • factor (float) – Set the maximum ribbon width in terms of a multiple of the minimum width. The default is 2.0

  • normal (tuple(float), optional) – Normal to use as default

  • tcoords (bool, str, optional) – If True, generate texture coordinates along the ribbon. This can also be specified to generate the texture coordinates in the following ways: 'length', 'normalized',

Examples

Convert a line to a ribbon and plot it.

>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> path = sphere.geodesic(0, 100)
>>> ribbon = path.ribbon()
>>> pv.plot([sphere, ribbon])  
smooth(n_iter=20, relaxation_factor=0.01, convergence=0.0, edge_angle=15, feature_angle=45, boundary_smoothing=True, feature_smoothing=False, inplace=False)

Adjust point coordinates using Laplacian smoothing.

The effect is to “relax” the mesh, making the cells better shaped and the vertices more evenly distributed.

Parameters
  • n_iter (int) – Number of iterations for Laplacian smoothing.

  • relaxation_factor (float, optional) – Relaxation factor controls the amount of displacement in a single iteration. Generally a lower relaxation factor and higher number of iterations is numerically more stable.

  • convergence (float, optional) – Convergence criterion for the iteration process. Smaller numbers result in more smoothing iterations. Range from (0 to 1).

  • edge_angle (float, optional) – Edge angle to control smoothing along edges (either interior or boundary).

  • feature_angle (float, optional) – Feature angle for sharp edge identification.

  • boundary_smoothing (bool, optional) – Boolean flag to control smoothing of boundary edges.

  • feature_smoothing (bool, optional) – Boolean flag to control smoothing of feature edges.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Smoothed mesh. None when inplace=True.

Return type

pyvista.PolyData

Examples

Smooth the edges of an all triangular cube

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(5).clean()
>>> smooth_cube = cube.smooth(1000, feature_smoothing=False)
>>> n_edge_cells = cube.extract_feature_edges().n_cells
>>> n_smooth_cells = smooth_cube.extract_feature_edges().n_cells
>>> print('Sharp Edges on Cube:        %d' % n_edge_cells)
Sharp Edges on Cube:        384
>>> print('Sharp Edges on Smooth Cube: %d' % n_smooth_cells)
Sharp Edges on Smooth Cube: 12
strip(join=False, max_length=1000, pass_cell_data=False, pass_cell_ids=False, pass_point_ids=False)

Strip poly data cells.

Generates triangle strips and/or poly-lines from input polygons, triangle strips, and lines.

Polygons are assembled into triangle strips only if they are triangles; other types of polygons are passed through to the output and not stripped. (Use triangulate filter to triangulate non-triangular polygons prior to running this filter if you need to strip all the data.) The filter will pass through (to the output) vertices if they are present in the input polydata. Also note that if triangle strips or polylines are defined in the input they are passed through and not joined nor extended. (If you wish to strip these use triangulate filter to fragment the input into triangles and lines prior to running this filter.)

Parameters
  • join (bool) – If on, the output polygonal segments will be joined if they are contiguous. This is useful after slicing a surface. The default is off.

  • max_length (int) – Specify the maximum number of triangles in a triangle strip, and/or the maximum number of lines in a poly-line.

  • pass_cell_data (bool) – Enable/Disable passing of the CellData in the input to the output as FieldData. Note the field data is transformed.

  • pass_cell_ids (bool) – If on, the output polygonal dataset will have a celldata array that holds the cell index of the original 3D cell that produced each output cell. This is useful for picking. The default is off to conserve memory.

  • pass_point_ids (bool) – If on, the output polygonal dataset will have a pointdata array that holds the point index of the original vertex that produced each output vertex. This is useful for picking. The default is off to conserve memory.

Examples

>>> from pyvista import examples
>>> mesh = examples.load_airplane()
>>> slc = mesh.slice(normal='z', origin=(0,0,-10))
>>> stripped = slc.strip()
>>> stripped.n_cells
1
subdivide(nsub, subfilter='linear', inplace=False)

Increase the number of triangles in a single, connected triangular mesh.

Uses one of the following vtk subdivision filters to subdivide a mesh. vtkButterflySubdivisionFilter vtkLoopSubdivisionFilter vtkLinearSubdivisionFilter

Linear subdivision results in the fastest mesh subdivision, but it does not smooth mesh edges, but rather splits each triangle into 4 smaller triangles.

Butterfly and loop subdivision perform smoothing when dividing, and may introduce artifacts into the mesh when dividing.

Subdivision filter appears to fail for multiple part meshes. Should be one single mesh.

Parameters
  • nsub (int) – Number of subdivisions. Each subdivision creates 4 new triangles, so the number of resulting triangles is nface*4**nsub where nface is the current number of faces.

  • subfilter (string, optional) – Can be one of the following: ‘butterfly’, ‘loop’, ‘linear’

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – pyvista polydata object. None when inplace=True

Return type

Polydata object

Examples

>>> from pyvista import examples
>>> import pyvista
>>> mesh = pyvista.PolyData(examples.planefile)
>>> submesh = mesh.subdivide(1, 'loop') 

Alternatively, update the mesh in-place

>>> mesh.subdivide(1, 'loop', inplace=True) 
tri_filter(inplace=False)

Return an all triangle mesh.

DEPRECATED: Please use triangulate instead.

triangulate(inplace=False)

Return an all triangle mesh.

More complex polygons will be broken down into tetrahedrals.

Parameters

inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Mesh containing only triangles. None when inplace=True

Return type

pyvista.PolyData

tube(radius=None, scalars=None, capping=True, n_sides=20, radius_factor=10, preference='point', inplace=False)

Generate a tube around each input line.

The radius of the tube can be set to linearly vary with a scalar value.

Parameters
  • radius (float) – Minimum tube radius (minimum because the tube radius may vary).

  • scalars (str, optional) – scalars array by which the radius varies

  • capping (bool, optional) – Turn on/off whether to cap the ends with polygons. Default True.

  • n_sides (int, optional) – Set the number of sides for the tube. Minimum of 3.

  • radius_factor (float, optional) – Maximum tube radius in terms of a multiple of the minimum radius.

  • preference (str, optional) – The field preference when searching for the scalars array by name.

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Tube-filtered mesh. None when inplace=True.

Return type

pyvista.PolyData

Examples

Convert a single line to a tube

>>> import pyvista as pv
>>> line = pv.Line()
>>> tube = line.tube(radius=0.02)
>>> print('Line Cells:', line.n_cells)
Line Cells: 1
>>> print('Tube Cells:', tube.n_cells)
Tube Cells: 22

UnstructuredGrid Filters

The pyvista.UnstructuredGridFilters is inherited by pyvista.UnstructuredGrid making all the following filters available as callable methods directly from any UnstructuredGrid mesh.

Methods

delaunay_2d([tol, alpha, offset, bound, …])

Apply a delaunay 2D filter along the best fitting plane.

class pyvista.UnstructuredGridFilters(*args, **kwargs)

Bases: pyvista.core.filters.DataSetFilters

An internal class to manage filtes/algorithms for unstructured grid datasets.

delaunay_2d(tol=1e-05, alpha=0.0, offset=1.0, bound=False, progress_bar=False)

Apply a delaunay 2D filter along the best fitting plane.

This extracts the grid’s points and performs the triangulation on those alone.

Parameters

progress_bar (bool, optional) – Display a progress bar to indicate progress.

UniformGrid Filters

The pyvista.UniformGridFilters is inherited by pyvista.UniformGrid making all the following filters available as callable methods directly from any UniformGrid mesh.

Methods

extract_subset(voi[, rate, boundary])

Select piece (e.g., volume of interest).

gaussian_smooth([radius_factor, std_dev, …])

Smooth the data with a Gaussian kernel.

class pyvista.UniformGridFilters(*args, **kwargs)

Bases: pyvista.core.filters.DataSetFilters

An internal class to manage filtes/algorithms for uniform grid datasets.

extract_subset(voi, rate=1, 1, 1, boundary=False)

Select piece (e.g., volume of interest).

To use this filter set the VOI ivar which are i-j-k min/max indices that specify a rectangular region in the data. (Note that these are 0-offset.) You can also specify a sampling rate to subsample the data.

Typical applications of this filter are to extract a slice from a volume for image processing, subsampling large volumes to reduce data size, or extracting regions of a volume with interesting data.

Parameters
  • voi (tuple(int)) – Length 6 iterable of ints: (xmin, xmax, ymin, ymax, zmin, zmax). These bounds specify the volume of interest in i-j-k min/max indices.

  • rate (tuple(int)) – Length 3 iterable of ints: (xrate, yrate, zrate). Default: (1, 1, 1)

  • boundary (bool) – Control whether to enforce that the “boundary” of the grid is output in the subsampling process. (This only has effect when the rate in any direction is not equal to 1). When this is on, the subsampling will always include the boundary of the grid even though the sample rate is not an even multiple of the grid dimensions. (By default this is off.)

gaussian_smooth(radius_factor=1.5, std_dev=2.0, scalars=None, preference='points', progress_bar=False)

Smooth the data with a Gaussian kernel.

Parameters
  • radius_factor (float or iterable, optional) – Unitless factor to limit the extent of the kernel.

  • std_dev (float or iterable, optional) – Standard deviation of the kernel in pixel units.

  • scalars (str, optional) – Name of scalars to process. Defaults to currently active scalars.

  • preference (str, optional) – When scalars is specified, this is the preferred array type to search for in the dataset. Must be either 'point' or 'cell'

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Composite Filters

These are filters that can be applied to composite datasets, i.e. pyvista.MultiBlock. The pyvista.CompositeFilters class inherits many but not all of the filters from pyvista.DataSetFilters.

Methods

cell_centers([vertex])

Generate points at the center of the cells in this dataset.

cell_data_to_point_data([pass_cell_data])

Transform cell data into point data.

clip([normal, origin, invert, value, inplace])

Clip a dataset by a plane by specifying the origin and normal.

clip_box([bounds, invert, factor])

Clip a dataset by a bounding box defined by the bounds.

combine([merge_points])

Append all blocks into a single unstructured grid.

compute_cell_sizes([length, area, volume, …])

Compute sizes for 1D (length), 2D (area) and 3D (volume) cells.

elevation([low_point, high_point, …])

Generate scalar values on a dataset.

extract_all_edges([progress_bar])

Extract all the internal/external edges of the dataset as PolyData.

extract_geometry()

Combine the geomertry of all blocks into a single PolyData object.

outline([generate_faces, nested])

Produce an outline of the full extent for the all blocks in this composite dataset.

outline_corners([factor, nested])

Produce an outline of the corners for the all blocks in this composite dataset.

point_data_to_cell_data([pass_point_data])

Transform point data into cell data.

slice([normal, origin, generate_triangles, …])

Slice a dataset by a plane at the specified origin and normal vector orientation.

slice_along_axis([n, axis, tolerance, …])

Create many slices of the input dataset along a specified axis.

slice_along_line(line[, generate_triangles, …])

Slice a dataset using a polyline/spline as the path.

slice_orthogonal([x, y, z, …])

Create three orthogonal slices through the dataset on the three cartesian planes.

triangulate([inplace])

Return an all triangle mesh.

wireframe([progress_bar])

Extract all the internal/external edges of the dataset as PolyData.

class pyvista.CompositeFilters(*args, **kwargs)

Bases: object

An internal class to manage filtes/algorithms for composite datasets.

cell_centers(vertex=True)

Generate points at the center of the cells in this dataset.

These points can be used for placing glyphs / vectors.

Parameters

vertex (bool) – Enable/disable the generation of vertex cells.

cell_data_to_point_data(pass_cell_data=False)

Transform cell data into point data.

Point data are specified per node and cell data specified within cells. Optionally, the input point data can be passed through to the output.

The method of transformation is based on averaging the data values of all cells using a particular point. Optionally, the input cell data can be passed through to the output as well.

See also: pyvista.DataSetFilters.point_data_to_cell_data()

Parameters

pass_cell_data (bool) – If enabled, pass the input cell data through to the output

clip(normal='x', origin=None, invert=True, value=0.0, inplace=False)

Clip a dataset by a plane by specifying the origin and normal.

If no parameters are given the clip will occur in the center of that dataset.

Parameters
  • normal (tuple(float) or str) – Length 3 tuple for the normal vector direction. Can also be specified as a string conventional direction such as 'x' for (1,0,0) or '-x' for (-1,0,0), etc.

  • origin (tuple(float), optional) – The center (x,y,z) coordinate of the plane on which the clip occurs. The default is the center of the dataset.

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

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

  • inplace (bool, optional) – Updates mesh in-place while returning nothing.

Returns

mesh – Clipped mesh when inplace=False. When inplace=True, None

Return type

pyvista.PolyData

Examples

Clip a cube along the +X direction. triangulate is used as the cube is initially composed of quadrilateral faces and subdivide only works on triangles.

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip()

Clip a cube in the +Z direction. This leaves half a cube below the XY plane.

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip('z')
clip_box(bounds=None, invert=True, factor=0.35)

Clip a dataset by a bounding box defined by the bounds.

If no bounds are given, a corner of the dataset bounds will be removed.

Parameters
  • bounds (tuple(float)) – Length 6 sequence of floats: (xmin, xmax, ymin, ymax, zmin, zmax). Length 3 sequence of floats: distances from the min coordinate of of the input mesh. Single float value: uniform distance from the min coordinate. Length 12 sequence of length 3 sequence of floats: a plane collection (normal, center, …). pyvista.PolyData: if a poly mesh is passed that represents a box with 6 faces that all form a standard box, then planes will be extracted from the box to define the clipping region.

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

  • factor (float, optional) – If bounds are not given this is the factor along each axis to extract the default box.

Examples

Clip a corner of a cube. The bounds of a cube are normally [-0.5, 0.5, -0.5, 0.5, -0.5, 0.5], and this removes 1/8 of the cube’s surface.

>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip_box([0, 1, 0, 1, 0, 1])
combine(merge_points=False)

Append all blocks into a single unstructured grid.

Parameters

merge_points (bool, optional) – Merge coincidental points.

compute_cell_sizes(length=True, area=True, volume=True, progress_bar=False)

Compute sizes for 1D (length), 2D (area) and 3D (volume) cells.

Parameters
  • length (bool) – Specify whether or not to compute the length of 1D cells.

  • area (bool) – Specify whether or not to compute the area of 2D cells.

  • volume (bool) – Specify whether or not to compute the volume of 3D cells.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

elevation(low_point=None, high_point=None, scalar_range=None, preference='point', set_active=True, progress_bar=False)

Generate scalar values on a dataset.

The scalar values lie within a user specified range, and are generated by computing a projection of each dataset point onto a line. The line can be oriented arbitrarily. A typical example is to generate scalars based on elevation or height above a plane.

Parameters
  • low_point (tuple(float), optional) – The low point of the projection line in 3D space. Default is bottom center of the dataset. Otherwise pass a length 3 tuple(float).

  • high_point (tuple(float), optional) – The high point of the projection line in 3D space. Default is top center of the dataset. Otherwise pass a length 3 tuple(float).

  • scalar_range (str or tuple(float), optional) – The scalar range to project to the low and high points on the line that will be mapped to the dataset. If None given, the values will be computed from the elevation (Z component) range between the high and low points. Min and max of a range can be given as a length 2 tuple(float). If str name of scalara array present in the dataset given, the valid range of that array will be used.

  • preference (str, optional) – When an array name is specified for scalar_range, this is the preferred array type to search for in the dataset. Must be either ‘point’ or ‘cell’.

  • set_active (bool, optional) – A boolean flag on whether or not to set the new Elevation scalar as the active scalars array on the output dataset.

  • progress_bar (bool, optional) – Display a progress bar to indicate progress.

Warning

This will create a scalars array named Elevation on the point data of the input dataset and overasdf write an array named Elevation if present.

extract_all_edges(progress_bar=False)

Extract all the internal/external edges of the dataset as PolyData.

This produces a full wireframe representation of the input dataset.

Parameters

progress_bar (bool, optional) – Display a progress bar to indicate progress.

extract_geometry()

Combine the geomertry of all blocks into a single PolyData object.

Place this filter at the end of a pipeline before a polydata consumer such as a polydata mapper to extract geometry from all blocks and append them to one polydata object.

outline(generate_faces=False, nested=False)

Produce an outline of the full extent for the all blocks in this composite dataset.

Parameters
  • generate_faces (bool, optional) – Generate solid faces for the box. This is off by default

  • nested (bool, optional) – If True, these creates individual outlines for each nested dataset

outline_corners(factor=0.2, nested=False)

Produce an outline of the corners for the all blocks in this composite dataset.

Parameters
  • factor (float, optional) – controls the relative size of the corners to the length of the corresponding bounds

  • ested (bool, optional) – If True, these creates individual outlines for each nested dataset

point_data_to_cell_data(pass_point_data=False)

Transform point data into cell data.

Point data are specified per node and cell data specified within cells. Optionally, the input point data can be passed through to the output.

See also: pyvista.DataSetFilters.cell_data_to_point_data()

Parameters

pass_point_data (bool) – If enabled, pass the input point data through to the output

slice(normal='x', origin=None, generate_triangles=False, contour=False)

Slice a dataset by a plane at the specified origin and normal vector orientation.

If no origin is specified, the center of the input dataset will be used.

Parameters
  • normal (tuple(float) or str) – Length 3 tuple for the normal vector direction. Can also be specified as a string conventional direction such as 'x' for (1,0,0) or '-x' for (-1,0,0)`, etc.

  • origin (tuple(float)) – The center (x,y,z) coordinate of the plane on which the slice occurs

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

slice_along_axis(n=5, axis='x', tolerance=None, generate_triangles=False, contour=False, bounds=None, center=None)

Create many slices of the input dataset along a specified axis.

Parameters
  • n (int) – The number of slices to create

  • axis (str or int) – The axis to generate the slices along. Perpendicular to the slices. Can be string name ('x', 'y', or 'z') or axis index (0, 1, or 2).

  • tolerance (float, optional) – The tolerance to the edge of the dataset bounds to create the slices

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

slice_along_line(line, generate_triangles=False, contour=False)

Slice a dataset using a polyline/spline as the path.

This also works for lines generated with pyvista.Line()

Parameters
  • line (pyvista.PolyData) – A PolyData object containing one single PolyLine cell.

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

slice_orthogonal(x=None, y=None, z=None, generate_triangles=False, contour=False)

Create three orthogonal slices through the dataset on the three cartesian planes.

Yields a MutliBlock dataset of the three slices.

Parameters
  • x (float) – The X location of the YZ slice

  • y (float) – The Y location of the XZ slice

  • z (float) – The Z location of the XY slice

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

  • contour (bool, optional) – If True, apply a contour filter after slicing

triangulate(inplace=False)

Return an all triangle mesh.

More complex polygons will be broken down into triangles.

Parameters

inplace (bool, optional) – Updates mesh in-place while returning None.

Returns

mesh – Mesh containing only triangles. None when inplace=True

Return type

pyvista.UnstructuredGrid

wireframe(progress_bar=False)

Extract all the internal/external edges of the dataset as PolyData.

This produces a full wireframe representation of the input dataset.

Parameters

progress_bar (bool, optional) – Display a progress bar to indicate progress.