matplotlib.path#

A module for dealing with the polylines used throughout Matplotlib.

The primary class for polyline handling in Matplotlib isPath. Almost allvector drawing makes use ofPaths somewhere in the drawing pipeline.

Whilst aPath instance itself cannot be drawn, someArtist subclasses,such asPathPatch andPathCollection, can be used for convenientPathvisualisation.

classmatplotlib.path.Path(vertices,codes=None,_interpolation_steps=1,closed=False,readonly=False)[source]#

Bases:object

A series of possibly disconnected, possibly closed, line and curvesegments.

The underlying storage is made up of two parallel numpy arrays:

  • vertices: an (N, 2) float array of vertices

  • codes: an N-lengthnumpy.uint8 array of path codes, or None

These two arrays always have the same length in the firstdimension. For example, to represent a cubic curve, you mustprovide three vertices and threeCURVE4 codes.

The code types are:

  • STOP1 vertex (ignored)

    A marker for the end of the entire path (currently not required andignored)

  • MOVETO1 vertex

    Pick up the pen and move to the given vertex.

  • LINETO1 vertex

    Draw a line from the current position to the given vertex.

  • CURVE31 control point, 1 endpoint

    Draw a quadratic Bézier curve from the current position, with the givencontrol point, to the given end point.

  • CURVE42 control points, 1 endpoint

    Draw a cubic Bézier curve from the current position, with the givencontrol points, to the given end point.

  • CLOSEPOLY1 vertex (ignored)

    Draw a line segment to the start point of the current polyline.

Ifcodes is None, it is interpreted as aMOVETO followed by a seriesofLINETO.

Users of Path objects should not access the vertices and codes arraysdirectly. Instead, they should useiter_segments orcleaned to get thevertex/code pairs. This helps, in particular, to consistently handle thecase ofcodes being None.

Some behavior of Path objects can be controlled by rcParams. See thercParams whose keys start with 'path.'.

Note

The vertices and codes arrays should be treated asimmutable -- there are a number of optimizations and assumptionsmade up front in the constructor that will not change when thedata changes.

Create a new path with the given vertices and codes.

Parameters:
vertices(N, 2) array-like

The path vertices, as an array, masked array or sequence of pairs.Masked values, if any, will be converted to NaNs, which are thenhandled correctly by the Agg PathIterator and other consumers ofpath data, such asiter_segments().

codesarray-like or None, optional

N-length array of integers representing the codes of the path.If not None, codes must be the same length as vertices.If None,vertices will be treated as a series of line segments.

_interpolation_stepsint, optional

Used as a hint to certain projections, such as Polar, that thispath should be linearly interpolated immediately before drawing.This attribute is primarily an implementation detail and is notintended for public use.

closedbool, optional

Ifcodes is None and closed is True, vertices will be treated asline segments of a closed polygon. Note that the last vertex willthen be ignored (as the corresponding code will be set toCLOSEPOLY).

readonlybool, optional

Makes the path behave in an immutable way and sets the verticesand codes as read-only arrays.

CLOSEPOLY=np.uint8(79)#
CURVE3=np.uint8(3)#
CURVE4=np.uint8(4)#
LINETO=np.uint8(2)#
MOVETO=np.uint8(1)#
NUM_VERTICES_FOR_CODE={np.uint8(0):1,np.uint8(1):1,np.uint8(2):1,np.uint8(3):2,np.uint8(4):3,np.uint8(79):1}#

A dictionary mapping Path codes to the number of vertices that thecode expects.

STOP=np.uint8(0)#
classmethodarc(theta1,theta2,n=None,is_wedge=False)[source]#

Return aPath for the unit circle arc from anglestheta1 totheta2 (in degrees).

theta2 is unwrapped to produce the shortest arc within 360 degrees.That is, iftheta2 >theta1 + 360, the arc will be fromtheta1 totheta2 - 360 and not a full circle plus some extra overlap.

Ifn is provided, it is the number of spline segments to make.Ifn is not provided, the number of spline segments isdetermined based on the delta betweentheta1 andtheta2.

classmethodcircle(center=(0.0,0.0),radius=1.0,readonly=False)[source]#

Return aPath representing a circle of a given radius and center.

Parameters:
center(float, float), default: (0, 0)

The center of the circle.

radiusfloat, default: 1

The radius of the circle.

readonlybool

Whether the created path should have the "readonly" argumentset when creating the Path instance.

Notes

The circle is approximated using 8 cubic Bézier curves, as described in

cleaned(transform=None,remove_nans=False,clip=None,*,simplify=False,curves=False,stroke_width=1.0,snap=False,sketch=None)[source]#

Return a newPath with vertices and codes cleaned according to theparameters.

See also

Path.iter_segments

for details of the keyword arguments.

clip_to_bbox(bbox,inside=True)[source]#

Clip the path to the given bounding box.

The path must be made up of one or more closed polygons. Thisalgorithm will not behave correctly for unclosed paths.

Ifinside isTrue, clip to the inside of the box, otherwiseto the outside of the box.

code_type#

alias ofuint8

propertycodes#

The list of codes in thePath as a 1D array.

