doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
inverted()[source] Return the corresponding inverse transformation. It holds x == self.inverted().transform(self.transform(x)). The return value of this method should be treated as temporary. An update to self does not cause a corresponding update to its inverted copy.
matplotlib.transformations#matplotlib.transforms.Transform.inverted
is_separable=False True if this transform is separable in the x- and y- dimensions.
matplotlib.transformations#matplotlib.transforms.Transform.is_separable
output_dims=None The number of output dimensions of this transform. Must be overridden (with integers) in the subclass.
matplotlib.transformations#matplotlib.transforms.Transform.output_dims
transform(values)[source] Apply this transformation on the given array of values. Parameters valuesarray The input values as NumPy array of length input_dims or shape (N x input_dims). Returns array The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input.
matplotlib.transformations#matplotlib.transforms.Transform.transform
transform_affine(values)[source] Apply only the affine part of this transformation on the given array of values. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In non-affine transformations, this is generally a no-op. In affine transformations, this is equivalent to transform(values). Parameters valuesarray The input values as NumPy array of length input_dims or shape (N x input_dims). Returns array The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input.
matplotlib.transformations#matplotlib.transforms.Transform.transform_affine
transform_angles(angles, pts, radians=False, pushoff=1e-05)[source] Transform a set of angles anchored at specific locations. Parameters angles(N,) array-like The angles to transform. pts(N, 2) array-like The points where the angles are anchored. radiansbool, default: False Whether angles are radians or degrees. pushofffloat For each point in pts and angle in angles, the transformed angle is computed by transforming a segment of length pushoff starting at that point and making that angle relative to the horizontal axis, and measuring the angle between the horizontal axis and the transformed segment. Returns (N,) array
matplotlib.transformations#matplotlib.transforms.Transform.transform_angles
transform_bbox(bbox)[source] Transform the given bounding box. For smarter transforms including caching (a common requirement in Matplotlib), see TransformedBbox.
matplotlib.transformations#matplotlib.transforms.Transform.transform_bbox
transform_non_affine(values)[source] Apply only the non-affine part of this transformation. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In non-affine transformations, this is generally equivalent to transform(values). In affine transformations, this is always a no-op. Parameters valuesarray The input values as NumPy array of length input_dims or shape (N x input_dims). Returns array The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input.
matplotlib.transformations#matplotlib.transforms.Transform.transform_non_affine
transform_path(path)[source] Apply the transform to Path path, returning a new Path. In some cases, this transform may insert curves into the path that began as line segments.
matplotlib.transformations#matplotlib.transforms.Transform.transform_path
transform_path_affine(path)[source] Apply the affine part of this transform to Path path, returning a new Path. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values)).
matplotlib.transformations#matplotlib.transforms.Transform.transform_path_affine
transform_path_non_affine(path)[source] Apply the non-affine part of this transform to Path path, returning a new Path. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values)).
matplotlib.transformations#matplotlib.transforms.Transform.transform_path_non_affine
transform_point(point)[source] Return a transformed point. This function is only kept for backcompatibility; the more general transform method is capable of transforming both a list of points and a single point. The point is given as a sequence of length input_dims. The transformed point is returned as a sequence of length output_dims.
matplotlib.transformations#matplotlib.transforms.Transform.transform_point
classmatplotlib.transforms.TransformedBbox(bbox, transform, **kwargs)[source] Bases: matplotlib.transforms.BboxBase A Bbox that is automatically transformed by a given transform. When either the child bounding box or transform changes, the bounds of this bbox will update accordingly. Parameters bboxBbox transformTransform __init__(bbox, transform, **kwargs)[source] Parameters bboxBbox transformTransform __module__='matplotlib.transforms' __str__()[source] Return str(self). get_points()[source]
matplotlib.transformations#matplotlib.transforms.TransformedBbox
__init__(bbox, transform, **kwargs)[source] Parameters bboxBbox transformTransform
matplotlib.transformations#matplotlib.transforms.TransformedBbox.__init__
__module__='matplotlib.transforms'
matplotlib.transformations#matplotlib.transforms.TransformedBbox.__module__
__str__()[source] Return str(self).
matplotlib.transformations#matplotlib.transforms.TransformedBbox.__str__
get_points()[source]
matplotlib.transformations#matplotlib.transforms.TransformedBbox.get_points
classmatplotlib.transforms.TransformedPatchPath(patch)[source] Bases: matplotlib.transforms.TransformedPath A TransformedPatchPath caches a non-affine transformed copy of the Patch. This cached copy is automatically updated when the non-affine part of the transform or the patch changes. Parameters patchPatch __init__(patch)[source] Parameters patchPatch __module__='matplotlib.transforms'
matplotlib.transformations#matplotlib.transforms.TransformedPatchPath
__init__(patch)[source] Parameters patchPatch
matplotlib.transformations#matplotlib.transforms.TransformedPatchPath.__init__
__module__='matplotlib.transforms'
matplotlib.transformations#matplotlib.transforms.TransformedPatchPath.__module__
classmatplotlib.transforms.TransformedPath(path, transform)[source] Bases: matplotlib.transforms.TransformNode A TransformedPath caches a non-affine transformed copy of the Path. This cached copy is automatically updated when the non-affine part of the transform changes. Note Paths are considered immutable by this class. Any update to the path's vertices/codes will not trigger a transform recomputation. Parameters pathPath transformTransform __init__(path, transform)[source] Parameters pathPath transformTransform __module__='matplotlib.transforms' get_affine()[source] get_fully_transformed_path()[source] Return a fully-transformed copy of the child path. get_transformed_path_and_affine()[source] Return a copy of the child path, with the non-affine part of the transform already applied, along with the affine part of the path necessary to complete the transformation. get_transformed_points_and_affine()[source] Return a copy of the child path, with the non-affine part of the transform already applied, along with the affine part of the path necessary to complete the transformation. Unlike get_transformed_path_and_affine(), no interpolation will be performed.
matplotlib.transformations#matplotlib.transforms.TransformedPath
__init__(path, transform)[source] Parameters pathPath transformTransform
matplotlib.transformations#matplotlib.transforms.TransformedPath.__init__
__module__='matplotlib.transforms'
matplotlib.transformations#matplotlib.transforms.TransformedPath.__module__
get_affine()[source]
matplotlib.transformations#matplotlib.transforms.TransformedPath.get_affine
get_fully_transformed_path()[source] Return a fully-transformed copy of the child path.
matplotlib.transformations#matplotlib.transforms.TransformedPath.get_fully_transformed_path
get_transformed_path_and_affine()[source] Return a copy of the child path, with the non-affine part of the transform already applied, along with the affine part of the path necessary to complete the transformation.
matplotlib.transformations#matplotlib.transforms.TransformedPath.get_transformed_path_and_affine
get_transformed_points_and_affine()[source] Return a copy of the child path, with the non-affine part of the transform already applied, along with the affine part of the path necessary to complete the transformation. Unlike get_transformed_path_and_affine(), no interpolation will be performed.
matplotlib.transformations#matplotlib.transforms.TransformedPath.get_transformed_points_and_affine
classmatplotlib.transforms.TransformNode(shorthand_name=None)[source] Bases: object The base class for anything that participates in the transform tree and needs to invalidate its parents or be invalidated. This includes classes that are not really transforms, such as bounding boxes, since some transforms depend on bounding boxes to compute their values. Parameters shorthand_namestr A string representing the "name" of the transform. The name carries no significance other than to improve the readability of str(transform) when DEBUG=True. INVALID=3 INVALID_AFFINE=2 INVALID_NON_AFFINE=1 __copy__()[source] __deepcopy__(memo)[source] __dict__=mappingproxy({'__module__': 'matplotlib.transforms', '__doc__': '\n The base class for anything that participates in the transform tree\n and needs to invalidate its parents or be invalidated. This includes\n classes that are not really transforms, such as bounding boxes, since some\n transforms depend on bounding boxes to compute their values.\n ', 'INVALID_NON_AFFINE': 1, 'INVALID_AFFINE': 2, 'INVALID': 3, 'is_affine': False, 'is_bbox': False, 'pass_through': False, '__init__': <function TransformNode.__init__>, '__getstate__': <function TransformNode.__getstate__>, '__setstate__': <function TransformNode.__setstate__>, '__copy__': <function TransformNode.__copy__>, '__deepcopy__': <function TransformNode.__deepcopy__>, 'invalidate': <function TransformNode.invalidate>, '_invalidate_internal': <function TransformNode._invalidate_internal>, 'set_children': <function TransformNode.set_children>, 'frozen': <function TransformNode.frozen>, '__dict__': <attribute '__dict__' of 'TransformNode' objects>, '__weakref__': <attribute '__weakref__' of 'TransformNode' objects>, '__annotations__': {}}) __getstate__()[source] __init__(shorthand_name=None)[source] Parameters shorthand_namestr A string representing the "name" of the transform. The name carries no significance other than to improve the readability of str(transform) when DEBUG=True. __module__='matplotlib.transforms' __setstate__(data_dict)[source] __weakref__ list of weak references to the object (if defined) frozen()[source] Return a frozen copy of this transform node. The frozen copy will not be updated when its children change. Useful for storing a previously known state of a transform where copy.deepcopy() might normally be used. invalidate()[source] Invalidate this TransformNode and triggers an invalidation of its ancestors. Should be called any time the transform changes. is_affine=False is_bbox=False pass_through=False If pass_through is True, all ancestors will always be invalidated, even if 'self' is already invalid. set_children(*children)[source] Set the children of the transform, to let the invalidation system know which transforms can invalidate this transform. Should be called from the constructor of any transforms that depend on other transforms.
matplotlib.transformations#matplotlib.transforms.TransformNode
__copy__()[source]
matplotlib.transformations#matplotlib.transforms.TransformNode.__copy__
__deepcopy__(memo)[source]
matplotlib.transformations#matplotlib.transforms.TransformNode.__deepcopy__
__dict__=mappingproxy({'__module__': 'matplotlib.transforms', '__doc__': '\n The base class for anything that participates in the transform tree\n and needs to invalidate its parents or be invalidated. This includes\n classes that are not really transforms, such as bounding boxes, since some\n transforms depend on bounding boxes to compute their values.\n ', 'INVALID_NON_AFFINE': 1, 'INVALID_AFFINE': 2, 'INVALID': 3, 'is_affine': False, 'is_bbox': False, 'pass_through': False, '__init__': <function TransformNode.__init__>, '__getstate__': <function TransformNode.__getstate__>, '__setstate__': <function TransformNode.__setstate__>, '__copy__': <function TransformNode.__copy__>, '__deepcopy__': <function TransformNode.__deepcopy__>, 'invalidate': <function TransformNode.invalidate>, '_invalidate_internal': <function TransformNode._invalidate_internal>, 'set_children': <function TransformNode.set_children>, 'frozen': <function TransformNode.frozen>, '__dict__': <attribute '__dict__' of 'TransformNode' objects>, '__weakref__': <attribute '__weakref__' of 'TransformNode' objects>, '__annotations__': {}})
matplotlib.transformations#matplotlib.transforms.TransformNode.__dict__
__getstate__()[source]
matplotlib.transformations#matplotlib.transforms.TransformNode.__getstate__
__init__(shorthand_name=None)[source] Parameters shorthand_namestr A string representing the "name" of the transform. The name carries no significance other than to improve the readability of str(transform) when DEBUG=True.
matplotlib.transformations#matplotlib.transforms.TransformNode.__init__
__module__='matplotlib.transforms'
matplotlib.transformations#matplotlib.transforms.TransformNode.__module__
__setstate__(data_dict)[source]
matplotlib.transformations#matplotlib.transforms.TransformNode.__setstate__
__weakref__ list of weak references to the object (if defined)
matplotlib.transformations#matplotlib.transforms.TransformNode.__weakref__
frozen()[source] Return a frozen copy of this transform node. The frozen copy will not be updated when its children change. Useful for storing a previously known state of a transform where copy.deepcopy() might normally be used.
matplotlib.transformations#matplotlib.transforms.TransformNode.frozen
INVALID=3
matplotlib.transformations#matplotlib.transforms.TransformNode.INVALID
INVALID_AFFINE=2
matplotlib.transformations#matplotlib.transforms.TransformNode.INVALID_AFFINE
INVALID_NON_AFFINE=1
matplotlib.transformations#matplotlib.transforms.TransformNode.INVALID_NON_AFFINE
invalidate()[source] Invalidate this TransformNode and triggers an invalidation of its ancestors. Should be called any time the transform changes.
matplotlib.transformations#matplotlib.transforms.TransformNode.invalidate
is_affine=False
matplotlib.transformations#matplotlib.transforms.TransformNode.is_affine
is_bbox=False
matplotlib.transformations#matplotlib.transforms.TransformNode.is_bbox
pass_through=False If pass_through is True, all ancestors will always be invalidated, even if 'self' is already invalid.
matplotlib.transformations#matplotlib.transforms.TransformNode.pass_through
set_children(*children)[source] Set the children of the transform, to let the invalidation system know which transforms can invalidate this transform. Should be called from the constructor of any transforms that depend on other transforms.
matplotlib.transformations#matplotlib.transforms.TransformNode.set_children
classmatplotlib.transforms.TransformWrapper(child)[source] Bases: matplotlib.transforms.Transform A helper class that holds a single child transform and acts equivalently to it. This is useful if a node of the transform tree must be replaced at run time with a transform of a different type. This class allows that replacement to correctly trigger invalidation. TransformWrapper instances must have the same input and output dimensions during their entire lifetime, so the child transform may only be replaced with another child transform of the same dimensions. child: A Transform instance. This child may later be replaced with set(). __eq__(other)[source] Return self==value. __hash__=None __init__(child)[source] child: A Transform instance. This child may later be replaced with set(). __module__='matplotlib.transforms' __str__()[source] Return str(self). frozen()[source] Return a frozen copy of this transform node. The frozen copy will not be updated when its children change. Useful for storing a previously known state of a transform where copy.deepcopy() might normally be used. propertyhas_inverse bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed. propertyis_affine bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed. propertyis_separable bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed. pass_through=True If pass_through is True, all ancestors will always be invalidated, even if 'self' is already invalid. set(child)[source] Replace the current child of this transform with another one. The new child must have the same number of input and output dimensions as the current child.
matplotlib.transformations#matplotlib.transforms.TransformWrapper
__eq__(other)[source] Return self==value.
matplotlib.transformations#matplotlib.transforms.TransformWrapper.__eq__
__hash__=None
matplotlib.transformations#matplotlib.transforms.TransformWrapper.__hash__
__init__(child)[source] child: A Transform instance. This child may later be replaced with set().
matplotlib.transformations#matplotlib.transforms.TransformWrapper.__init__
__module__='matplotlib.transforms'
matplotlib.transformations#matplotlib.transforms.TransformWrapper.__module__
__str__()[source] Return str(self).
matplotlib.transformations#matplotlib.transforms.TransformWrapper.__str__
frozen()[source] Return a frozen copy of this transform node. The frozen copy will not be updated when its children change. Useful for storing a previously known state of a transform where copy.deepcopy() might normally be used.
matplotlib.transformations#matplotlib.transforms.TransformWrapper.frozen
pass_through=True If pass_through is True, all ancestors will always be invalidated, even if 'self' is already invalid.
matplotlib.transformations#matplotlib.transforms.TransformWrapper.pass_through
set(child)[source] Replace the current child of this transform with another one. The new child must have the same number of input and output dimensions as the current child.
matplotlib.transformations#matplotlib.transforms.TransformWrapper.set
matplotlib.tri Unstructured triangular grid functions. classmatplotlib.tri.Triangulation(x, y, triangles=None, mask=None)[source] An unstructured triangular grid consisting of npoints points and ntri triangles. The triangles can either be specified by the user or automatically generated using a Delaunay triangulation. Parameters x, y(npoints,) array-like Coordinates of grid points. triangles(ntri, 3) array-like of int, optional For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If not specified, the Delaunay triangulation is calculated. mask(ntri,) array-like of bool, optional Which triangles are masked out. Notes For a Triangulation to be valid it must not have duplicate points, triangles formed from colinear points, or overlapping triangles. Attributes triangles(ntri, 3) array of int For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If you want to take the mask into account, use get_masked_triangles instead. mask(ntri, 3) array of bool Masked out triangles. is_delaunaybool Whether the Triangulation is a calculated Delaunay triangulation (where triangles was not specified) or not. calculate_plane_coefficients(z)[source] Calculate plane equation coefficients for all unmasked triangles from the point (x, y) coordinates and specified z-array of shape (npoints). The returned array has shape (npoints, 3) and allows z-value at (x, y) position in triangle tri to be calculated using z = array[tri, 0] * x  + array[tri, 1] * y + array[tri, 2]. propertyedges Return integer array of shape (nedges, 2) containing all edges of non-masked triangles. Each row defines an edge by it's start point index and end point index. Each edge appears only once, i.e. for an edge between points i and j, there will only be either (i, j) or (j, i). get_cpp_triangulation()[source] Return the underlying C++ Triangulation object, creating it if necessary. staticget_from_args_and_kwargs(*args, **kwargs)[source] Return a Triangulation object from the args and kwargs, and the remaining args and kwargs with the consumed values removed. There are two alternatives: either the first argument is a Triangulation object, in which case it is returned, or the args and kwargs are sufficient to create a new Triangulation to return. In the latter case, see Triangulation.__init__ for the possible args and kwargs. get_masked_triangles()[source] Return an array of triangles that are not masked. get_trifinder()[source] Return the default matplotlib.tri.TriFinder of this triangulation, creating it if necessary. This allows the same TriFinder object to be easily shared. propertyneighbors Return integer array of shape (ntri, 3) containing neighbor triangles. For each triangle, the indices of the three triangles that share the same edges, or -1 if there is no such neighboring triangle. neighbors[i, j] is the triangle that is the neighbor to the edge from point index triangles[i, j] to point index triangles[i, (j+1)%3]. set_mask(mask)[source] Set or clear the mask array. Parameters maskNone or bool array of length ntri classmatplotlib.tri.TriContourSet(ax, *args, **kwargs)[source] Bases: matplotlib.contour.ContourSet Create and store a set of contour lines or filled regions for a triangular grid. This class is typically not instantiated directly by the user but by tricontour and tricontourf. Attributes axAxes The Axes object in which the contours are drawn. collectionssilent_list of PathCollections The Artists representing the contour. This is a list of PathCollections for both line and filled contours. levelsarray The values of the contour levels. layersarray Same as levels for line contours; half-way between levels for filled contours. See ContourSet._process_colors. Draw triangular grid contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in the docstring of tricontour. classmatplotlib.tri.TriFinder(triangulation)[source] Abstract base class for classes used to find the triangles of a Triangulation in which (x, y) points lie. Rather than instantiate an object of a class derived from TriFinder, it is usually better to use the function Triangulation.get_trifinder. Derived classes implement __call__(x, y) where x and y are array-like point coordinates of the same shape. classmatplotlib.tri.TrapezoidMapTriFinder(triangulation)[source] Bases: matplotlib.tri.trifinder.TriFinder TriFinder class implemented using the trapezoid map algorithm from the book "Computational Geometry, Algorithms and Applications", second edition, by M. de Berg, M. van Kreveld, M. Overmars and O. Schwarzkopf. The triangulation must be valid, i.e. it must not have duplicate points, triangles formed from colinear points, or overlapping triangles. The algorithm has some tolerance to triangles formed from colinear points, but this should not be relied upon. classmatplotlib.tri.TriInterpolator(triangulation, z, trifinder=None)[source] Abstract base class for classes used to interpolate on a triangular grid. Derived classes implement the following methods: __call__(x, y), where x, y are array-like point coordinates of the same shape, and that returns a masked array of the same shape containing the interpolated z-values. gradient(x, y), where x, y are array-like point coordinates of the same shape, and that returns a list of 2 masked arrays of the same shape containing the 2 derivatives of the interpolator (derivatives of interpolated z values with respect to x and y). classmatplotlib.tri.LinearTriInterpolator(triangulation, z, trifinder=None)[source] Bases: matplotlib.tri.triinterpolate.TriInterpolator Linear interpolator on a triangular grid. Each triangle is represented by a plane so that an interpolated value at point (x, y) lies on the plane of the triangle containing (x, y). Interpolated values are therefore continuous across the triangulation, but their first derivatives are discontinuous at edges between triangles. Parameters triangulationTriangulation The triangulation to interpolate over. z(npoints,) array-like Array of values, defined at grid points, to interpolate between. trifinderTriFinder, optional If this is not specified, the Triangulation's default TriFinder will be used by calling Triangulation.get_trifinder. Methods `__call__` (x, y) (Returns interpolated values at (x, y) points.) `gradient` (x, y) (Returns interpolated derivatives at (x, y) points.) gradient(x, y)[source] Returns a list of 2 masked arrays containing interpolated derivatives at the specified (x, y) points. Parameters x, yarray-like x and y coordinates of the same shape and any number of dimensions. Returns dzdx, dzdynp.ma.array 2 masked arrays of the same shape as x and y; values corresponding to (x, y) points outside of the triangulation are masked out. The first returned array contains the values of \(\frac{\partial z}{\partial x}\) and the second those of \(\frac{\partial z}{\partial y}\). classmatplotlib.tri.CubicTriInterpolator(triangulation, z, kind='min_E', trifinder=None, dz=None)[source] Bases: matplotlib.tri.triinterpolate.TriInterpolator Cubic interpolator on a triangular grid. In one-dimension - on a segment - a cubic interpolating function is defined by the values of the function and its derivative at both ends. This is almost the same in 2D inside a triangle, except that the values of the function and its 2 derivatives have to be defined at each triangle node. The CubicTriInterpolator takes the value of the function at each node - provided by the user - and internally computes the value of the derivatives, resulting in a smooth interpolation. (As a special feature, the user can also impose the value of the derivatives at each node, but this is not supposed to be the common usage.) Parameters triangulationTriangulation The triangulation to interpolate over. z(npoints,) array-like Array of values, defined at grid points, to interpolate between. kind{'min_E', 'geom', 'user'}, optional Choice of the smoothing algorithm, in order to compute the interpolant derivatives (defaults to 'min_E'): if 'min_E': (default) The derivatives at each node is computed to minimize a bending energy. if 'geom': The derivatives at each node is computed as a weighted average of relevant triangle normals. To be used for speed optimization (large grids). if 'user': The user provides the argument dz, no computation is hence needed. trifinderTriFinder, optional If not specified, the Triangulation's default TriFinder will be used by calling Triangulation.get_trifinder. dztuple of array-likes (dzdx, dzdy), optional Used only if kind ='user'. In this case dz must be provided as (dzdx, dzdy) where dzdx, dzdy are arrays of the same shape as z and are the interpolant first derivatives at the triangulation points. Notes This note is a bit technical and details how the cubic interpolation is computed. The interpolation is based on a Clough-Tocher subdivision scheme of the triangulation mesh (to make it clearer, each triangle of the grid will be divided in 3 child-triangles, and on each child triangle the interpolated function is a cubic polynomial of the 2 coordinates). This technique originates from FEM (Finite Element Method) analysis; the element used is a reduced Hsieh-Clough-Tocher (HCT) element. Its shape functions are described in [1]. The assembled function is guaranteed to be C1-smooth, i.e. it is continuous and its first derivatives are also continuous (this is easy to show inside the triangles but is also true when crossing the edges). In the default case (kind ='min_E'), the interpolant minimizes a curvature energy on the functional space generated by the HCT element shape functions - with imposed values but arbitrary derivatives at each node. The minimized functional is the integral of the so-called total curvature (implementation based on an algorithm from [2] - PCG sparse solver): \[E(z) = \frac{1}{2} \int_{\Omega} \left( \left( \frac{\partial^2{z}}{\partial{x}^2} \right)^2 + \left( \frac{\partial^2{z}}{\partial{y}^2} \right)^2 + 2\left( \frac{\partial^2{z}}{\partial{y}\partial{x}} \right)^2 \right) dx\,dy\] If the case kind ='geom' is chosen by the user, a simple geometric approximation is used (weighted average of the triangle normal vectors), which could improve speed on very large grids. References 1 Michel Bernadou, Kamal Hassan, "Basis functions for general Hsieh-Clough-Tocher triangles, complete or reduced.", International Journal for Numerical Methods in Engineering, 17(5):784 - 789. 2.01. 2 C.T. Kelley, "Iterative Methods for Optimization". Methods `__call__` (x, y) (Returns interpolated values at (x, y) points.) `gradient` (x, y) (Returns interpolated derivatives at (x, y) points.) gradient(x, y)[source] Returns a list of 2 masked arrays containing interpolated derivatives at the specified (x, y) points. Parameters x, yarray-like x and y coordinates of the same shape and any number of dimensions. Returns dzdx, dzdynp.ma.array 2 masked arrays of the same shape as x and y; values corresponding to (x, y) points outside of the triangulation are masked out. The first returned array contains the values of \(\frac{\partial z}{\partial x}\) and the second those of \(\frac{\partial z}{\partial y}\). classmatplotlib.tri.TriRefiner(triangulation)[source] Abstract base class for classes implementing mesh refinement. A TriRefiner encapsulates a Triangulation object and provides tools for mesh refinement and interpolation. Derived classes must implement: refine_triangulation(return_tri_index=False, **kwargs) , where the optional keyword arguments kwargs are defined in each TriRefiner concrete implementation, and which returns: a refined triangulation, optionally (depending on return_tri_index), for each point of the refined triangulation: the index of the initial triangulation triangle to which it belongs. refine_field(z, triinterpolator=None, **kwargs), where: z array of field values (to refine) defined at the base triangulation nodes, triinterpolator is an optional TriInterpolator, the other optional keyword arguments kwargs are defined in each TriRefiner concrete implementation; and which returns (as a tuple) a refined triangular mesh and the interpolated values of the field at the refined triangulation nodes. classmatplotlib.tri.UniformTriRefiner(triangulation)[source] Bases: matplotlib.tri.trirefine.TriRefiner Uniform mesh refinement by recursive subdivisions. Parameters triangulationTriangulation The encapsulated triangulation (to be refined) refine_field(z, triinterpolator=None, subdiv=3)[source] Refine a field defined on the encapsulated triangulation. Parameters z(npoints,) array-like Values of the field to refine, defined at the nodes of the encapsulated triangulation. (n_points is the number of points in the initial triangulation) triinterpolatorTriInterpolator, optional Interpolator used for field interpolation. If not specified, a CubicTriInterpolator will be used. subdivint, default: 3 Recursion level for the subdivision. Each triangle is divided into 4**subdiv child triangles. Returns refi_triTriangulation The returned refined triangulation. refi_z1D array of length: refi_tri node count. The returned interpolated field (at refi_tri nodes). refine_triangulation(return_tri_index=False, subdiv=3)[source] Compute an uniformly refined triangulation refi_triangulation of the encapsulated triangulation. This function refines the encapsulated triangulation by splitting each father triangle into 4 child sub-triangles built on the edges midside nodes, recursing subdiv times. In the end, each triangle is hence divided into 4**subdiv child triangles. Parameters return_tri_indexbool, default: False Whether an index table indicating the father triangle index of each point is returned. subdivint, default: 3 Recursion level for the subdivision. Each triangle is divided into 4**subdiv child triangles; hence, the default results in 64 refined subtriangles for each triangle of the initial triangulation. Returns refi_triangulationTriangulation The refined triangulation. found_indexint array Index of the initial triangulation containing triangle, for each point of refi_triangulation. Returned only if return_tri_index is set to True. classmatplotlib.tri.TriAnalyzer(triangulation)[source] Define basic tools for triangular mesh analysis and improvement. A TriAnalyzer encapsulates a Triangulation object and provides basic tools for mesh analysis and mesh improvement. Parameters triangulationTriangulation The encapsulated triangulation to analyze. Attributes scale_factors Factors to rescale the triangulation into a unit square. circle_ratios(rescale=True)[source] Return a measure of the triangulation triangles flatness. The ratio of the incircle radius over the circumcircle radius is a widely used indicator of a triangle flatness. It is always <= 0.5 and == 0.5 only for equilateral triangles. Circle ratios below 0.01 denote very flat triangles. To avoid unduly low values due to a difference of scale between the 2 axis, the triangular mesh can first be rescaled to fit inside a unit square with scale_factors (Only if rescale is True, which is its default value). Parameters rescalebool, default: True If True, internally rescale (based on scale_factors), so that the (unmasked) triangles fit exactly inside a unit square mesh. Returns masked array Ratio of the incircle radius over the circumcircle radius, for each 'rescaled' triangle of the encapsulated triangulation. Values corresponding to masked triangles are masked out. get_flat_tri_mask(min_circle_ratio=0.01, rescale=True)[source] Eliminate excessively flat border triangles from the triangulation. Returns a mask new_mask which allows to clean the encapsulated triangulation from its border-located flat triangles (according to their circle_ratios()). This mask is meant to be subsequently applied to the triangulation using Triangulation.set_mask. new_mask is an extension of the initial triangulation mask in the sense that an initially masked triangle will remain masked. The new_mask array is computed recursively; at each step flat triangles are removed only if they share a side with the current mesh border. Thus no new holes in the triangulated domain will be created. Parameters min_circle_ratiofloat, default: 0.01 Border triangles with incircle/circumcircle radii ratio r/R will be removed if r/R < min_circle_ratio. rescalebool, default: True If True, first, internally rescale (based on scale_factors) so that the (unmasked) triangles fit exactly inside a unit square mesh. This rescaling accounts for the difference of scale which might exist between the 2 axis. Returns array of bool Mask to apply to encapsulated triangulation. All the initially masked triangles remain masked in the new_mask. Notes The rationale behind this function is that a Delaunay triangulation - of an unstructured set of points - sometimes contains almost flat triangles at its border, leading to artifacts in plots (especially for high-resolution contouring). Masked with computed new_mask, the encapsulated triangulation would contain no more unmasked border triangles with a circle ratio below min_circle_ratio, thus improving the mesh quality for subsequent plots or interpolation. propertyscale_factors Factors to rescale the triangulation into a unit square. Returns (float, float) Scaling factors (kx, ky) so that the triangulation [triangulation.x * kx, triangulation.y * ky] fits exactly inside a unit square.
matplotlib.tri_api
classmatplotlib.tri.CubicTriInterpolator(triangulation, z, kind='min_E', trifinder=None, dz=None)[source] Bases: matplotlib.tri.triinterpolate.TriInterpolator Cubic interpolator on a triangular grid. In one-dimension - on a segment - a cubic interpolating function is defined by the values of the function and its derivative at both ends. This is almost the same in 2D inside a triangle, except that the values of the function and its 2 derivatives have to be defined at each triangle node. The CubicTriInterpolator takes the value of the function at each node - provided by the user - and internally computes the value of the derivatives, resulting in a smooth interpolation. (As a special feature, the user can also impose the value of the derivatives at each node, but this is not supposed to be the common usage.) Parameters triangulationTriangulation The triangulation to interpolate over. z(npoints,) array-like Array of values, defined at grid points, to interpolate between. kind{'min_E', 'geom', 'user'}, optional Choice of the smoothing algorithm, in order to compute the interpolant derivatives (defaults to 'min_E'): if 'min_E': (default) The derivatives at each node is computed to minimize a bending energy. if 'geom': The derivatives at each node is computed as a weighted average of relevant triangle normals. To be used for speed optimization (large grids). if 'user': The user provides the argument dz, no computation is hence needed. trifinderTriFinder, optional If not specified, the Triangulation's default TriFinder will be used by calling Triangulation.get_trifinder. dztuple of array-likes (dzdx, dzdy), optional Used only if kind ='user'. In this case dz must be provided as (dzdx, dzdy) where dzdx, dzdy are arrays of the same shape as z and are the interpolant first derivatives at the triangulation points. Notes This note is a bit technical and details how the cubic interpolation is computed. The interpolation is based on a Clough-Tocher subdivision scheme of the triangulation mesh (to make it clearer, each triangle of the grid will be divided in 3 child-triangles, and on each child triangle the interpolated function is a cubic polynomial of the 2 coordinates). This technique originates from FEM (Finite Element Method) analysis; the element used is a reduced Hsieh-Clough-Tocher (HCT) element. Its shape functions are described in [1]. The assembled function is guaranteed to be C1-smooth, i.e. it is continuous and its first derivatives are also continuous (this is easy to show inside the triangles but is also true when crossing the edges). In the default case (kind ='min_E'), the interpolant minimizes a curvature energy on the functional space generated by the HCT element shape functions - with imposed values but arbitrary derivatives at each node. The minimized functional is the integral of the so-called total curvature (implementation based on an algorithm from [2] - PCG sparse solver): \[E(z) = \frac{1}{2} \int_{\Omega} \left( \left( \frac{\partial^2{z}}{\partial{x}^2} \right)^2 + \left( \frac{\partial^2{z}}{\partial{y}^2} \right)^2 + 2\left( \frac{\partial^2{z}}{\partial{y}\partial{x}} \right)^2 \right) dx\,dy\] If the case kind ='geom' is chosen by the user, a simple geometric approximation is used (weighted average of the triangle normal vectors), which could improve speed on very large grids. References 1 Michel Bernadou, Kamal Hassan, "Basis functions for general Hsieh-Clough-Tocher triangles, complete or reduced.", International Journal for Numerical Methods in Engineering, 17(5):784 - 789. 2.01. 2 C.T. Kelley, "Iterative Methods for Optimization". Methods `__call__` (x, y) (Returns interpolated values at (x, y) points.) `gradient` (x, y) (Returns interpolated derivatives at (x, y) points.) gradient(x, y)[source] Returns a list of 2 masked arrays containing interpolated derivatives at the specified (x, y) points. Parameters x, yarray-like x and y coordinates of the same shape and any number of dimensions. Returns dzdx, dzdynp.ma.array 2 masked arrays of the same shape as x and y; values corresponding to (x, y) points outside of the triangulation are masked out. The first returned array contains the values of \(\frac{\partial z}{\partial x}\) and the second those of \(\frac{\partial z}{\partial y}\).
matplotlib.tri_api#matplotlib.tri.CubicTriInterpolator
gradient(x, y)[source] Returns a list of 2 masked arrays containing interpolated derivatives at the specified (x, y) points. Parameters x, yarray-like x and y coordinates of the same shape and any number of dimensions. Returns dzdx, dzdynp.ma.array 2 masked arrays of the same shape as x and y; values corresponding to (x, y) points outside of the triangulation are masked out. The first returned array contains the values of \(\frac{\partial z}{\partial x}\) and the second those of \(\frac{\partial z}{\partial y}\).
matplotlib.tri_api#matplotlib.tri.CubicTriInterpolator.gradient
classmatplotlib.tri.LinearTriInterpolator(triangulation, z, trifinder=None)[source] Bases: matplotlib.tri.triinterpolate.TriInterpolator Linear interpolator on a triangular grid. Each triangle is represented by a plane so that an interpolated value at point (x, y) lies on the plane of the triangle containing (x, y). Interpolated values are therefore continuous across the triangulation, but their first derivatives are discontinuous at edges between triangles. Parameters triangulationTriangulation The triangulation to interpolate over. z(npoints,) array-like Array of values, defined at grid points, to interpolate between. trifinderTriFinder, optional If this is not specified, the Triangulation's default TriFinder will be used by calling Triangulation.get_trifinder. Methods `__call__` (x, y) (Returns interpolated values at (x, y) points.) `gradient` (x, y) (Returns interpolated derivatives at (x, y) points.) gradient(x, y)[source] Returns a list of 2 masked arrays containing interpolated derivatives at the specified (x, y) points. Parameters x, yarray-like x and y coordinates of the same shape and any number of dimensions. Returns dzdx, dzdynp.ma.array 2 masked arrays of the same shape as x and y; values corresponding to (x, y) points outside of the triangulation are masked out. The first returned array contains the values of \(\frac{\partial z}{\partial x}\) and the second those of \(\frac{\partial z}{\partial y}\).
matplotlib.tri_api#matplotlib.tri.LinearTriInterpolator
gradient(x, y)[source] Returns a list of 2 masked arrays containing interpolated derivatives at the specified (x, y) points. Parameters x, yarray-like x and y coordinates of the same shape and any number of dimensions. Returns dzdx, dzdynp.ma.array 2 masked arrays of the same shape as x and y; values corresponding to (x, y) points outside of the triangulation are masked out. The first returned array contains the values of \(\frac{\partial z}{\partial x}\) and the second those of \(\frac{\partial z}{\partial y}\).
matplotlib.tri_api#matplotlib.tri.LinearTriInterpolator.gradient
classmatplotlib.tri.TrapezoidMapTriFinder(triangulation)[source] Bases: matplotlib.tri.trifinder.TriFinder TriFinder class implemented using the trapezoid map algorithm from the book "Computational Geometry, Algorithms and Applications", second edition, by M. de Berg, M. van Kreveld, M. Overmars and O. Schwarzkopf. The triangulation must be valid, i.e. it must not have duplicate points, triangles formed from colinear points, or overlapping triangles. The algorithm has some tolerance to triangles formed from colinear points, but this should not be relied upon.
matplotlib.tri_api#matplotlib.tri.TrapezoidMapTriFinder
classmatplotlib.tri.TriAnalyzer(triangulation)[source] Define basic tools for triangular mesh analysis and improvement. A TriAnalyzer encapsulates a Triangulation object and provides basic tools for mesh analysis and mesh improvement. Parameters triangulationTriangulation The encapsulated triangulation to analyze. Attributes scale_factors Factors to rescale the triangulation into a unit square. circle_ratios(rescale=True)[source] Return a measure of the triangulation triangles flatness. The ratio of the incircle radius over the circumcircle radius is a widely used indicator of a triangle flatness. It is always <= 0.5 and == 0.5 only for equilateral triangles. Circle ratios below 0.01 denote very flat triangles. To avoid unduly low values due to a difference of scale between the 2 axis, the triangular mesh can first be rescaled to fit inside a unit square with scale_factors (Only if rescale is True, which is its default value). Parameters rescalebool, default: True If True, internally rescale (based on scale_factors), so that the (unmasked) triangles fit exactly inside a unit square mesh. Returns masked array Ratio of the incircle radius over the circumcircle radius, for each 'rescaled' triangle of the encapsulated triangulation. Values corresponding to masked triangles are masked out. get_flat_tri_mask(min_circle_ratio=0.01, rescale=True)[source] Eliminate excessively flat border triangles from the triangulation. Returns a mask new_mask which allows to clean the encapsulated triangulation from its border-located flat triangles (according to their circle_ratios()). This mask is meant to be subsequently applied to the triangulation using Triangulation.set_mask. new_mask is an extension of the initial triangulation mask in the sense that an initially masked triangle will remain masked. The new_mask array is computed recursively; at each step flat triangles are removed only if they share a side with the current mesh border. Thus no new holes in the triangulated domain will be created. Parameters min_circle_ratiofloat, default: 0.01 Border triangles with incircle/circumcircle radii ratio r/R will be removed if r/R < min_circle_ratio. rescalebool, default: True If True, first, internally rescale (based on scale_factors) so that the (unmasked) triangles fit exactly inside a unit square mesh. This rescaling accounts for the difference of scale which might exist between the 2 axis. Returns array of bool Mask to apply to encapsulated triangulation. All the initially masked triangles remain masked in the new_mask. Notes The rationale behind this function is that a Delaunay triangulation - of an unstructured set of points - sometimes contains almost flat triangles at its border, leading to artifacts in plots (especially for high-resolution contouring). Masked with computed new_mask, the encapsulated triangulation would contain no more unmasked border triangles with a circle ratio below min_circle_ratio, thus improving the mesh quality for subsequent plots or interpolation. propertyscale_factors Factors to rescale the triangulation into a unit square. Returns (float, float) Scaling factors (kx, ky) so that the triangulation [triangulation.x * kx, triangulation.y * ky] fits exactly inside a unit square.
matplotlib.tri_api#matplotlib.tri.TriAnalyzer
circle_ratios(rescale=True)[source] Return a measure of the triangulation triangles flatness. The ratio of the incircle radius over the circumcircle radius is a widely used indicator of a triangle flatness. It is always <= 0.5 and == 0.5 only for equilateral triangles. Circle ratios below 0.01 denote very flat triangles. To avoid unduly low values due to a difference of scale between the 2 axis, the triangular mesh can first be rescaled to fit inside a unit square with scale_factors (Only if rescale is True, which is its default value). Parameters rescalebool, default: True If True, internally rescale (based on scale_factors), so that the (unmasked) triangles fit exactly inside a unit square mesh. Returns masked array Ratio of the incircle radius over the circumcircle radius, for each 'rescaled' triangle of the encapsulated triangulation. Values corresponding to masked triangles are masked out.
matplotlib.tri_api#matplotlib.tri.TriAnalyzer.circle_ratios
get_flat_tri_mask(min_circle_ratio=0.01, rescale=True)[source] Eliminate excessively flat border triangles from the triangulation. Returns a mask new_mask which allows to clean the encapsulated triangulation from its border-located flat triangles (according to their circle_ratios()). This mask is meant to be subsequently applied to the triangulation using Triangulation.set_mask. new_mask is an extension of the initial triangulation mask in the sense that an initially masked triangle will remain masked. The new_mask array is computed recursively; at each step flat triangles are removed only if they share a side with the current mesh border. Thus no new holes in the triangulated domain will be created. Parameters min_circle_ratiofloat, default: 0.01 Border triangles with incircle/circumcircle radii ratio r/R will be removed if r/R < min_circle_ratio. rescalebool, default: True If True, first, internally rescale (based on scale_factors) so that the (unmasked) triangles fit exactly inside a unit square mesh. This rescaling accounts for the difference of scale which might exist between the 2 axis. Returns array of bool Mask to apply to encapsulated triangulation. All the initially masked triangles remain masked in the new_mask. Notes The rationale behind this function is that a Delaunay triangulation - of an unstructured set of points - sometimes contains almost flat triangles at its border, leading to artifacts in plots (especially for high-resolution contouring). Masked with computed new_mask, the encapsulated triangulation would contain no more unmasked border triangles with a circle ratio below min_circle_ratio, thus improving the mesh quality for subsequent plots or interpolation.
matplotlib.tri_api#matplotlib.tri.TriAnalyzer.get_flat_tri_mask
classmatplotlib.tri.Triangulation(x, y, triangles=None, mask=None)[source] An unstructured triangular grid consisting of npoints points and ntri triangles. The triangles can either be specified by the user or automatically generated using a Delaunay triangulation. Parameters x, y(npoints,) array-like Coordinates of grid points. triangles(ntri, 3) array-like of int, optional For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If not specified, the Delaunay triangulation is calculated. mask(ntri,) array-like of bool, optional Which triangles are masked out. Notes For a Triangulation to be valid it must not have duplicate points, triangles formed from colinear points, or overlapping triangles. Attributes triangles(ntri, 3) array of int For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. If you want to take the mask into account, use get_masked_triangles instead. mask(ntri, 3) array of bool Masked out triangles. is_delaunaybool Whether the Triangulation is a calculated Delaunay triangulation (where triangles was not specified) or not. calculate_plane_coefficients(z)[source] Calculate plane equation coefficients for all unmasked triangles from the point (x, y) coordinates and specified z-array of shape (npoints). The returned array has shape (npoints, 3) and allows z-value at (x, y) position in triangle tri to be calculated using z = array[tri, 0] * x  + array[tri, 1] * y + array[tri, 2]. propertyedges Return integer array of shape (nedges, 2) containing all edges of non-masked triangles. Each row defines an edge by it's start point index and end point index. Each edge appears only once, i.e. for an edge between points i and j, there will only be either (i, j) or (j, i). get_cpp_triangulation()[source] Return the underlying C++ Triangulation object, creating it if necessary. staticget_from_args_and_kwargs(*args, **kwargs)[source] Return a Triangulation object from the args and kwargs, and the remaining args and kwargs with the consumed values removed. There are two alternatives: either the first argument is a Triangulation object, in which case it is returned, or the args and kwargs are sufficient to create a new Triangulation to return. In the latter case, see Triangulation.__init__ for the possible args and kwargs. get_masked_triangles()[source] Return an array of triangles that are not masked. get_trifinder()[source] Return the default matplotlib.tri.TriFinder of this triangulation, creating it if necessary. This allows the same TriFinder object to be easily shared. propertyneighbors Return integer array of shape (ntri, 3) containing neighbor triangles. For each triangle, the indices of the three triangles that share the same edges, or -1 if there is no such neighboring triangle. neighbors[i, j] is the triangle that is the neighbor to the edge from point index triangles[i, j] to point index triangles[i, (j+1)%3]. set_mask(mask)[source] Set or clear the mask array. Parameters maskNone or bool array of length ntri
matplotlib.tri_api#matplotlib.tri.Triangulation
calculate_plane_coefficients(z)[source] Calculate plane equation coefficients for all unmasked triangles from the point (x, y) coordinates and specified z-array of shape (npoints). The returned array has shape (npoints, 3) and allows z-value at (x, y) position in triangle tri to be calculated using z = array[tri, 0] * x  + array[tri, 1] * y + array[tri, 2].
matplotlib.tri_api#matplotlib.tri.Triangulation.calculate_plane_coefficients
get_cpp_triangulation()[source] Return the underlying C++ Triangulation object, creating it if necessary.
matplotlib.tri_api#matplotlib.tri.Triangulation.get_cpp_triangulation
staticget_from_args_and_kwargs(*args, **kwargs)[source] Return a Triangulation object from the args and kwargs, and the remaining args and kwargs with the consumed values removed. There are two alternatives: either the first argument is a Triangulation object, in which case it is returned, or the args and kwargs are sufficient to create a new Triangulation to return. In the latter case, see Triangulation.__init__ for the possible args and kwargs.
matplotlib.tri_api#matplotlib.tri.Triangulation.get_from_args_and_kwargs
get_masked_triangles()[source] Return an array of triangles that are not masked.
matplotlib.tri_api#matplotlib.tri.Triangulation.get_masked_triangles
get_trifinder()[source] Return the default matplotlib.tri.TriFinder of this triangulation, creating it if necessary. This allows the same TriFinder object to be easily shared.
matplotlib.tri_api#matplotlib.tri.Triangulation.get_trifinder
set_mask(mask)[source] Set or clear the mask array. Parameters maskNone or bool array of length ntri
matplotlib.tri_api#matplotlib.tri.Triangulation.set_mask
classmatplotlib.tri.TriContourSet(ax, *args, **kwargs)[source] Bases: matplotlib.contour.ContourSet Create and store a set of contour lines or filled regions for a triangular grid. This class is typically not instantiated directly by the user but by tricontour and tricontourf. Attributes axAxes The Axes object in which the contours are drawn. collectionssilent_list of PathCollections The Artists representing the contour. This is a list of PathCollections for both line and filled contours. levelsarray The values of the contour levels. layersarray Same as levels for line contours; half-way between levels for filled contours. See ContourSet._process_colors. Draw triangular grid contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in the docstring of tricontour.
matplotlib.tri_api#matplotlib.tri.TriContourSet
classmatplotlib.tri.TriFinder(triangulation)[source] Abstract base class for classes used to find the triangles of a Triangulation in which (x, y) points lie. Rather than instantiate an object of a class derived from TriFinder, it is usually better to use the function Triangulation.get_trifinder. Derived classes implement __call__(x, y) where x and y are array-like point coordinates of the same shape.
matplotlib.tri_api#matplotlib.tri.TriFinder
classmatplotlib.tri.TriInterpolator(triangulation, z, trifinder=None)[source] Abstract base class for classes used to interpolate on a triangular grid. Derived classes implement the following methods: __call__(x, y), where x, y are array-like point coordinates of the same shape, and that returns a masked array of the same shape containing the interpolated z-values. gradient(x, y), where x, y are array-like point coordinates of the same shape, and that returns a list of 2 masked arrays of the same shape containing the 2 derivatives of the interpolator (derivatives of interpolated z values with respect to x and y).
matplotlib.tri_api#matplotlib.tri.TriInterpolator
classmatplotlib.tri.TriRefiner(triangulation)[source] Abstract base class for classes implementing mesh refinement. A TriRefiner encapsulates a Triangulation object and provides tools for mesh refinement and interpolation. Derived classes must implement: refine_triangulation(return_tri_index=False, **kwargs) , where the optional keyword arguments kwargs are defined in each TriRefiner concrete implementation, and which returns: a refined triangulation, optionally (depending on return_tri_index), for each point of the refined triangulation: the index of the initial triangulation triangle to which it belongs. refine_field(z, triinterpolator=None, **kwargs), where: z array of field values (to refine) defined at the base triangulation nodes, triinterpolator is an optional TriInterpolator, the other optional keyword arguments kwargs are defined in each TriRefiner concrete implementation; and which returns (as a tuple) a refined triangular mesh and the interpolated values of the field at the refined triangulation nodes.
matplotlib.tri_api#matplotlib.tri.TriRefiner
classmatplotlib.tri.UniformTriRefiner(triangulation)[source] Bases: matplotlib.tri.trirefine.TriRefiner Uniform mesh refinement by recursive subdivisions. Parameters triangulationTriangulation The encapsulated triangulation (to be refined) refine_field(z, triinterpolator=None, subdiv=3)[source] Refine a field defined on the encapsulated triangulation. Parameters z(npoints,) array-like Values of the field to refine, defined at the nodes of the encapsulated triangulation. (n_points is the number of points in the initial triangulation) triinterpolatorTriInterpolator, optional Interpolator used for field interpolation. If not specified, a CubicTriInterpolator will be used. subdivint, default: 3 Recursion level for the subdivision. Each triangle is divided into 4**subdiv child triangles. Returns refi_triTriangulation The returned refined triangulation. refi_z1D array of length: refi_tri node count. The returned interpolated field (at refi_tri nodes). refine_triangulation(return_tri_index=False, subdiv=3)[source] Compute an uniformly refined triangulation refi_triangulation of the encapsulated triangulation. This function refines the encapsulated triangulation by splitting each father triangle into 4 child sub-triangles built on the edges midside nodes, recursing subdiv times. In the end, each triangle is hence divided into 4**subdiv child triangles. Parameters return_tri_indexbool, default: False Whether an index table indicating the father triangle index of each point is returned. subdivint, default: 3 Recursion level for the subdivision. Each triangle is divided into 4**subdiv child triangles; hence, the default results in 64 refined subtriangles for each triangle of the initial triangulation. Returns refi_triangulationTriangulation The refined triangulation. found_indexint array Index of the initial triangulation containing triangle, for each point of refi_triangulation. Returned only if return_tri_index is set to True.
matplotlib.tri_api#matplotlib.tri.UniformTriRefiner
refine_field(z, triinterpolator=None, subdiv=3)[source] Refine a field defined on the encapsulated triangulation. Parameters z(npoints,) array-like Values of the field to refine, defined at the nodes of the encapsulated triangulation. (n_points is the number of points in the initial triangulation) triinterpolatorTriInterpolator, optional Interpolator used for field interpolation. If not specified, a CubicTriInterpolator will be used. subdivint, default: 3 Recursion level for the subdivision. Each triangle is divided into 4**subdiv child triangles. Returns refi_triTriangulation The returned refined triangulation. refi_z1D array of length: refi_tri node count. The returned interpolated field (at refi_tri nodes).
matplotlib.tri_api#matplotlib.tri.UniformTriRefiner.refine_field
refine_triangulation(return_tri_index=False, subdiv=3)[source] Compute an uniformly refined triangulation refi_triangulation of the encapsulated triangulation. This function refines the encapsulated triangulation by splitting each father triangle into 4 child sub-triangles built on the edges midside nodes, recursing subdiv times. In the end, each triangle is hence divided into 4**subdiv child triangles. Parameters return_tri_indexbool, default: False Whether an index table indicating the father triangle index of each point is returned. subdivint, default: 3 Recursion level for the subdivision. Each triangle is divided into 4**subdiv child triangles; hence, the default results in 64 refined subtriangles for each triangle of the initial triangulation. Returns refi_triangulationTriangulation The refined triangulation. found_indexint array Index of the initial triangulation containing triangle, for each point of refi_triangulation. Returned only if return_tri_index is set to True.
matplotlib.tri_api#matplotlib.tri.UniformTriRefiner.refine_triangulation
matplotlib.type1font A class representing a Type 1 font. This version reads pfa and pfb files and splits them for embedding in pdf files. It also supports SlantFont and ExtendFont transformations, similarly to pdfTeX and friends. There is no support yet for subsetting. Usage: >>> font = Type1Font(filename) >>> clear_part, encrypted_part, finale = font.parts >>> slanted_font = font.transform({'slant': 0.167}) >>> extended_font = font.transform({'extend': 1.2}) Sources: Adobe Technical Note #5040, Supporting Downloadable PostScript Language Fonts. Adobe Type 1 Font Format, Adobe Systems Incorporated, third printing, v1.1, 1993. ISBN 0-201-57044-0. classmatplotlib.type1font.Type1Font(input)[source] Bases: object A class representing a Type-1 font, for use by backends. Attributes partstuple A 3-tuple of the cleartext part, the encrypted part, and the finale of zeros. decryptedbytes The decrypted form of parts[1]. propdict[str, Any] A dictionary of font properties. Initialize a Type-1 font. Parameters inputstr or 3-tuple Either a pfb file name, or a 3-tuple of already-decoded Type-1 font parts. decrypted parts prop transform(effects)[source] Return a new font that is slanted and/or extended. Parameters effectsdict A dict with optional entries: 'slant'float, default: 0 Tangent of the angle that the font is to be slanted to the right. Negative values slant to the left. 'extend'float, default: 1 Scaling factor for the font width. Values less than 1 condense the glyphs. Returns Type1Font
matplotlib.type1font
classmatplotlib.type1font.Type1Font(input)[source] Bases: object A class representing a Type-1 font, for use by backends. Attributes partstuple A 3-tuple of the cleartext part, the encrypted part, and the finale of zeros. decryptedbytes The decrypted form of parts[1]. propdict[str, Any] A dictionary of font properties. Initialize a Type-1 font. Parameters inputstr or 3-tuple Either a pfb file name, or a 3-tuple of already-decoded Type-1 font parts. decrypted parts prop transform(effects)[source] Return a new font that is slanted and/or extended. Parameters effectsdict A dict with optional entries: 'slant'float, default: 0 Tangent of the angle that the font is to be slanted to the right. Negative values slant to the left. 'extend'float, default: 1 Scaling factor for the font width. Values less than 1 condense the glyphs. Returns Type1Font
matplotlib.type1font#matplotlib.type1font.Type1Font
decrypted
matplotlib.type1font#matplotlib.type1font.Type1Font.decrypted
parts
matplotlib.type1font#matplotlib.type1font.Type1Font.parts
prop
matplotlib.type1font#matplotlib.type1font.Type1Font.prop
transform(effects)[source] Return a new font that is slanted and/or extended. Parameters effectsdict A dict with optional entries: 'slant'float, default: 0 Tangent of the angle that the font is to be slanted to the right. Negative values slant to the left. 'extend'float, default: 1 Scaling factor for the font width. Values less than 1 condense the glyphs. Returns Type1Font
matplotlib.type1font#matplotlib.type1font.Type1Font.transform
matplotlib.units The classes here provide support for using custom classes with Matplotlib, e.g., those that do not expose the array interface but know how to convert themselves to arrays. It also supports classes with units and units conversion. Use cases include converters for custom objects, e.g., a list of datetime objects, as well as for objects that are unit aware. We don't assume any particular units implementation; rather a units implementation must register with the Registry converter dictionary and provide a ConversionInterface. For example, here is a complete implementation which supports plotting with native datetime objects: import matplotlib.units as units import matplotlib.dates as dates import matplotlib.ticker as ticker import datetime class DateConverter(units.ConversionInterface): @staticmethod def convert(value, unit, axis): "Convert a datetime value to a scalar or array." return dates.date2num(value) @staticmethod def axisinfo(unit, axis): "Return major and minor tick locators and formatters." if unit != 'date': return None majloc = dates.AutoDateLocator() majfmt = dates.AutoDateFormatter(majloc) return AxisInfo(majloc=majloc, majfmt=majfmt, label='date') @staticmethod def default_units(x, axis): "Return the default unit for x or None." return 'date' # Finally we register our object type with the Matplotlib units registry. units.registry[datetime.date] = DateConverter() classmatplotlib.units.AxisInfo(majloc=None, minloc=None, majfmt=None, minfmt=None, label=None, default_limits=None)[source] Bases: object Information to support default axis labeling, tick labeling, and limits. An instance of this class must be returned by ConversionInterface.axisinfo. Parameters majloc, minlocLocator, optional Tick locators for the major and minor ticks. majfmt, minfmtFormatter, optional Tick formatters for the major and minor ticks. labelstr, optional The default axis label. default_limitsoptional The default min and max limits of the axis if no data has been plotted. Notes If any of the above are None, the axis will simply use the default value. exceptionmatplotlib.units.ConversionError[source] Bases: TypeError classmatplotlib.units.ConversionInterface[source] Bases: object The minimal interface for a converter to take custom data types (or sequences) and convert them to values Matplotlib can use. staticaxisinfo(unit, axis)[source] Return an AxisInfo for the axis with the specified units. staticconvert(obj, unit, axis)[source] Convert obj using unit for the specified axis. If obj is a sequence, return the converted sequence. The output must be a sequence of scalars that can be used by the numpy array layer. staticdefault_units(x, axis)[source] Return the default unit for x or None for the given axis. staticis_numlike(x)[source] [Deprecated] The Matplotlib datalim, autoscaling, locators etc work with scalars which are the units converted to floats given the current unit. The converter may be passed these floats, or arrays of them, even when units are set. Notes Deprecated since version 3.5. classmatplotlib.units.DecimalConverter[source] Bases: matplotlib.units.ConversionInterface Converter for decimal.Decimal data to float. staticconvert(value, unit, axis)[source] Convert Decimals to floats. The unit and axis arguments are not used. Parameters valuedecimal.Decimal or iterable Decimal or list of Decimal need to be converted classmatplotlib.units.Registry[source] Bases: dict Register types with conversion interface. get_converter(x)[source] Get the converter interface instance for x, or None.
matplotlib.units_api
classmatplotlib.units.AxisInfo(majloc=None, minloc=None, majfmt=None, minfmt=None, label=None, default_limits=None)[source] Bases: object Information to support default axis labeling, tick labeling, and limits. An instance of this class must be returned by ConversionInterface.axisinfo. Parameters majloc, minlocLocator, optional Tick locators for the major and minor ticks. majfmt, minfmtFormatter, optional Tick formatters for the major and minor ticks. labelstr, optional The default axis label. default_limitsoptional The default min and max limits of the axis if no data has been plotted. Notes If any of the above are None, the axis will simply use the default value.
matplotlib.units_api#matplotlib.units.AxisInfo
exceptionmatplotlib.units.ConversionError[source] Bases: TypeError
matplotlib.units_api#matplotlib.units.ConversionError
classmatplotlib.units.ConversionInterface[source] Bases: object The minimal interface for a converter to take custom data types (or sequences) and convert them to values Matplotlib can use. staticaxisinfo(unit, axis)[source] Return an AxisInfo for the axis with the specified units. staticconvert(obj, unit, axis)[source] Convert obj using unit for the specified axis. If obj is a sequence, return the converted sequence. The output must be a sequence of scalars that can be used by the numpy array layer. staticdefault_units(x, axis)[source] Return the default unit for x or None for the given axis. staticis_numlike(x)[source] [Deprecated] The Matplotlib datalim, autoscaling, locators etc work with scalars which are the units converted to floats given the current unit. The converter may be passed these floats, or arrays of them, even when units are set. Notes Deprecated since version 3.5.
matplotlib.units_api#matplotlib.units.ConversionInterface
staticaxisinfo(unit, axis)[source] Return an AxisInfo for the axis with the specified units.
matplotlib.units_api#matplotlib.units.ConversionInterface.axisinfo
staticconvert(obj, unit, axis)[source] Convert obj using unit for the specified axis. If obj is a sequence, return the converted sequence. The output must be a sequence of scalars that can be used by the numpy array layer.
matplotlib.units_api#matplotlib.units.ConversionInterface.convert
staticdefault_units(x, axis)[source] Return the default unit for x or None for the given axis.
matplotlib.units_api#matplotlib.units.ConversionInterface.default_units
staticis_numlike(x)[source] [Deprecated] The Matplotlib datalim, autoscaling, locators etc work with scalars which are the units converted to floats given the current unit. The converter may be passed these floats, or arrays of them, even when units are set. Notes Deprecated since version 3.5.
matplotlib.units_api#matplotlib.units.ConversionInterface.is_numlike
classmatplotlib.units.DecimalConverter[source] Bases: matplotlib.units.ConversionInterface Converter for decimal.Decimal data to float. staticconvert(value, unit, axis)[source] Convert Decimals to floats. The unit and axis arguments are not used. Parameters valuedecimal.Decimal or iterable Decimal or list of Decimal need to be converted
matplotlib.units_api#matplotlib.units.DecimalConverter
staticconvert(value, unit, axis)[source] Convert Decimals to floats. The unit and axis arguments are not used. Parameters valuedecimal.Decimal or iterable Decimal or list of Decimal need to be converted
matplotlib.units_api#matplotlib.units.DecimalConverter.convert
classmatplotlib.units.Registry[source] Bases: dict Register types with conversion interface. get_converter(x)[source] Get the converter interface instance for x, or None.
matplotlib.units_api#matplotlib.units.Registry
get_converter(x)[source] Get the converter interface instance for x, or None.
matplotlib.units_api#matplotlib.units.Registry.get_converter
matplotlib.use(backend, *, force=True)[source] Select the backend used for rendering and GUI integration. Parameters backendstr The backend to switch to. This can either be one of the standard backend names, which are case-insensitive: interactive backends: GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, QtAgg, QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo non-interactive backends: agg, cairo, pdf, pgf, ps, svg, template or a string of the form: module://my.module.name. Switching to an interactive backend is not possible if an unrelated event loop has already been started (e.g., switching to GTK3Agg if a TkAgg window has already been opened). Switching to a non-interactive backend is always possible. forcebool, default: True If True (the default), raise an ImportError if the backend cannot be set up (either because it fails to import, or because an incompatible GUI interactive framework is already running); if False, silently ignore the failure. See also Backends matplotlib.get_backend
matplotlib_configuration_api#matplotlib.use
matplotlib.widgets GUI neutral widgets Widgets that are designed to work for any of the GUI backends. All of these widgets require you to predefine a matplotlib.axes.Axes instance and pass that as the first parameter. Matplotlib doesn't try to be too smart with respect to layout -- you will have to figure out how wide and tall you want your Axes to be to accommodate your widget. classmatplotlib.widgets.AxesWidget(ax)[source] Bases: matplotlib.widgets.Widget Widget connected to a single Axes. To guarantee that the widget remains responsive and not garbage-collected, a reference to the object should be maintained by the user. This is necessary because the callback registry maintains only weak-refs to the functions, which are member functions of the widget. If there are no references to the widget object it may be garbage collected which will disconnect the callbacks. Attributes axAxes The parent axes for the widget. canvasFigureCanvasBase The parent figure canvas for the widget. activebool Is the widget active? propertycids[source] connect_event(event, callback)[source] Connect a callback function with an event. This should be used in lieu of figure.canvas.mpl_connect since this function stores callback ids for later clean up. disconnect_events()[source] Disconnect all events created by this widget. classmatplotlib.widgets.Button(ax, label, image=None, color='0.85', hovercolor='0.95')[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral button. For the button to remain responsive you must keep a reference to it. Call on_clicked to connect to the button. Attributes ax The matplotlib.axes.Axes the button renders into. label A matplotlib.text.Text instance. color The color of the button when not hovering. hovercolor The color of the button when hovering. Parameters axAxes The Axes instance the button will be placed into. labelstr The button text. imagearray-like or PIL Image The image to place in the button, if not None. The parameter is directly forwarded to imshow. colorcolor The color of the button when not activated. hovercolorcolor The color of the button when the mouse is over it. propertycnt[source] disconnect(cid)[source] Remove the callback function with connection id cid. propertyobservers[source] on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback. classmatplotlib.widgets.CheckButtons(ax, labels, actives=None)[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral set of check buttons. For the check buttons to remain responsive you must keep a reference to this object. Connect to the CheckButtons with the on_clicked method. Attributes axAxes The parent axes for the widget. labelslist of Text rectangleslist of Rectangle lineslist of (Line2D, Line2D) pairs List of lines for the x's in the check boxes. These lines exist for each box, but have set_visible(False) when its box is not checked. Add check buttons to matplotlib.axes.Axes instance ax. Parameters axAxes The parent axes for the widget. labelslist of str The labels of the check buttons. activeslist of bool, optional The initial check states of the buttons. The list must have the same length as labels. If not given, all buttons are unchecked. propertycnt[source] disconnect(cid)[source] Remove the observer with connection id cid. get_status()[source] Return a tuple of the status (True/False) of all of the check buttons. propertyobservers[source] on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback. set_active(index)[source] Toggle (activate or deactivate) a check button by index. Callbacks will be triggered if eventson is True. Parameters indexint Index of the check button to toggle. Raises ValueError If index is invalid. classmatplotlib.widgets.Cursor(ax, horizOn=True, vertOn=True, useblit=False, **lineprops)[source] Bases: matplotlib.widgets.AxesWidget A crosshair cursor that spans the axes and moves with mouse cursor. For the cursor to remain responsive you must keep a reference to it. Parameters axmatplotlib.axes.Axes The Axes to attach the cursor to. horizOnbool, default: True Whether to draw the horizontal line. vertOnbool, default: True Whether to draw the vertical line. useblitbool, default: False Use blitting for faster drawing if supported by the backend. Other Parameters **lineprops Line2D properties that control the appearance of the lines. See also axhline. Examples See Cursor. clear(event)[source] Internal event handler to clear the cursor. onmove(event)[source] Internal event handler to draw the cursor when the mouse moves. classmatplotlib.widgets.EllipseSelector(ax, onselect, drawtype=<deprecated parameter>, minspanx=0, minspany=0, useblit=False, lineprops=<deprecated parameter>, props=None, spancoords='data', button=None, grab_range=10, handle_props=None, interactive=False, state_modifier_keys=None, drag_from_anywhere=False, ignore_event_outside=False)[source] Bases: matplotlib.widgets.RectangleSelector Select an elliptical region of an axes. For the cursor to remain responsive you must keep a reference to it. Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True. Parameters axAxes The parent axes for the widget. onselectfunction A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature: def onselect(eclick: MouseEvent, erelease: MouseEvent) where eclick and erelease are the mouse click and release MouseEvents that start and complete the selection. minspanxfloat, default: 0 Selections with an x-span less than or equal to minspanx are removed (when already existing) or cancelled. minspanyfloat, default: 0 Selections with an y-span less than or equal to minspanx are removed (when already existing) or cancelled. useblitbool, default: False Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the ellipse is drawn. See matplotlib.patches.Patch for valid properties. Default: dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True) spancoords{"data", "pixels"}, default: "data" Whether to interpret minspanx and minspany in data or in pixel coordinates. buttonMouseButton, list of MouseButton, default: all buttons Button(s) that trigger rectangle selection. grab_rangefloat, default: 10 Distance in pixels within which the interactive tool handles can be activated. handle_propsdict, optional Properties with which the interactive handles (marker artists) are drawn. See the marker arguments in matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams except for the default value of markeredgecolor which will be the same as the edgecolor property in props. interactivebool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. state_modifier_keysdict, optional Keyboard modifiers which affect the widget's behavior. Values amend the defaults. "move": Move the existing shape, default: no modifier. "clear": Clear the current shape, default: "escape". "square": Make the shape square, default: "shift". "center": Make the initial point the center of the shape, default: "ctrl". "square" and "center" can be combined. drag_from_anywherebool, default: False If True, the widget can be moved by clicking anywhere within its bounds. ignore_event_outsidebool, default: False If True, the event triggered outside the span selector will be ignored. Examples Rectangle and ellipse selectors propertydraw_shape[source] classmatplotlib.widgets.Lasso(ax, xy, callback=None, useblit=True)[source] Bases: matplotlib.widgets.AxesWidget Selection curve of an arbitrary shape. The selected path can be used in conjunction with contains_point to select data points from an image. Unlike LassoSelector, this must be initialized with a starting point xy, and the Lasso events are destroyed upon release. Parameters axAxes The parent axes for the widget. xy(float, float) Coordinates of the start of the lasso. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). callbackcallable Whenever the lasso is released, the callback function is called and passed the vertices of the selected path. onmove(event)[source] onrelease(event)[source] classmatplotlib.widgets.LassoSelector(ax, onselect=None, useblit=True, props=None, button=None)[source] Bases: matplotlib.widgets._SelectorWidget Selection curve of an arbitrary shape. For the selector to remain responsive you must keep a reference to it. The selected path can be used in conjunction with contains_point to select data points from an image. In contrast to Lasso, LassoSelector is written with an interface similar to RectangleSelector and SpanSelector, and will continue to interact with the axes until disconnected. Example usage: ax = plt.subplot() ax.plot(x, y) def onselect(verts): print(verts) lasso = LassoSelector(ax, onselect) Parameters axAxes The parent axes for the widget. onselectfunction Whenever the lasso is released, the onselect function is called and passed the vertices of the selected path. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the line is drawn, see matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams. buttonMouseButton or list of MouseButton, optional The mouse buttons used for rectangle selection. Default is None, which corresponds to all buttons. onpress(event)[source] [Deprecated] Notes Deprecated since version 3.5: onrelease(event)[source] [Deprecated] Notes Deprecated since version 3.5: classmatplotlib.widgets.LockDraw[source] Bases: object Some widgets, like the cursor, draw onto the canvas, and this is not desirable under all circumstances, like when the toolbar is in zoom-to-rect mode and drawing a rectangle. To avoid this, a widget can acquire a canvas' lock with canvas.widgetlock(widget) before drawing on the canvas; this will prevent other widgets from doing so at the same time (if they also try to acquire the lock first). available(o)[source] Return whether drawing is available to o. isowner(o)[source] Return whether o owns this lock. locked()[source] Return whether the lock is currently held by an owner. release(o)[source] Release the lock from o. classmatplotlib.widgets.MultiCursor(canvas, axes, useblit=True, horizOn=False, vertOn=True, **lineprops)[source] Bases: matplotlib.widgets.Widget Provide a vertical (default) and/or horizontal line cursor shared between multiple axes. For the cursor to remain responsive you must keep a reference to it. Parameters canvasmatplotlib.backend_bases.FigureCanvasBase The FigureCanvas that contains all the axes. axeslist of matplotlib.axes.Axes The Axes to attach the cursor to. useblitbool, default: True Use blitting for faster drawing if supported by the backend. horizOnbool, default: False Whether to draw the horizontal line. vertOn: bool, default: True Whether to draw the vertical line. Other Parameters **lineprops Line2D properties that control the appearance of the lines. See also axhline. Examples See Multicursor. clear(event)[source] Clear the cursor. connect()[source] Connect events. disconnect()[source] Disconnect events. onmove(event)[source] classmatplotlib.widgets.PolygonSelector(ax, onselect, useblit=False, props=None, handle_props=None, grab_range=10)[source] Bases: matplotlib.widgets._SelectorWidget Select a polygon region of an axes. Place vertices with each mouse click, and make the selection by completing the polygon (clicking on the first vertex). Once drawn individual vertices can be moved by clicking and dragging with the left mouse button, or removed by clicking the right mouse button. In addition, the following modifier keys can be used: Hold ctrl and click and drag a vertex to reposition it before the polygon has been completed. Hold the shift key and click and drag anywhere in the axes to move all vertices. Press the esc key to start a new polygon. For the selector to remain responsive you must keep a reference to it. Parameters axAxes The parent axes for the widget. onselectfunction When a polygon is completed or modified after completion, the onselect function is called and passed a list of the vertices as (xdata, ydata) tuples. useblitbool, default: False Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the line is drawn, see matplotlib.lines.Line2D for valid properties. Default: dict(color='k', linestyle='-', linewidth=2, alpha=0.5) handle_propsdict, optional Artist properties for the markers drawn at the vertices of the polygon. See the marker arguments in matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams except for the default value of markeredgecolor which will be the same as the color property in props. grab_rangefloat, default: 10 A vertex is selected (to complete the polygon or to move a vertex) if the mouse click is within grab_range pixels of the vertex. Notes If only one point remains after removing points, the selector reverts to an incomplete state and you can start drawing a new polygon from the existing point. Examples Polygon Selector propertyline[source] onmove(event)[source] Cursor move event handler and validator. propertyvertex_select_radius[source] propertyverts The polygon vertices, as a list of (x, y) pairs. classmatplotlib.widgets.RadioButtons(ax, labels, active=0, activecolor='blue')[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral radio button. For the buttons to remain responsive you must keep a reference to this object. Connect to the RadioButtons with the on_clicked method. Attributes axAxes The parent axes for the widget. activecolorcolor The color of the selected button. labelslist of Text The button labels. circleslist of Circle The buttons. value_selectedstr The label text of the currently selected button. Add radio buttons to an Axes. Parameters axAxes The axes to add the buttons to. labelslist of str The button labels. activeint The index of the initially selected button. activecolorcolor The color of the selected button. propertycnt[source] disconnect(cid)[source] Remove the observer with connection id cid. propertyobservers[source] on_clicked(func)[source] Connect the callback function func to button click events. Returns a connection id, which can be used to disconnect the callback. set_active(index)[source] Select button with number index. Callbacks will be triggered if eventson is True. classmatplotlib.widgets.RangeSlider(ax, label, valmin, valmax, valinit=None, valfmt=None, closedmin=True, closedmax=True, dragging=True, valstep=None, orientation='horizontal', track_color='lightgrey', handle_style=None, **kwargs)[source] Bases: matplotlib.widgets.SliderBase A slider representing a range of floating point values. Defines the min and max of the range via the val attribute as a tuple of (min, max). Create a slider that defines a range contained within [valmin, valmax] in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event. Attributes valtuple of float Slider value. Parameters axAxes The Axes to put the slider in. labelstr Slider label. valminfloat The minimum value of the slider. valmaxfloat The maximum value of the slider. valinittuple of float or None, default: None The initial positions of the slider. If None the initial positions will be at the 25th and 75th percentiles of the range. valfmtstr, default: None %-format string used to format the slider values. If None, a ScalarFormatter is used instead. closedminbool, default: True Whether the slider interval is closed on the bottom. closedmaxbool, default: True Whether the slider interval is closed on the top. draggingbool, default: True If True the slider can be dragged by the mouse. valstepfloat, default: None If given, the slider will snap to multiples of valstep. orientation{'horizontal', 'vertical'}, default: 'horizontal' The orientation of the slider. track_colorcolor, default: 'lightgrey' The color of the background track. The track is accessible for further styling via the track attribute. handle_styledict Properties of the slider handles. Default values are Key Value Default Description facecolor color 'white' The facecolor of the slider handles. edgecolor color '.75' The edgecolor of the slider handles. size int 10 The size of the slider handles in points. Other values will be transformed as marker{foo} and passed to the Line2D constructor. e.g. handle_style = {'style'='x'} will result in markerstyle = 'x'. Notes Additional kwargs are passed on to self.poly which is the Polygon that draws the slider knob. See the Polygon documentation for valid property names (facecolor, edgecolor, alpha, etc.). on_changed(func)[source] Connect func as callback function to changes of the slider value. Parameters funccallable Function to call when slider is changed. The function must accept a numpy array with shape (2,) as its argument. Returns int Connection id (which can be used to disconnect func). set_max(max)[source] Set the lower value of the slider to max. Parameters maxfloat set_min(min)[source] Set the lower value of the slider to min. Parameters minfloat set_val(val)[source] Set slider value to val. Parameters valtuple or array-like of float classmatplotlib.widgets.RectangleSelector(ax, onselect, drawtype=<deprecated parameter>, minspanx=0, minspany=0, useblit=False, lineprops=<deprecated parameter>, props=None, spancoords='data', button=None, grab_range=10, handle_props=None, interactive=False, state_modifier_keys=None, drag_from_anywhere=False, ignore_event_outside=False)[source] Bases: matplotlib.widgets._SelectorWidget Select a rectangular region of an axes. For the cursor to remain responsive you must keep a reference to it. Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True. Parameters axAxes The parent axes for the widget. onselectfunction A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature: def onselect(eclick: MouseEvent, erelease: MouseEvent) where eclick and erelease are the mouse click and release MouseEvents that start and complete the selection. minspanxfloat, default: 0 Selections with an x-span less than or equal to minspanx are removed (when already existing) or cancelled. minspanyfloat, default: 0 Selections with an y-span less than or equal to minspanx are removed (when already existing) or cancelled. useblitbool, default: False Whether to use blitting for faster drawing (if supported by the backend). propsdict, optional Properties with which the rectangle is drawn. See matplotlib.patches.Patch for valid properties. Default: dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True) spancoords{"data", "pixels"}, default: "data" Whether to interpret minspanx and minspany in data or in pixel coordinates. buttonMouseButton, list of MouseButton, default: all buttons Button(s) that trigger rectangle selection. grab_rangefloat, default: 10 Distance in pixels within which the interactive tool handles can be activated. handle_propsdict, optional Properties with which the interactive handles (marker artists) are drawn. See the marker arguments in matplotlib.lines.Line2D for valid properties. Default values are defined in mpl.rcParams except for the default value of markeredgecolor which will be the same as the edgecolor property in props. interactivebool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. state_modifier_keysdict, optional Keyboard modifiers which affect the widget's behavior. Values amend the defaults. "move": Move the existing shape, default: no modifier. "clear": Clear the current shape, default: "escape". "square": Make the shape square, default: "shift". "center": Make the initial point the center of the shape, default: "ctrl". "square" and "center" can be combined. drag_from_anywherebool, default: False If True, the widget can be moved by clicking anywhere within its bounds. ignore_event_outsidebool, default: False If True, the event triggered outside the span selector will be ignored. Examples >>> import matplotlib.pyplot as plt >>> import matplotlib.widgets as mwidgets >>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [10, 50, 100]) >>> def onselect(eclick, erelease): ... print(eclick.xdata, eclick.ydata) ... print(erelease.xdata, erelease.ydata) >>> props = dict(facecolor='blue', alpha=0.5) >>> rect = mwidgets.RectangleSelector(ax, onselect, interactive=True, props=props) >>> fig.show() See also: Rectangle and ellipse selectors propertyactive_handle[source] propertycenter Center of rectangle. propertycorners Corners of rectangle from lower left, moving clockwise. propertydraw_shape[source] propertydrawtype[source] propertyedge_centers Midpoint of rectangle edges from left, moving anti-clockwise. propertyextents Return (xmin, xmax, ymin, ymax). propertygeometry Return an array of shape (2, 5) containing the x (RectangleSelector.geometry[1, :]) and y (RectangleSelector.geometry[0, :]) coordinates of the four corners of the rectangle starting and ending in the top left corner. propertyinteractive[source] propertymaxdist[source] propertyto_draw[source] classmatplotlib.widgets.Slider(ax, label, valmin, valmax, valinit=0.5, valfmt=None, closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, valstep=None, orientation='horizontal', *, initcolor='r', track_color='lightgrey', handle_style=None, **kwargs)[source] Bases: matplotlib.widgets.SliderBase A slider representing a floating point range. Create a slider from valmin to valmax in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event. Attributes valfloat Slider value. Parameters axAxes The Axes to put the slider in. labelstr Slider label. valminfloat The minimum value of the slider. valmaxfloat The maximum value of the slider. valinitfloat, default: 0.5 The slider initial position. valfmtstr, default: None %-format string used to format the slider value. If None, a ScalarFormatter is used instead. closedminbool, default: True Whether the slider interval is closed on the bottom. closedmaxbool, default: True Whether the slider interval is closed on the top. sliderminSlider, default: None Do not allow the current slider to have a value less than the value of the Slider slidermin. slidermaxSlider, default: None Do not allow the current slider to have a value greater than the value of the Slider slidermax. draggingbool, default: True If True the slider can be dragged by the mouse. valstepfloat or array-like, default: None If a float, the slider will snap to multiples of valstep. If an array the slider will snap to the values in the array. orientation{'horizontal', 'vertical'}, default: 'horizontal' The orientation of the slider. initcolorcolor, default: 'r' The color of the line at the valinit position. Set to 'none' for no line. track_colorcolor, default: 'lightgrey' The color of the background track. The track is accessible for further styling via the track attribute. handle_styledict Properties of the slider handle. Default values are Key Value Default Description facecolor color 'white' The facecolor of the slider handle. edgecolor color '.75' The edgecolor of the slider handle. size int 10 The size of the slider handle in points. Other values will be transformed as marker{foo} and passed to the Line2D constructor. e.g. handle_style = {'style'='x'} will result in markerstyle = 'x'. Notes Additional kwargs are passed on to self.poly which is the Polygon that draws the slider knob. See the Polygon documentation for valid property names (facecolor, edgecolor, alpha, etc.). propertycnt[source] propertyobservers[source] on_changed(func)[source] Connect func as callback function to changes of the slider value. Parameters funccallable Function to call when slider is changed. The function must accept a single float as its arguments. Returns int Connection id (which can be used to disconnect func). set_val(val)[source] Set slider value to val. Parameters valfloat classmatplotlib.widgets.SliderBase(ax, orientation, closedmin, closedmax, valmin, valmax, valfmt, dragging, valstep)[source] Bases: matplotlib.widgets.AxesWidget The base class for constructing Slider widgets. Not intended for direct usage. For the slider to remain responsive you must maintain a reference to it. disconnect(cid)[source] Remove the observer with connection id cid. Parameters cidint Connection id of the observer to be removed. reset()[source] Reset the slider to the initial value. classmatplotlib.widgets.SpanSelector(ax, onselect, direction, minspan=0, useblit=False, props=None, onmove_callback=None, interactive=False, button=None, handle_props=None, grab_range=10, drag_from_anywhere=False, ignore_event_outside=False)[source] Bases: matplotlib.widgets._SelectorWidget Visually select a min/max range on a single axis and call a function with those values. To guarantee that the selector remains responsive, keep a reference to it. In order to turn off the SpanSelector, set span_selector.active to False. To turn it back on, set it to True. Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True. Parameters axmatplotlib.axes.Axes onselectcallable A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature: def on_select(min: float, max: float) -> Any direction{"horizontal", "vertical"} The direction along which to draw the span selector. minspanfloat, default: 0 If selection is less than or equal to minspan, the selection is removed (when already existing) or cancelled. useblitbool, default: False If True, use the backend-dependent blitting features for faster canvas updates. propsdict, optional Dictionary of matplotlib.patches.Patch properties. Default: dict(facecolor='red', alpha=0.5) onmove_callbackfunc(min, max), min/max are floats, default: None Called on mouse move while the span is being selected. span_staysbool, default: False If True, the span stays visible after the mouse is released. Deprecated, use interactive instead. interactivebool, default: False Whether to draw a set of handles that allow interaction with the widget after it is drawn. buttonMouseButton or list of MouseButton, default: all buttons The mouse buttons which activate the span selector. handle_propsdict, default: None Properties of the handle lines at the edges of the span. Only used when interactive is True. See matplotlib.lines.Line2D for valid properties. grab_rangefloat, default: 10 Distance in pixels within which the interactive tool handles can be activated. drag_from_anywherebool, default: False If True, the widget can be moved by clicking anywhere within its bounds. ignore_event_outsidebool, default: False If True, the event triggered outside the span selector will be ignored. Examples >>> import matplotlib.pyplot as plt >>> import matplotlib.widgets as mwidgets >>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [10, 50, 100]) >>> def onselect(vmin, vmax): ... print(vmin, vmax) >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal', ... props=dict(facecolor='blue', alpha=0.5)) >>> fig.show() See also: Span Selector propertyactive_handle[source] connect_default_events()[source] Connect the major canvas events to methods. propertydirection Direction of the span selector: 'vertical' or 'horizontal'. propertyextents Return extents of the span selector. new_axes(ax)[source] Set SpanSelector to operate on a new Axes. propertypressv[source] propertyprev[source] propertyrect[source] propertyrectprops[source] propertyspan_stays[source] classmatplotlib.widgets.SubplotTool(targetfig, toolfig)[source] Bases: matplotlib.widgets.Widget A tool to adjust the subplot params of a matplotlib.figure.Figure. Parameters targetfigFigure The figure instance to adjust. toolfigFigure The figure instance to embed the subplot tool into. classmatplotlib.widgets.TextBox(ax, label, initial='', color='.95', hovercolor='1', label_pad=0.01, textalignment='left')[source] Bases: matplotlib.widgets.AxesWidget A GUI neutral text input box. For the text box to remain responsive you must keep a reference to it. Call on_text_change to be updated whenever the text changes. Call on_submit to be updated whenever the user hits enter or leaves the text entry field. Attributes axAxes The parent axes for the widget. labelText colorcolor The color of the text box when not hovering. hovercolorcolor The color of the text box when hovering. Parameters axAxes The Axes instance the button will be placed into. labelstr Label for this text box. initialstr Initial value in the text box. colorcolor The color of the box. hovercolorcolor The color of the box when the mouse is over it. label_padfloat The distance between the label and the right side of the textbox. textalignment{'left', 'center', 'right'} The horizontal location of the text. propertyDIST_FROM_LEFT[source] begin_typing(x)[source] propertychange_observers[source] propertycnt[source] disconnect(cid)[source] Remove the observer with connection id cid. on_submit(func)[source] When the user hits enter or leaves the submission box, call this func with event. A connection id is returned which can be used to disconnect. on_text_change(func)[source] When the text changes, call this func with event. A connection id is returned which can be used to disconnect. position_cursor(x)[source] set_val(val)[source] stop_typing()[source] propertysubmit_observers[source] propertytext classmatplotlib.widgets.ToolHandles(ax, x, y, marker='o', marker_props=None, useblit=True)[source] Bases: object Control handles for canvas tools. Parameters axmatplotlib.axes.Axes Matplotlib axes where tool handles are displayed. x, y1D arrays Coordinates of control handles. markerstr, default: 'o' Shape of marker used to display handle. See matplotlib.pyplot.plot. marker_propsdict, optional Additional marker properties. See matplotlib.lines.Line2D. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). propertyartists closest(x, y)[source] Return index and pixel distance to closest index. set_animated(val)[source] set_data(pts, y=None)[source] Set x and y positions of handles. set_visible(val)[source] propertyx propertyy classmatplotlib.widgets.ToolLineHandles(ax, positions, direction, line_props=None, useblit=True)[source] Bases: object Control handles for canvas tools. Parameters axmatplotlib.axes.Axes Matplotlib axes where tool handles are displayed. positions1D array Positions of handles in data coordinates. direction{"horizontal", "vertical"} Direction of handles, either 'vertical' or 'horizontal' line_propsdict, optional Additional line properties. See matplotlib.lines.Line2D. useblitbool, default: True Whether to use blitting for faster drawing (if supported by the backend). propertyartists closest(x, y)[source] Return index and pixel distance to closest handle. Parameters x, yfloat x, y position from which the distance will be calculated to determinate the closest handle Returns index, distanceindex of the handle and its distance from position x, y propertydirection Direction of the handle: 'vertical' or 'horizontal'. propertypositions Positions of the handle in data coordinates. remove()[source] Remove the handles artist from the figure. set_animated(value)[source] Set the animated state of the handles artist. set_data(positions)[source] Set x or y positions of handles, depending if the lines are vertical of horizontal. Parameters positionstuple of length 2 Set the positions of the handle in data coordinates set_visible(value)[source] Set the visibility state of the handles artist. classmatplotlib.widgets.Widget[source] Bases: object Abstract base class for GUI neutral widgets. propertyactive Is the widget active? drawon=True eventson=True get_active()[source] Get whether the widget is active. ignore(event)[source] Return whether event should be ignored. This method should be called at the beginning of any event callback. set_active(active)[source] Set whether the widget is active.
matplotlib.widgets_api
classmatplotlib.widgets.AxesWidget(ax)[source] Bases: matplotlib.widgets.Widget Widget connected to a single Axes. To guarantee that the widget remains responsive and not garbage-collected, a reference to the object should be maintained by the user. This is necessary because the callback registry maintains only weak-refs to the functions, which are member functions of the widget. If there are no references to the widget object it may be garbage collected which will disconnect the callbacks. Attributes axAxes The parent axes for the widget. canvasFigureCanvasBase The parent figure canvas for the widget. activebool Is the widget active? propertycids[source] connect_event(event, callback)[source] Connect a callback function with an event. This should be used in lieu of figure.canvas.mpl_connect since this function stores callback ids for later clean up. disconnect_events()[source] Disconnect all events created by this widget.
matplotlib.widgets_api#matplotlib.widgets.AxesWidget
connect_event(event, callback)[source] Connect a callback function with an event. This should be used in lieu of figure.canvas.mpl_connect since this function stores callback ids for later clean up.
matplotlib.widgets_api#matplotlib.widgets.AxesWidget.connect_event
disconnect_events()[source] Disconnect all events created by this widget.
matplotlib.widgets_api#matplotlib.widgets.AxesWidget.disconnect_events