matplotlib.tri#

Unstructured triangular grid functions.

classmatplotlib.tri.Triangulation(x,y,triangles=None,mask=None)[source]#

An unstructured triangular grid consisting of npoints points andntri triangles. The triangles can either be specified by the useror 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 makeup the triangle, ordered in an anticlockwise manner. If notspecified, the Delaunay triangulation is calculated.

mask(ntri,) array-like of bool, optional

Which triangles are masked out.

Attributes:
triangles(ntri, 3) array of int

For each triangle, the indices of the three points that makeup the triangle, ordered in an anticlockwise manner. If you want totake themask into account, useget_masked_triangles instead.

mask(ntri, 3) array of bool or None

Masked out triangles.

is_delaunaybool

Whether the Triangulation is a calculated Delaunaytriangulation (wheretriangles was not specified) or not.

Notes

For a Triangulation to be valid it must not have duplicate points,triangles formed from colinear points, or overlapping triangles.

calculate_plane_coefficients(z)[source]#

Calculate plane equation coefficients for all unmasked triangles fromthe 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 usingz=array[tri,0]*x +array[tri,1]*y+array[tri,2].

propertyedges#

Return integer array of shape (nedges, 2) containing all edges ofnon-masked triangles.

Each row defines an edge by its start point index and end pointindex. Each edge appears only once, i.e. for an edge between pointsi andj, there will only be either(i, j) or(j, i).

get_cpp_triangulation()[source]#

Return the underlying C++ Triangulation object, creating itif necessary.

staticget_from_args_and_kwargs(*args,**kwargs)[source]#

Return a Triangulation object from the args and kwargs, andthe remaining args and kwargs with the consumed values removed.

There are two alternatives: either the first argument is aTriangulation object, in which case it is returned, or the argsand kwargs are sufficient to create a new Triangulation toreturn. In the latter case, see Triangulation.__init__ forthe possible args and kwargs.

get_masked_triangles()[source]#

Return an array of triangles taking the mask into account.

get_trifinder()[source]#