Each code is one ofSTOP,MOVETO,LINETO,CURVE3,CURVE4 orCLOSEPOLY. For codes that correspond to more than one vertex(CURVE3 andCURVE4), that code will be repeated so that the lengthofvertices andcodes is always the same.

contains_path(path,transform=None)[source]#

Return whether this (closed) path completely contains the given path.

Iftransform is notNone, the path will be transformed beforechecking for containment.

contains_point(point,transform=None,radius=0.0)[source]#

Return whether the area enclosed by the path contains the given point.

The path is always treated as closed; i.e. if the last code is notCLOSEPOLY an implicit segment connecting the last vertex to the firstvertex is assumed.

Parameters:
point(float, float)

The point (x, y) to check.

transformTransform, optional

If notNone,point will be compared toself transformedbytransform; i.e. for a correct check,transform shouldtransform the path into the coordinate system ofpoint.

radiusfloat, default: 0

Additional margin on the path in coordinates ofpoint.The path is extended tangentially byradius/2; i.e. if you woulddraw the path with a linewidth ofradius, all points on the linewould still be considered to be contained in the area. Conversely,negative values shrink the area: Points on the imaginary linewill be considered outside the area.

Returns:
bool

Notes

The current algorithm has some limitations:

  • The result is undefined for points exactly at the boundary(i.e. at the path shifted byradius/2).

  • The result is undefined if there is no enclosed area, i.e. allvertices are on a straight line.

  • If bounding lines start to cross each other due toradius shift,the result is not guaranteed to be correct.

contains_points(points,transform=None,radius=0.0)[source]#

Return whether the area enclosed by the path contains the given points.

The path is always treated as closed; i.e. if the last code is notCLOSEPOLY an implicit segment connecting the last vertex to the firstvertex is assumed.

Parameters:
points(N, 2) array

The points to check. Columns contain x and y values.

transformTransform, optional

If notNone,points will be compared toself transformedbytransform; i.e. for a correct check,transform shouldtransform the path into the coordinate system ofpoints.

radiusfloat, default: 0

Additional margin on the path in coordinates ofpoints.The path is extended tangentially byradius/2; i.e. if you woulddraw the path with a linewidth ofradius, all points on the linewould still be considered to be contained in the area. Conversely,negative values shrink the area: Points on the imaginary linewill be considered outside the area.

Returns:
length-N bool array

Notes

The current algorithm has some limitations:

  • The result is undefined for points exactly at the boundary(i.e. at the path shifted byradius/2).

  • The result is undefined if there is no enclosed area, i.e. allvertices are on a straight line.

  • If bounding lines start to cross each other due toradius shift,the result is not guaranteed to be correct.

copy()[source]#

Return a shallow copy of thePath, which will share thevertices and codes with the sourcePath.

deepcopy(memo=None)[source]#

Return a deepcopy of thePath. ThePath will not bereadonly, even if the sourcePath is.

get_extents(transform=None,**kwargs)[source]#

Get Bbox of the path.

Parameters:
transformTransform, optional

Transform to apply to path before computing extents, if any.

**kwargs

Forwarded toiter_bezier.

Returns:
matplotlib.transforms.Bbox

The extents of the path Bbox([[xmin, ymin], [xmax, ymax]])

statichatch(hatchpattern,density=6)[source]#

Given a hatch specifier,hatchpattern, generates aPath thatcan be used in a repeated hatching pattern.density is thenumber of lines per unit square.

interpolated(steps)[source]#

Return a new path with each segment divided intosteps parts.

Codes other thanLINETO,MOVETO, andCLOSEPOLY are not handled correctly.

Parameters:
stepsint

The number of segments in the new path for each in the original.

Returns:
Path

The interpolated path.

intersects_bbox(bbox,filled=True)[source]#

Return whether this path intersects a givenBbox.

Iffilled is True, then this also returns True if the path completelyencloses theBbox (i.e., the path is treated as filled).

The bounding box is always considered filled.

intersects_path(other,filled=True)[source]#

Return whether if this path intersects another given path.

Iffilled is True, then this also returns True if one path completelyencloses the other (i.e., the paths are treated as filled).

iter_bezier(**kwargs)[source]#

Iterate over each Bézier curve (lines included) in aPath.

Parameters:
**kwargs

Forwarded toiter_segments.

Yields:
BBezierSegment

The Bézier curves that make up the current path. Note in particularthat freestanding points are Bézier curves of order 0, and linesare Bézier curves of order 1 (with two control points).

codecode_type

The code describing what kind of curve is being returned.MOVETO,LINETO,CURVE3, andCURVE4 correspond toBézier curves with 1, 2, 3, and 4 control points (respectively).CLOSEPOLY is aLINETO with the control points correctlychosen based on the start/end points of the current stroke.

iter_segments(transform=None,remove_nans=True,clip=None,snap=False,stroke_width=1.0,simplify=None,curves=True,sketch=None)[source]#

Iterate over all curve segments in the path.

Each iteration returns a pair(vertices,code), whereverticesis a sequence of 1-3 coordinate pairs, andcode is aPath code.

Additionally, this method can provide a number of standard cleanups andconversions to the path.