Return the defaultmatplotlib.tri.TriFinder of thistriangulation, creating it if necessary. This allows the sameTriFinder 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 thatshare the same edges, or -1 if there is no such neighboringtriangle.neighbors[i,j] is the triangle that is the neighborto the edge from point indextriangles[i,j] to point indextriangles[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:ContourSet

Create and store a set of contour lines or filled regions fora triangular grid.

This class is typically not instantiated directly by the user but bytricontour andtricontourf.

Attributes:
levelsarray

The values of the contour levels.

layersarray

Same as levels for line contours; half-way betweenlevels for filled contours. SeeContourSet._process_colors.

Draw triangular grid contour lines or filled regions,depending on whether keyword argfilled is False(default) or True.

The first argument of the initializer must be anAxesobject. The remaining arguments and keyword argumentsare described in the docstring oftricontour.

set(*,agg_filter=<UNSET>,alpha=<UNSET>,animated=<UNSET>,antialiased=<UNSET>,array=<UNSET>,capstyle=<UNSET>,clim=<UNSET>,clip_box=<UNSET>,clip_on=<UNSET>,clip_path=<UNSET>,cmap=<UNSET>,color=<UNSET>,edgecolor=<UNSET>,facecolor=<UNSET>,gid=<UNSET>,hatch=<UNSET>,hatch_linewidth=<UNSET>,hatchcolor=<UNSET>,in_layout=<UNSET>,joinstyle=<UNSET>,label=<UNSET>,linestyle=<UNSET>,linewidth=<UNSET>,mouseover=<UNSET>,norm=<UNSET>,offset_transform=<UNSET>,offsets=<UNSET>,path_effects=<UNSET>,paths=<UNSET>,picker=<UNSET>,pickradius=<UNSET>,rasterized=<UNSET>,sketch_params=<UNSET>,snap=<UNSET>,transform=<UNSET>,url=<UNSET>,urls=<UNSET>,visible=<UNSET>,zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties are

Property

Description

agg_filter

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

alpha

array-like or float or None

animated

bool

antialiased oraa orantialiaseds

bool or list of bools

array

array-like or None

capstyle

CapStyle or {'butt', 'projecting', 'round'}

clim

(vmin: float, vmax: float)

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

cmap

Colormap or str or None

color

color or list of RGBA tuples

edgecolor orec oredgecolors

color or list ofcolor or 'face'

facecolor orfacecolors orfc

color or list ofcolor

figure

Figure orSubFigure

gid

str

hatch

{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}

hatch_linewidth

unknown

hatchcolor

color or list ofcolor or 'edge'

in_layout

bool

joinstyle

JoinStyle or {'miter', 'round', 'bevel'}

label

object

linestyle ordashes orlinestyles orls

str or tuple or list thereof

linewidth orlinewidths orlw

float or list of floats

mouseover

bool

norm

Normalize or str or None

offset_transform ortransOffset

Transform

offsets

(N, 2) or (2,) array-like

path_effects

list ofAbstractPathEffect

paths

unknown

picker

None or bool or float or callable

pickradius

float

rasterized

bool

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

transform

Transform

url

str

urls

list of str or None

visible

bool

zorder

float

classmatplotlib.tri.TriFinder(triangulation)[source]#

Abstract base class for classes used to find the triangles of aTriangulation in which (x, y) points lie.

Rather than instantiate an object of a class derived from TriFinder, it isusually better to use the functionTriangulation.get_trifinder.

Derived classes implement __call__(x, y) where x and y are array-like pointcoordinates of the same shape.

classmatplotlib.tri.TrapezoidMapTriFinder(triangulation)[source]#

Bases:TriFinder

TriFinder class implemented using the trapezoidmap algorithm from the book "Computational Geometry, Algorithms andApplications", second edition, by M. de Berg, M. van Kreveld, M. Overmarsand O. Schwarzkopf.

The triangulation must be valid, i.e. it must not have duplicate points,triangles formed from colinear points, or overlapping triangles. Thealgorithm has some tolerance to triangles formed from colinear points, butthis 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, andthat returns a masked array of the same shape containing theinterpolated z-values.

  • gradient(x,y),where x, y are array-like point coordinates of the sameshape, and that returns a list of 2 masked arrays of the same shapecontaining the 2 derivatives of the interpolator (derivatives ofinterpolated z values with respect to x and y).

classmatplotlib.tri.LinearTriInterpolator(triangulation,z,trifinder=None)[source]#

Bases:TriInterpolator

Linear interpolator on a triangular grid.

Each triangle is represented by a plane so that an interpolated value atpoint (x, y) lies on the plane of the triangle containing (x, y).Interpolated values are therefore continuous across the triangulation, buttheir 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 willbe used by callingTriangulation.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 derivativesat the specified (x, y) points.

Parameters:
x, yarray-like

x and y coordinates of the same shape and any number ofdimensions.

Returns:
dzdx, dzdynp.ma.array

2 masked arrays of the same shape asx andy; valuescorresponding to (x, y) points outside of the triangulationare 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:TriInterpolator

Cubic interpolator on a triangular grid.

In one-dimension - on a segment - a cubic interpolating function isdefined 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 valuesof the function and its 2 derivatives have to be defined at each trianglenode.

The CubicTriInterpolator takes the value of the function at each node -provided by the user - and internally computes the value of thederivatives, resulting in a smooth interpolation.(As a special feature, the user can also impose the value of thederivatives at each node, but this is not supposed to be the commonusage.)

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 computethe interpolant derivatives (defaults to 'min_E'):

  • if 'min_E': (default) The derivatives at each node is computedto minimize a bending energy.

  • if 'geom': The derivatives at each node is computed as aweighted average of relevant triangle normals. To be used forspeed optimization (large grids).

  • if 'user': The user provides the argumentdz, no computationis hence needed.

trifinderTriFinder, optional

If not specified, the Triangulation's default TriFinder willbe used by callingTriangulation.get_trifinder.

dztuple of array-likes (dzdx, dzdy), optional

Used only ifkind ='user'. In this casedz must be provided as(dzdx, dzdy) where dzdx, dzdy are arrays of the same shape asz andare the interpolant first derivatives at thetriangulation points.

Methods

`__call__` (x, y)

(Returns interpolated values at (x, y) points.)

`gradient` (x, y)

(Returns interpolated derivatives at (x, y) points.)

Notes

This note is a bit technical and details how the cubic interpolation iscomputed.

The interpolation is based on a Clough-Tocher subdivision scheme ofthetriangulation mesh (to make it clearer, each triangle of thegrid will be divided in 3 child-triangles, and on each child trianglethe 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 iscontinuous and its first derivatives are also continuous (thisis easy to show inside the triangles but is also true when crossing theedges).

In the default case (kind ='min_E'), the interpolant minimizes acurvature energy on the functional space generated by the HCT elementshape functions - with imposed values but arbitrary derivatives at eachnode. The minimized functional is the integral of the so-called totalcurvature (implementation based on an algorithm from[2] - PCG sparsesolver):

\[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 casekind ='geom' is chosen by the user, a simple geometricapproximation is used (weighted average of the triangle normalvectors), which could improve speed on very large grids.

References

[1]

Michel Bernadou, Kamal Hassan, "Basis functions for generalHsieh-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".

gradient(x,y)[source]#

Returns a list of 2 masked arrays containing interpolated derivativesat the specified (x, y) points.

Parameters:
x, yarray-like

x and y coordinates of the same shape and any number ofdimensions.

Returns:
dzdx, dzdynp.ma.array

2 masked arrays of the same shape asx andy; valuescorresponding to (x, y) points outside of the triangulationare 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 formesh refinement and interpolation.

Derived classes must implement:

  • refine_triangulation(return_tri_index=False,**kwargs) , wherethe optional keyword argumentskwargs are defined in eachTriRefiner concrete implementation, and which returns:

    • a refined triangulation,

    • optionally (depending onreturn_tri_index), for eachpoint of the refined triangulation: the index ofthe initial triangulation triangle to which it belongs.

  • refine_field(z,triinterpolator=None,**kwargs), where:

    • z array of field values (to refine) defined at the basetriangulation nodes,

    • triinterpolator is an optionalTriInterpolator,

    • the other optional keyword argumentskwargs are defined ineach TriRefiner concrete implementation;

    and which returns (as a tuple) a refined triangular mesh and theinterpolated values of the field at the refined triangulation nodes.

classmatplotlib.tri.UniformTriRefiner(triangulation)[source]#

Bases: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 theencapsulated triangulation. (n_points is the number of pointsin the initial triangulation)

triinterpolatorTriInterpolator, optional

Interpolator used for field interpolation. If not specified,aCubicTriInterpolator will be used.

subdivint, default: 3

Recursion level for the subdivision.Each triangle is divided into4**subdiv child triangles.

Returns:
refi_triTriangulation

The returned refined triangulation.

refi_z1D array of length:refi_tri node count.

The returned interpolated field (atrefi_tri nodes).

refine_triangulation(return_tri_index=False,subdiv=3)[source]#

Compute a uniformly refined triangulationrefi_triangulation ofthe encapsulatedtriangulation.

This function refines the encapsulated triangulation by splitting eachfather triangle into 4 child sub-triangles built on the edges midsidenodes, recursingsubdiv times. In the end, each triangle is hencedivided into4**subdiv child triangles.

Parameters:
return_tri_indexbool, default: False

Whether an index table indicating the father triangle index of eachpoint is returned.

subdivint, default: 3

Recursion level for the subdivision.Each triangle is divided into4**subdiv child triangles;hence, the default results in 64 refined subtriangles for eachtriangle of the initial triangulation.

Returns:
refi_triangulationTriangulation

The refined triangulation.

found_indexint array

Index of the initial triangulation containing triangle, for eachpoint ofrefi_triangulation.Returned only ifreturn_tri_index is set to True.

classmatplotlib.tri.TriAnalyzer(triangulation)[source]#

Define basic tools for triangular mesh analysis and improvement.

A TriAnalyzer encapsulates aTriangulation object and provides basictools 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 awidely used indicator of a triangle flatness.It is always<=0.5 and==0.5 only for equilateraltriangles. Circle ratios below 0.01 denote very flat triangles.

To avoid unduly low values due to a difference of scale between the 2axis, the triangular mesh can first be rescaled to fit inside a unitsquare withscale_factors (Only ifrescale is True, which isits default value).

Parameters:
rescalebool, default: True

If True, internally rescale (based onscale_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, foreach '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 masknew_mask which allows to clean the encapsulatedtriangulation from its border-located flat triangles(according to theircircle_ratios()).This mask is meant to be subsequently applied to the triangulationusingTriangulation.set_mask.new_mask is an extension of the initial triangulation maskin the sense that an initially masked triangle will remain masked.

Thenew_mask array is computed recursively; at each step flattriangles are removed only if they share a side with the current meshborder. 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 willbe removed if r/R <min_circle_ratio.

rescalebool, default: True

If True, first, internally rescale (based onscale_factors) sothat the (unmasked) triangles fit exactly inside a unit squaremesh. This rescaling accounts for the difference of scale whichmight exist between the 2 axis.

Returns:
array of bool

Mask to apply to encapsulated triangulation.All the initially masked triangles remain masked in thenew_mask.

Notes

The rationale behind this function is that a Delaunaytriangulation - of an unstructured set of points - sometimes containsalmost flat triangles at its border, leading to artifacts in plots(especially for high-resolution contouring).Masked with computednew_mask, the encapsulatedtriangulation would contain no more unmasked border triangleswith a circle ratio belowmin_circle_ratio, thus improving themesh 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.