Parameters:
transformNone orTransform

If not None, the given affine transformation will be applied to thepath.

remove_nansbool, optional

Whether to remove all NaNs from the path and skip over them usingMOVETO commands.

clipNone or (float, float, float, float), optional

If not None, must be a four-tuple (x1, y1, x2, y2)defining a rectangle in which to clip the path.

snapNone or bool, optional

If True, snap all nodes to pixels; if False, don't snap them.If None, snap if the path contains only segmentsparallel to the x or y axes, and no more than 1024 of them.

stroke_widthfloat, optional

The width of the stroke being drawn (used for path snapping).

simplifyNone or bool, optional

Whether to simplify the path by removing verticesthat do not affect its appearance. If None, use theshould_simplify attribute. See alsorcParams["path.simplify"] (default:True)andrcParams["path.simplify_threshold"] (default:0.111111111111).

curvesbool, optional

If True, curve segments will be returned as curve segments.If False, all curves will be converted to line segments.

sketchNone or sequence, optional

If not None, must be a 3-tuple of the form(scale, length, randomness), representing the sketch parameters.

classmethodmake_compound_path(*args)[source]#

Concatenate a list ofPaths into a singlePath, removing allSTOPs.

classmethodmake_compound_path_from_polys(XY)[source]#

Make a compoundPath object to draw a number of polygons with equalnumbers of sides.

(Sourcecode,2x.png,png)

(2x.png,png)

Parameters:
XY(numpolys, numsides, 2) array
propertyreadonly#

True if thePath is read-only.

propertyshould_simplify#

True if the vertices array should be simplified.

propertysimplify_threshold#

The fraction of a pixel difference below which vertices willbe simplified out.

to_polygons(transform=None,width=0,height=0,closed_only=True)[source]#

Convert this path to a list of polygons or polylines. Eachpolygon/polyline is an (N, 2) array of vertices. In other words,each polygon has noMOVETO instructions or curves. Thisis useful for displaying in backends that do not supportcompound paths or Bézier curves.

Ifwidth andheight are both non-zero then the lines willbe simplified so that vertices outside of (0, 0), (width,height) will be clipped.

The resulting polygons will be simplified if thePath.should_simplify attribute of the path isTrue.

Ifclosed_only isTrue (default), only closed polygons,with the last point being the same as the first point, will bereturned. Any unclosed polylines in the path will beexplicitly closed. Ifclosed_only isFalse, any unclosedpolygons in the path will be returned as unclosed polygons,and the closed polygons will be returned explicitly closed bysetting the last point to the same as the first point.

transformed(transform)[source]#

Return a transformed copy of the path.

See also

matplotlib.transforms.TransformedPath

A specialized path class that will cache the transformed result and automatically update when the transform changes.

classmethodunit_circle()[source]#

Return the readonlyPath of the unit circle.

For most cases,Path.circle() will be what you want.

classmethodunit_circle_righthalf()[source]#

Return aPath of the right half of a unit circle.

SeePath.circle for the reference on the approximation used.

classmethodunit_rectangle()[source]#

Return aPath instance of the unit rectangle from (0, 0) to (1, 1).

classmethodunit_regular_asterisk(numVertices)[source]#

Return aPath for a unit regular asterisk with the givennumVertices and radius of 1.0, centered at (0, 0).

classmethodunit_regular_polygon(numVertices)[source]#

Return aPath instance for a unit regular polygon with thegivennumVertices such that the circumscribing circle has radius 1.0,centered at (0, 0).

classmethodunit_regular_star(numVertices,innerCircle=0.5)[source]#

Return aPath for a unit regular star with the givennumVertices and radius of 1.0, centered at (0, 0).

propertyvertices#

The vertices of thePath as an (N, 2) array.

classmethodwedge(theta1,theta2,n=None)[source]#

Return aPath for the unit circle wedge from anglestheta1 totheta2 (in degrees).

theta2 is unwrapped to produce the shortest wedge within 360 degrees.That is, iftheta2 >theta1 + 360, the wedge will be fromtheta1totheta2 - 360 and not a full circle plus some extra overlap.

Ifn is provided, it is the number of spline segments to make.Ifn is not provided, the number of spline segments isdetermined based on the delta betweentheta1 andtheta2.

SeePath.arc for the reference on the approximation used.

matplotlib.path.get_path_collection_extents(master_transform,paths,transforms,offsets,offset_transform)[source]#

Get bounding box of aPathCollections internal objects.

That is, given a sequence ofPaths,Transforms objects, and offsets, as foundin aPathCollection, return the bounding box that encapsulates all of them.

Parameters:
master_transformTransform

Global transformation applied to all paths.

pathslist ofPath
transformslist ofAffine2DBase

If non-empty, this overridesmaster_transform.

offsets(N, 2) array-like
offset_transformAffine2DBase

Transform applied to the offsets before offsetting the path.

Notes

The way thatpaths,transforms andoffsets are combined follows the samemethod as for collections: each is iterated over independently, so if you have 3paths (A, B, C), 2 transforms (α, β) and 1 offset (O), their combinations are asfollows:

  • (A, α, O)

  • (B, β, O)

  • (C, α, O)