_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_29700 | See Migration guide for more details. tf.compat.v1.TensorShape
tf.TensorShape(
dims
)
A TensorShape represents a possibly-partial shape specification for a Tensor. It may be one of the following:
Fully-known shape: has a known number of dimensions and a known size for each dimension. e.g. TensorShape([16, 256])
Partially-known shape: has a known number of dimensions, and an unknown size for one or more dimension. e.g. TensorShape([None, 256])
Unknown shape: has an unknown number of dimensions, and an unknown size in all dimensions. e.g. TensorShape(None)
If a tensor is produced by an operation of type "Foo", its shape may be inferred if there is a registered shape function for "Foo". See Shape functions for details of shape functions and how to register them. Alternatively, the shape may be set explicitly using tf.Tensor.set_shape.
Args
dims A list of Dimensions, or None if the shape is unspecified.
Raises
TypeError If dims cannot be converted to a list of dimensions.
Attributes
dims Deprecated. Returns list of dimensions for this shape. Suggest TensorShape.as_list instead.
ndims Deprecated accessor for rank.
rank Returns the rank of this shape, or None if it is unspecified. Methods as_list View source
as_list()
Returns a list of integers or None for each dimension.
Returns A list of integers or None for each dimension.
Raises
ValueError If self is an unknown shape with an unknown rank. as_proto View source
as_proto()
Returns this shape as a TensorShapeProto. assert_has_rank View source
assert_has_rank(
rank
)
Raises an exception if self is not compatible with the given rank.
Args
rank An integer.
Raises
ValueError If self does not represent a shape with the given rank. assert_is_compatible_with View source
assert_is_compatible_with(
other
)
Raises exception if self and other do not represent the same shape. This method can be used to assert that there exists a shape that both self and other represent.
Args
other Another TensorShape.
Raises
ValueError If self and other do not represent the same shape. assert_is_fully_defined View source
assert_is_fully_defined()
Raises an exception if self is not fully defined in every dimension.
Raises
ValueError If self does not have a known value for every dimension. assert_same_rank View source
assert_same_rank(
other
)
Raises an exception if self and other do not have compatible ranks.
Args
other Another TensorShape.
Raises
ValueError If self and other do not represent shapes with the same rank. concatenate View source
concatenate(
other
)
Returns the concatenation of the dimension in self and other.
Note: If either self or other is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing.
Args
other Another TensorShape.
Returns A TensorShape whose dimensions are the concatenation of the dimensions in self and other.
is_compatible_with View source
is_compatible_with(
other
)
Returns True iff self is compatible with other. Two possibly-partially-defined shapes are compatible if there exists a fully-defined shape that both shapes can represent. Thus, compatibility allows the shape inference code to reason about partially-defined shapes. For example: TensorShape(None) is compatible with all shapes. TensorShape([None, None]) is compatible with all two-dimensional shapes, such as TensorShape([32, 784]), and also TensorShape(None). It is not compatible with, for example, TensorShape([None]) or TensorShape([None, None, None]). TensorShape([32, None]) is compatible with all two-dimensional shapes with size 32 in the 0th dimension, and also TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32]), TensorShape([32, None, 1]) or TensorShape([64, None]). TensorShape([32, 784]) is compatible with itself, and also TensorShape([32, None]), TensorShape([None, 784]), TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32, 1, 784]) or TensorShape([None]). The compatibility relation is reflexive and symmetric, but not transitive. For example, TensorShape([32, 784]) is compatible with TensorShape(None), and TensorShape(None) is compatible with TensorShape([4, 4]), but TensorShape([32, 784]) is not compatible with TensorShape([4, 4]).
Args
other Another TensorShape.
Returns True iff self is compatible with other.
is_fully_defined View source
is_fully_defined()
Returns True iff self is fully defined in every dimension. merge_with View source
merge_with(
other
)
Returns a TensorShape combining the information in self and other. The dimensions in self and other are merged elementwise, according to the rules defined for Dimension.merge_with().
Args
other Another TensorShape.
Returns A TensorShape containing the combined information of self and other.
Raises
ValueError If self and other are not compatible. most_specific_compatible_shape View source
most_specific_compatible_shape(
other
)
Returns the most specific TensorShape compatible with self and other. TensorShape([None, 1]) is the most specific TensorShape compatible with both TensorShape([2, 1]) and TensorShape([5, 1]). Note that TensorShape(None) is also compatible with above mentioned TensorShapes. TensorShape([1, 2, 3]) is the most specific TensorShape compatible with both TensorShape([1, 2, 3]) and TensorShape([1, 2, 3]). There are more less specific TensorShapes compatible with above mentioned TensorShapes, e.g. TensorShape([1, 2, None]), TensorShape(None).
Args
other Another TensorShape.
Returns A TensorShape which is the most specific compatible shape of self and other.
num_elements View source
num_elements()
Returns the total number of elements, or none for incomplete shapes. with_rank View source
with_rank(
rank
)
Returns a shape based on self with the given rank. This method promotes a completely unknown shape to one with a known rank.
Args
rank An integer.
Returns A shape that is at least as specific as self with the given rank.
Raises
ValueError If self does not represent a shape with the given rank. with_rank_at_least View source
with_rank_at_least(
rank
)
Returns a shape based on self with at least the given rank.
Args
rank An integer.
Returns A shape that is at least as specific as self with at least the given rank.
Raises
ValueError If self does not represent a shape with at least the given rank. with_rank_at_most View source
with_rank_at_most(
rank
)
Returns a shape based on self with at most the given rank.
Args
rank An integer.
Returns A shape that is at least as specific as self with at most the given rank.
Raises
ValueError If self does not represent a shape with at most the given rank. __add__ View source
__add__(
other
)
__bool__ View source
__bool__()
Returns True if this shape contains non-zero information. __concat__ View source
__concat__(
other
)
__eq__ View source
__eq__(
other
)
Returns True if self is equivalent to other. __getitem__ View source
__getitem__(
key
)
Returns the value of a dimension or a shape, depending on the key.
Args
key If key is an integer, returns the dimension at that index; otherwise if key is a slice, returns a TensorShape whose dimensions are those selected by the slice from self.
Returns An integer if key is an integer, or a TensorShape if key is a slice.
Raises
ValueError If key is a slice and self is completely unknown and the step is set. __iter__ View source
__iter__()
Returns self.dims if the rank is known, otherwise raises ValueError. __len__ View source
__len__()
Returns the rank of this shape, or raises ValueError if unspecified. __ne__ View source
__ne__(
other
)
Returns True if self is known to be different from other. __nonzero__ View source
__nonzero__()
Returns True if this shape contains non-zero information. __radd__ View source
__radd__(
other
) | |
doc_29701 |
Aggregate using one or more operations over the specified axis. Parameters
func:function, str, list or dict
Function to use for aggregating the data. If a function, must either work when passed a Series or when passed to Series.apply. Accepted combinations are: function string function name list of functions and/or function names, e.g. [np.sum, 'mean'] dict of axis labels -> functions, function names or list of such. Can also accept a Numba JIT function with engine='numba' specified. Only passing a single function is supported with this engine. If the 'numba' engine is chosen, the function must be a user defined function with values and index as the first and second arguments respectively in the function signature. Each group’s index will be passed to the user defined function and optionally available for use. Changed in version 1.1.0. *args
Positional arguments to pass to func.
engine:str, default None
'cython' : Runs the function through C-extensions from cython. 'numba' : Runs the function through JIT compiled code from numba. None : Defaults to 'cython' or globally setting compute.use_numba New in version 1.1.0.
engine_kwargs:dict, default None
For 'cython' engine, there are no accepted engine_kwargs For 'numba' engine, the engine can accept nopython, nogil and parallel dictionary keys. The values must either be True or False. The default engine_kwargs for the 'numba' engine is {'nopython': True, 'nogil': False, 'parallel': False} and will be applied to the function New in version 1.1.0. **kwargs
Keyword arguments to be passed into func. Returns
Series
See also Series.groupby.apply
Apply function func group-wise and combine the results together. Series.groupby.transform
Aggregate using one or more operations over the specified axis. Series.aggregate
Transforms the Series on each group based on the given function. Notes When using engine='numba', there will be no “fall back” behavior internally. The group data and group index will be passed as numpy arrays to the JITed user defined function, and no alternative execution attempts will be tried. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details. Changed in version 1.3.0: The resulting dtype will reflect the return value of the passed func, see the examples below. Examples
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.groupby([1, 1, 2, 2]).min()
1 1
2 3
dtype: int64
>>> s.groupby([1, 1, 2, 2]).agg('min')
1 1
2 3
dtype: int64
>>> s.groupby([1, 1, 2, 2]).agg(['min', 'max'])
min max
1 1 2
2 3 4
The output column names can be controlled by passing the desired column names and aggregations as keyword arguments.
>>> s.groupby([1, 1, 2, 2]).agg(
... minimum='min',
... maximum='max',
... )
minimum maximum
1 1 2
2 3 4
Changed in version 1.3.0: The resulting dtype will reflect the return value of the aggregating function.
>>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min())
1 1.0
2 3.0
dtype: float64 | |
doc_29702 |
Implement the default Matplotlib key bindings for the canvas and toolbar described at Navigation keyboard shortcuts. Parameters
eventKeyEvent
A key press/release event.
canvasFigureCanvasBase, default: event.canvas
The backend-specific canvas instance. This parameter is kept for back-compatibility, but, if set, should always be equal to event.canvas.
toolbarNavigationToolbar2, default: event.canvas.toolbar
The navigation cursor toolbar. This parameter is kept for back-compatibility, but, if set, should always be equal to event.canvas.toolbar. | |
doc_29703 | Raised when a system call is interrupted by an incoming signal. Corresponds to errno EINTR. Changed in version 3.5: Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. | |
doc_29704 |
Return the locations of the ticks. Note Because the values are fixed, vmin and vmax are not used in this method. | |
doc_29705 |
Bases: tuple Create new instance of PsFont(texname, psname, effects, encoding, filename) effects
Alias for field number 2
encoding
Alias for field number 3
filename
Alias for field number 4
psname
Alias for field number 1
texname
Alias for field number 0 | |
doc_29706 | Return a list of all the message’s field values. | |
doc_29707 |
Check if the interval is open on the right side. For the meaning of closed and open see Interval. Returns
bool
True if the Interval is closed on the left-side. | |
doc_29708 | See Migration guide for more details. tf.compat.v1.random.uniform, tf.compat.v1.random_uniform
tf.random.uniform(
shape, minval=0, maxval=None, dtype=tf.dtypes.float32, seed=None, name=None
)
The generated values follow a uniform distribution in the range [minval, maxval). The lower bound minval is included in the range, while the upper bound maxval is excluded. For floats, the default range is [0, 1). For ints, at least maxval must be specified explicitly. In the integer case, the random integers are slightly biased unless maxval - minval is an exact power of two. The bias is small for values of maxval - minval significantly smaller than the range of the output (either 2**32 or 2**64). Examples:
tf.random.uniform(shape=[2])
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([..., ...], dtype=float32)>
tf.random.uniform(shape=[], minval=-1., maxval=0.)
<tf.Tensor: shape=(), dtype=float32, numpy=-...>
tf.random.uniform(shape=[], minval=5, maxval=10, dtype=tf.int64)
<tf.Tensor: shape=(), dtype=int64, numpy=...>
The seed argument produces a deterministic sequence of tensors across multiple calls. To repeat that sequence, use tf.random.set_seed:
tf.random.set_seed(5)
tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=2>
tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=0>
tf.random.set_seed(5)
tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=2>
tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10)
<tf.Tensor: shape=(), dtype=int32, numpy=0>
Without tf.random.set_seed but with a seed argument is specified, small changes to function graphs or previously executed operations will change the returned value. See tf.random.set_seed for details.
Args
shape A 1-D integer Tensor or Python array. The shape of the output tensor.
minval A Tensor or Python value of type dtype, broadcastable with shape (for integer types, broadcasting is not supported, so it needs to be a scalar). The lower bound on the range of random values to generate (inclusive). Defaults to 0.
maxval A Tensor or Python value of type dtype, broadcastable with shape (for integer types, broadcasting is not supported, so it needs to be a scalar). The upper bound on the range of random values to generate (exclusive). Defaults to 1 if dtype is floating point.
dtype The type of the output: float16, float32, float64, int32, or int64.
seed A Python integer. Used in combination with tf.random.set_seed to create a reproducible sequence of tensors across multiple calls.
name A name for the operation (optional).
Returns A tensor of the specified shape filled with random uniform values.
Raises
ValueError If dtype is integral and maxval is not specified. | |
doc_29709 | Return the current process’s real user id. Availability: Unix. | |
doc_29710 |
Bases: matplotlib.collections.RegularPolyCollection Draw a collection of regular asterisks with numsides points. Parameters
numsidesint
The number of sides of the polygon.
rotationfloat
The rotation of the polygon in radians.
sizestuple of float
The area of the circle circumscribing the polygon in points^2. **kwargs
Forwarded to Collection. Examples See Lasso Demo for a complete example: offsets = np.random.rand(20, 2)
facecolors = [cm.jet(x) for x in np.random.rand(20)]
collection = RegularPolyCollection(
numsides=5, # a pentagon
rotation=0, sizes=(50,),
facecolors=facecolors,
edgecolors=("black",),
linewidths=(1,),
offsets=offsets,
transOffset=ax.transData,
)
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_numsides()[source]
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_rotation()[source]
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.BrokenBarHCollection(xranges, yrange, **kwargs)[source]
Bases: matplotlib.collections.PolyCollection A collection of horizontal bars spanning yrange with a sequence of xranges. Parameters
xrangeslist of (float, float)
The sequence of (left-edge-position, width) pairs for each bar.
yrange(float, float)
The (lower-edge, height) common to all bars. **kwargs
Forwarded to Collection. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, verts=<UNSET>, verts_and_codes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
paths list of array-like
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
verts list of array-like
verts_and_codes unknown
visible bool
zorder float
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths(verts, closed=True)[source]
Set the vertices of the polygons. Parameters
vertslist of array-like
The sequence of polygons [verts0, verts1, ...] where each element verts_i defines the vertices of polygon i as a 2D array-like of shape (M, 2).
closedbool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY connection at the end.
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_verts(verts, closed=True)[source]
Set the vertices of the polygons. Parameters
vertslist of array-like
The sequence of polygons [verts0, verts1, ...] where each element verts_i defines the vertices of polygon i as a 2D array-like of shape (M, 2).
closedbool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY connection at the end.
set_verts_and_codes(verts, codes)[source]
Initialize vertices with path codes.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
classmethodspan_where(x, ymin, ymax, where, **kwargs)[source]
Return a BrokenBarHCollection that plots horizontal bars from over the regions in x where where is True. The bars range on the y-axis from ymin to ymax kwargs are passed on to the collection.
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.CircleCollection(sizes, **kwargs)[source]
Bases: matplotlib.collections._CollectionWithSizes A collection of circles, drawn using splines. Parameters
sizesfloat or array-like
The area of each circle in points^2. **kwargs
Forwarded to Collection. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.Collection(edgecolors=None, facecolors=None, linewidths=None, linestyles='solid', capstyle=None, joinstyle=None, antialiaseds=None, offsets=None, transOffset=None, norm=None, cmap=None, pickradius=5.0, hatch=None, urls=None, *, zorder=1, **kwargs)[source]
Bases: matplotlib.artist.Artist, matplotlib.cm.ScalarMappable Base class for Collections. Must be subclassed to be usable. A Collection represents a sequence of Patches that can be drawn more efficiently together than individually. For example, when a single path is being drawn repeatedly at different offsets, the renderer can typically execute a draw_marker() call much more efficiently than a series of repeated calls to draw_path() with the offsets put in one-by-one. Most properties of a collection can be configured per-element. Therefore, Collections have "plural" versions of many of the properties of a Patch (e.g. Collection.get_paths instead of Patch.get_path). Exceptions are the zorder, hatch, pickradius, capstyle and joinstyle properties, which can only be set globally for the whole collection. Besides these exceptions, all properties can be specified as single values (applying to all elements) or sequences of values. The property of the ith element of the collection is: prop[i % len(prop)]
Each Collection can optionally be used as its own ScalarMappable by passing the norm and cmap parameters to its constructor. If the Collection's ScalarMappable matrix _A has been set (via a call to Collection.set_array), then at draw time this internal scalar mappable will be used to set the facecolors and edgecolors, ignoring those that were manually passed in. Parameters
edgecolorscolor or list of colors, default: rcParams["patch.edgecolor"] (default: 'black')
Edge color for each patch making up the collection. The special value 'face' can be passed to make the edgecolor match the facecolor.
facecolorscolor or list of colors, default: rcParams["patch.facecolor"] (default: 'C0')
Face color for each patch making up the collection.
linewidthsfloat or list of floats, default: rcParams["patch.linewidth"] (default: 1.0)
Line width for each patch making up the collection.
linestylesstr or tuple or list thereof, default: 'solid'
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink lengths in points. For examples, see Linestyles.
capstyleCapStyle-like, default: rcParams["patch.capstyle"]
Style to use for capping lines for all paths in the collection. Allowed values are {'butt', 'projecting', 'round'}.
joinstyleJoinStyle-like, default: rcParams["patch.joinstyle"]
Style to use for joining lines for all paths in the collection. Allowed values are {'miter', 'round', 'bevel'}.
antialiasedsbool or list of bool, default: rcParams["patch.antialiased"] (default: True)
Whether each patch in the collection should be drawn with antialiasing.
offsets(float, float) or list thereof, default: (0, 0)
A vector by which to translate each patch after rendering (default is no translation). The translation is performed in screen (pixel) coordinates (i.e. after the Artist's transform is applied).
transOffsetTransform, default: IdentityTransform
A single transform which will be applied to each offsets vector before it is used.
normNormalize, optional
Forwarded to ScalarMappable. The default of None means that the first draw call will set vmin and vmax using the minimum and maximum values of the data.
cmapColormap, optional
Forwarded to ScalarMappable. The default of None will result in rcParams["image.cmap"] (default: 'viridis') being used.
hatchstr, optional
Hatching pattern to use in filled paths, if any. Valid strings are ['/', '', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See Hatch style reference for the meaning of each hatch type.
pickradiusfloat, default: 5.0
If pickradius <= 0, then Collection.contains will return True whenever the test point is inside of one of the polygons formed by the control points of a Path in the Collection. On the other hand, if it is greater than 0, then we instead check if the test point is contained in a stroke of width 2*pickradius following any of the Paths in the Collection.
urlslist of str, default: None
A URL for each patch to link to once drawn. Currently only works for the SVG backend. See Hyperlinks for examples.
zorderfloat, default: 1
The drawing order, shared by all Patches in the Collection. See Zorder Demo for all defaults and examples. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<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
alpha array-like or scalar or None
animated bool
antialiased bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 color or list of colors or 'face'
facecolor color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle str or tuple or list thereof
linewidth float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.EllipseCollection(widths, heights, angles, units='points', **kwargs)[source]
Bases: matplotlib.collections.Collection A collection of ellipses, drawn using splines. Parameters
widthsarray-like
The lengths of the first axes (e.g., major axis lengths).
heightsarray-like
The lengths of second axes.
anglesarray-like
The angles of the first axes, degrees CCW from the x-axis.
units{'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
The units in which majors and minors are given; 'width' and 'height' refer to the dimensions of the axes, while 'x' and 'y' refer to the offsets data units. 'xy' differs from all others in that the angle as plotted varies with the aspect ratio, and equals the specified angle only when the aspect ratio is unity. Hence it behaves the same as the Ellipse with axes.transData as its transform. **kwargs
Forwarded to Collection. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.EventCollection(positions, orientation='horizontal', lineoffset=0, linelength=1, linewidth=None, color=None, linestyle='solid', antialiased=None, **kwargs)[source]
Bases: matplotlib.collections.LineCollection A collection of locations along a single axis at which an "event" occurred. The events are given by a 1-dimensional array. They do not have an amplitude and are displayed as parallel lines. Parameters
positions1D array-like
Each value is an event.
orientation{'horizontal', 'vertical'}, default: 'horizontal'
The sequence of events is plotted along this direction. The marker lines of the single events are along the orthogonal direction.
lineoffsetfloat, default: 0
The offset of the center of the markers from the origin, in the direction orthogonal to orientation.
linelengthfloat, default: 1
The total height of the marker (i.e. the marker stretches from lineoffset - linelength/2 to lineoffset + linelength/2).
linewidthfloat or list thereof, default: rcParams["lines.linewidth"] (default: 1.5)
The line width of the event lines, in points.
colorcolor or list of colors, default: rcParams["lines.color"] (default: 'C0')
The color of the event lines.
linestylestr or tuple or list thereof, default: 'solid'
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points.
antialiasedbool or list thereof, default: rcParams["lines.antialiased"] (default: True)
Whether to use antialiasing for drawing the lines. **kwargs
Forwarded to LineCollection. Examples (Source code, png, pdf) add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
add_positions(position)[source]
Add one or more events at the specified positions.
append_positions(position)[source]
Add one or more events at the specified positions.
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
extend_positions(position)[source]
Add one or more events at the specified positions.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_color()[source]
Return the color of the lines used to mark each event.
get_colors()[source]
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linelength()[source]
Return the length of the lines used to mark each event.
get_lineoffset()[source]
Return the offset of the lines used to mark each event.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
Get the width of the lines used to mark each event.
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_orientation()[source]
Return the orientation of the event line ('horizontal' or 'vertical').
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_positions()[source]
Return an array containing the floating-point values of the positions.
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_segments()[source]
Returns
list
List of segments in the LineCollection. Each list item contains an array of vertices.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_horizontal()[source]
True if the eventcollection is horizontal, False if vertical.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, colors=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linelength=<UNSET>, lineoffset=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, orientation=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, positions=<UNSET>, rasterized=<UNSET>, segments=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, verts=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
cmap Colormap or str or None
color color or list of colors
colors color or list of colors
edgecolor or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linelength unknown
lineoffset unknown
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
orientation {'horizontal', 'vertical'}
path_effects AbstractPathEffect
paths unknown
picker None or bool or float or callable
pickradius float
positions unknown
rasterized bool
segments unknown
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
verts unknown
visible bool
zorder float
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set the edgecolor(s) of the LineCollection. Parameters
ccolor or list of colors
Single color (all lines have same color), or a sequence of rgba tuples; if it is a sequence the lines will cycle through the sequence.
set_colors(c)[source]
Set the edgecolor(s) of the LineCollection. Parameters
ccolor or list of colors
Single color (all lines have same color), or a sequence of rgba tuples; if it is a sequence the lines will cycle through the sequence.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linelength(linelength)[source]
Set the length of the lines used to mark each event.
set_lineoffset(lineoffset)[source]
Set the offset of the lines used to mark each event.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_orientation(orientation)[source]
Set the orientation of the event line. Parameters
orientation{'horizontal', 'vertical'}
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths(segments)[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_positions(positions)[source]
Set the positions of the events.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_segments(segments)[source]
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_verts(segments)[source]
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
switch_orientation()[source]
Switch the orientation of the event line, either from vertical to horizontal or vice versus.
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.LineCollection(segments, *args, zorder=2, **kwargs)[source]
Bases: matplotlib.collections.Collection Represents a sequence of Line2Ds that should be drawn together. This class extends Collection to represent a sequence of Line2Ds instead of just a sequence of Patchs. Just as in Collection, each property of a LineCollection may be either a single value or a list of values. This list is then used cyclically for each element of the LineCollection, so the property of the ith element of the collection is: prop[i % len(prop)]
The properties of each member of a LineCollection default to their values in rcParams["lines.*"] instead of rcParams["patch.*"], and the property colors is added in place of edgecolors. Parameters
segmentslist of array-like
A sequence of (line0, line1, line2), where: linen = (x0, y0), (x1, y1), ... (xm, ym)
or the equivalent numpy array with two columns. Each line can have a different number of segments.
linewidthsfloat or list of float, default: rcParams["lines.linewidth"] (default: 1.5)
The width of each line in points.
colorscolor or list of color, default: rcParams["lines.color"] (default: 'C0')
A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not allowed).
antialiasedsbool or list of bool, default: rcParams["lines.antialiased"] (default: True)
Whether to use antialiasing for each line.
zorderint, default: 2
zorder of the lines once drawn.
facecolorscolor or list of color, default: 'none'
When setting facecolors, each line is interpreted as a boundary for an area, implicitly closing the path from the last point to the first point. The enclosed area is filled with facecolor. In order to manually specify what should count as the "interior" of each line, please use PathCollection instead, where the "interior" can be specified by appropriate usage of CLOSEPOLY. **kwargs
Forwarded to Collection. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_color()[source]
get_colors()[source]
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_segments()[source]
Returns
list
List of segments in the LineCollection. Each list item contains an array of vertices.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, colors=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, segments=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, verts=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
cmap Colormap or str or None
color color or list of colors
colors color or list of colors
edgecolor or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
paths unknown
picker None or bool or float or callable
pickradius float
rasterized bool
segments unknown
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
verts unknown
visible bool
zorder float
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set the edgecolor(s) of the LineCollection. Parameters
ccolor or list of colors
Single color (all lines have same color), or a sequence of rgba tuples; if it is a sequence the lines will cycle through the sequence.
set_colors(c)[source]
Set the edgecolor(s) of the LineCollection. Parameters
ccolor or list of colors
Single color (all lines have same color), or a sequence of rgba tuples; if it is a sequence the lines will cycle through the sequence.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths(segments)[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_segments(segments)[source]
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_verts(segments)[source]
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.PatchCollection(patches, match_original=False, **kwargs)[source]
Bases: matplotlib.collections.Collection A generic collection of patches. This makes it easier to assign a colormap to a heterogeneous collection of patches. This also may improve plotting speed, since PatchCollection will draw faster than a large number of patches. patches
a sequence of Patch objects. This list may include a heterogeneous assortment of different patch types. match_original
If True, use the colors and linewidths of the original patches. If False, new colors may be assigned by providing the standard collection arguments, facecolor, edgecolor, linewidths, norm or cmap. If any of edgecolors, facecolors, linewidths, antialiaseds are None, they default to their rcParams patch setting, in sequence form. The use of ScalarMappable functionality is optional. If the ScalarMappable matrix _A has been set (via a call to set_array), at draw time a call to scalar mappable will be made to set the face colors. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths(patches)[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.PathCollection(paths, sizes=None, **kwargs)[source]
Bases: matplotlib.collections._CollectionWithSizes A collection of Paths, as created by e.g. scatter. Parameters
pathslist of path.Path
The paths that will make up the Collection.
sizesarray-like
The factor by which to scale each drawn Path. One unit squared in the Path's data space is scaled to be sizes**2 points when rendered. **kwargs
Forwarded to Collection. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
legend_elements(prop='colors', num='auto', fmt=None, func=<function PathCollection.<lambda>>, **kwargs)[source]
Create legend handles and labels for a PathCollection. Each legend handle is a Line2D representing the Path that was drawn, and each label is a string what each Path represents. This is useful for obtaining a legend for a scatter plot; e.g.: scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3])
plt.legend(*scatter.legend_elements())
creates three legend elements, one for each color with the numerical values passed to c as the labels. Also see the Automated legend creation example. Parameters
prop{"colors", "sizes"}, default: "colors"
If "colors", the legend handles will show the different colors of the collection. If "sizes", the legend will show the different sizes. To set both, use kwargs to directly edit the Line2D properties.
numint, None, "auto" (default), array-like, or Locator
Target number of elements to create. If None, use all unique elements of the mappable array. If an integer, target to use num elements in the normed range. If "auto", try to determine which option better suits the nature of the data. The number of created elements may slightly deviate from num due to a Locator being used to find useful locations. If a list or array, use exactly those elements for the legend. Finally, a Locator can be provided.
fmtstr, Formatter, or None (default)
The format or formatter to use for the labels. If a string must be a valid input for a StrMethodFormatter. If None (the default), use a ScalarFormatter.
funcfunction, default: lambda x: x
Function to calculate the labels. Often the size (or color) argument to scatter will have been pre-processed by the user using a function s = f(x) to make the markers visible; e.g. size = np.log10(x). Providing the inverse of this function here allows that pre-processing to be inverted, so that the legend labels have the correct values; e.g. func = lambda
x: 10**x. **kwargs
Allowed keyword arguments are color and size. E.g. it may be useful to set the color of the markers if prop="sizes" is used; similarly to set the size of the markers if prop="colors" is used. Any further parameters are passed onto the Line2D instance. This may be useful to e.g. specify a different markeredgecolor or alpha for the legend handles. Returns
handleslist of Line2D
Visual representation of each element of the legend.
labelslist of str
The string labels for elements of the legend.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
paths unknown
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths(paths)[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.PolyCollection(verts, sizes=None, closed=True, **kwargs)[source]
Bases: matplotlib.collections._CollectionWithSizes Parameters
vertslist of array-like
The sequence of polygons [verts0, verts1, ...] where each element verts_i defines the vertices of polygon i as a 2D array-like of shape (M, 2).
sizesarray-like, default: None
Squared scaling factors for the polygons. The coordinates of each polygon verts_i are multiplied by the square-root of the corresponding entry in sizes (i.e., sizes specify the scaling of areas). The scaling is applied before the Artist master transform.
closedbool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY connection at the end. **kwargs
Forwarded to Collection. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, paths=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, urls=<UNSET>, verts=<UNSET>, verts_and_codes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
paths list of array-like
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
urls list of str or None
verts list of array-like
verts_and_codes unknown
visible bool
zorder float
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths(verts, closed=True)[source]
Set the vertices of the polygons. Parameters
vertslist of array-like
The sequence of polygons [verts0, verts1, ...] where each element verts_i defines the vertices of polygon i as a 2D array-like of shape (M, 2).
closedbool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY connection at the end.
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_verts(verts, closed=True)[source]
Set the vertices of the polygons. Parameters
vertslist of array-like
The sequence of polygons [verts0, verts1, ...] where each element verts_i defines the vertices of polygon i as a 2D array-like of shape (M, 2).
closedbool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY connection at the end.
set_verts_and_codes(verts, codes)[source]
Initialize vertices with path codes.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.QuadMesh(coordinates, *, antialiased=True, shading='flat', pickradius=0, **kwargs)[source]
Bases: matplotlib.collections.Collection Class for the efficient drawing of a quadrilateral mesh. A quadrilateral mesh is a grid of M by N adjacent qudrilaterals that are defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is defined by the vertices (m+1, n) ----------- (m+1, n+1)
/ /
/ /
/ /
(m, n) -------- (m, n+1)
The mesh need not be regular and the polygons need not be convex. Parameters
coordinates(M+1, N+1, 2) array-like
The vertices. coordinates[m, n] specifies the (x, y) coordinates of vertex (m, n).
antialiasedbool, default: True
shading{'flat', 'gouraud'}, default: 'flat'
Notes Unlike other Collections, the default pickradius of QuadMesh is 0, i.e. contains checks whether the test point is within any of the mesh quadrilaterals. There exists a deprecated API version QuadMesh(M, N, coords), where the dimensions are given explicitly and coords is a (M*N, 2) array-like. This has been deprecated in Matplotlib 3.5. The following describes the semantics of this deprecated API. A quadrilateral mesh consists of a grid of vertices. The dimensions of this array are (meshWidth + 1, meshHeight + 1). Each vertex in the mesh has a different set of "mesh coordinates" representing its position in the topology of the mesh. For any values (m, n) such that 0 <= m <= meshWidth and 0 <= n <= meshHeight, the vertices at mesh coordinates (m, n), (m, n + 1), (m + 1, n + 1), and (m + 1, n) form one of the quadrilaterals in the mesh. There are thus (meshWidth * meshHeight) quadrilaterals in the mesh. The mesh need not be regular and the polygons need not be convex. A quadrilateral mesh is represented by a (2 x ((meshWidth + 1) * (meshHeight + 1))) numpy array coordinates, where each row is the x and y coordinates of one of the vertices. To define the function that maps from a data point to its corresponding color, use the set_cmap() method. Each of these arrays is indexed in row-major order by the mesh coordinates of the vertex (or the mesh coordinates of the lower left vertex, in the case of the colors). For example, the first entry in coordinates is the coordinates of the vertex at mesh coordinates (0, 0), then the one at (0, 1), then at (0, 2) .. (0, meshWidth), (1, 0), (1, 1), and so on. Parameters
edgecolorscolor or list of colors, default: rcParams["patch.edgecolor"] (default: 'black')
Edge color for each patch making up the collection. The special value 'face' can be passed to make the edgecolor match the facecolor.
facecolorscolor or list of colors, default: rcParams["patch.facecolor"] (default: 'C0')
Face color for each patch making up the collection.
linewidthsfloat or list of floats, default: rcParams["patch.linewidth"] (default: 1.0)
Line width for each patch making up the collection.
linestylesstr or tuple or list thereof, default: 'solid'
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink lengths in points. For examples, see Linestyles.
capstyleCapStyle-like, default: rcParams["patch.capstyle"]
Style to use for capping lines for all paths in the collection. Allowed values are {'butt', 'projecting', 'round'}.
joinstyleJoinStyle-like, default: rcParams["patch.joinstyle"]
Style to use for joining lines for all paths in the collection. Allowed values are {'miter', 'round', 'bevel'}.
antialiasedsbool or list of bool, default: rcParams["patch.antialiased"] (default: True)
Whether each patch in the collection should be drawn with antialiasing.
offsets(float, float) or list thereof, default: (0, 0)
A vector by which to translate each patch after rendering (default is no translation). The translation is performed in screen (pixel) coordinates (i.e. after the Artist's transform is applied).
transOffsetTransform, default: IdentityTransform
A single transform which will be applied to each offsets vector before it is used.
normNormalize, optional
Forwarded to ScalarMappable. The default of None means that the first draw call will set vmin and vmax using the minimum and maximum values of the data.
cmapColormap, optional
Forwarded to ScalarMappable. The default of None will result in rcParams["image.cmap"] (default: 'viridis') being used.
hatchstr, optional
Hatching pattern to use in filled paths, if any. Valid strings are ['/', '', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See Hatch style reference for the meaning of each hatch type.
pickradiusfloat, default: 5.0
If pickradius <= 0, then Collection.contains will return True whenever the test point is inside of one of the polygons formed by the control points of a Path in the Collection. On the other hand, if it is greater than 0, then we instead check if the test point is contained in a stroke of width 2*pickradius following any of the Paths in the Collection.
urlslist of str, default: None
A URL for each patch to link to once drawn. Currently only works for the SVG backend. See Hyperlinks for examples.
zorderfloat, default: 1
The drawing order, shared by all Patches in the Collection. See Zorder Demo for all defaults and examples. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
staticconvert_mesh_to_paths(meshWidth, meshHeight, coordinates)[source]
[Deprecated] Notes Deprecated since version 3.5:
convert_mesh_to_triangles(meshWidth, meshHeight, coordinates)[source]
[Deprecated] Notes Deprecated since version 3.5:
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_coordinates()[source]
Return the vertices of the mesh as an (M+1, N+1, 2) array. M, N are the number of quadrilaterals in the rows / columns of the mesh, corresponding to (M+1, N+1) vertices. The last dimension specifies the components (x, y).
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array (M, N) array-like or M*N array-like
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the data values. Parameters
A(M, N) array-like or M*N array-like
If the values are provided as a 2D grid, the shape must match the coordinates grid. If the values are 1D, they are reshaped to 2D. M, N follow from the coordinates grid, where the coordinates grid shape is (M, N) for 'gouraud' shading and (M+1, N+1) for 'flat' shading.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.RegularPolyCollection(numsides, rotation=0, sizes=(1,), **kwargs)[source]
Bases: matplotlib.collections._CollectionWithSizes A collection of n-sided regular polygons. Parameters
numsidesint
The number of sides of the polygon.
rotationfloat
The rotation of the polygon in radians.
sizestuple of float
The area of the circle circumscribing the polygon in points^2. **kwargs
Forwarded to Collection. Examples See Lasso Demo for a complete example: offsets = np.random.rand(20, 2)
facecolors = [cm.jet(x) for x in np.random.rand(20)]
collection = RegularPolyCollection(
numsides=5, # a pentagon
rotation=0, sizes=(50,),
facecolors=facecolors,
edgecolors=("black",),
linewidths=(1,),
offsets=offsets,
transOffset=ax.transData,
)
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_numsides()[source]
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_rotation()[source]
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.StarPolygonCollection(numsides, rotation=0, sizes=(1,), **kwargs)[source]
Bases: matplotlib.collections.RegularPolyCollection Draw a collection of regular stars with numsides points. Parameters
numsidesint
The number of sides of the polygon.
rotationfloat
The rotation of the polygon in radians.
sizestuple of float
The area of the circle circumscribing the polygon in points^2. **kwargs
Forwarded to Collection. Examples See Lasso Demo for a complete example: offsets = np.random.rand(20, 2)
facecolors = [cm.jet(x) for x in np.random.rand(20)]
collection = RegularPolyCollection(
numsides=5, # a pentagon
rotation=0, sizes=(50,),
facecolors=facecolors,
edgecolors=("black",),
linewidths=(1,),
offsets=offsets,
transOffset=ax.transData,
)
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_numsides()[source]
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_rotation()[source]
get_sizes()[source]
Return the sizes ('areas') of the elements in the collection. Returns
array
The 'area' of each element.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sizes=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
picker None or bool or float or callable
pickradius float
rasterized bool
sizes ndarray or None
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sizes(sizes, dpi=72.0)[source]
Set the sizes of each member of the collection. Parameters
sizesndarray or None
The size to set for each element of the collection. The value is the 'area' of the element.
dpifloat, default: 72
The dpi of the canvas.
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0
classmatplotlib.collections.TriMesh(triangulation, **kwargs)[source]
Bases: matplotlib.collections.Collection Class for the efficient drawing of a triangular mesh using Gouraud shading. A triangular mesh is a Triangulation object. Parameters
edgecolorscolor or list of colors, default: rcParams["patch.edgecolor"] (default: 'black')
Edge color for each patch making up the collection. The special value 'face' can be passed to make the edgecolor match the facecolor.
facecolorscolor or list of colors, default: rcParams["patch.facecolor"] (default: 'C0')
Face color for each patch making up the collection.
linewidthsfloat or list of floats, default: rcParams["patch.linewidth"] (default: 1.0)
Line width for each patch making up the collection.
linestylesstr or tuple or list thereof, default: 'solid'
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink lengths in points. For examples, see Linestyles.
capstyleCapStyle-like, default: rcParams["patch.capstyle"]
Style to use for capping lines for all paths in the collection. Allowed values are {'butt', 'projecting', 'round'}.
joinstyleJoinStyle-like, default: rcParams["patch.joinstyle"]
Style to use for joining lines for all paths in the collection. Allowed values are {'miter', 'round', 'bevel'}.
antialiasedsbool or list of bool, default: rcParams["patch.antialiased"] (default: True)
Whether each patch in the collection should be drawn with antialiasing.
offsets(float, float) or list thereof, default: (0, 0)
A vector by which to translate each patch after rendering (default is no translation). The translation is performed in screen (pixel) coordinates (i.e. after the Artist's transform is applied).
transOffsetTransform, default: IdentityTransform
A single transform which will be applied to each offsets vector before it is used.
normNormalize, optional
Forwarded to ScalarMappable. The default of None means that the first draw call will set vmin and vmax using the minimum and maximum values of the data.
cmapColormap, optional
Forwarded to ScalarMappable. The default of None will result in rcParams["image.cmap"] (default: 'viridis') being used.
hatchstr, optional
Hatching pattern to use in filled paths, if any. Valid strings are ['/', '', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See Hatch style reference for the meaning of each hatch type.
pickradiusfloat, default: 5.0
If pickradius <= 0, then Collection.contains will return True whenever the test point is inside of one of the polygons formed by the control points of a Path in the Collection. On the other hand, if it is greater than 0, then we instead check if the test point is contained in a stroke of width 2*pickradius following any of the Paths in the Collection.
urlslist of str, default: None
A URL for each patch to link to once drawn. Currently only works for the SVG backend. See Hyperlinks for examples.
zorderfloat, default: 1
The drawing order, shared by all Patches in the Collection. See Zorder Demo for all defaults and examples. add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
autoscale()[source]
Autoscale the scalar limits on the norm instance using the current array
autoscale_None()[source]
Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None
propertyaxes
The Axes instance the artist resides in, or None.
propertycallbacksSM[source]
changed()[source]
Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.
colorbar
The last colorbar associated with this ScalarMappable. May be None.
contains(mouseevent)[source]
Test whether the mouse event occurred in the collection. Returns bool, dict(ind=itemlist), where every item in itemlist contains the event.
staticconvert_mesh_to_paths(tri)[source]
Convert a given mesh into a sequence of Path objects. This function is primarily of use to implementers of backends that do not directly support meshes.
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_array()[source]
Return the array of values, that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the array.
get_capstyle()[source]
get_children()[source]
Return a list of the child Artists of this Artist.
get_clim()[source]
Return the values (min, max) that are mapped to the colormap limits.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cmap()[source]
Return the Colormap instance.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_dashes()[source]
Alias for get_linestyle.
get_datalim(transData)[source]
get_ec()[source]
Alias for get_edgecolor.
get_edgecolor()[source]
get_edgecolors()[source]
Alias for get_edgecolor.
get_facecolor()[source]
get_facecolors()[source]
Alias for get_facecolor.
get_fc()[source]
Alias for get_facecolor.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_fill()[source]
Return whether face is colored.
get_gid()[source]
Return the group id.
get_hatch()[source]
Return the current hatching pattern.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_joinstyle()[source]
get_label()[source]
Return the label used for this artist in the legend.
get_linestyle()[source]
get_linestyles()[source]
Alias for get_linestyle.
get_linewidth()[source]
get_linewidths()[source]
Alias for get_linewidth.
get_ls()[source]
Alias for get_linestyle.
get_lw()[source]
Alias for get_linewidth.
get_offset_transform()[source]
Return the Transform instance used by this artist offset.
get_offsets()[source]
Return the offsets for the collection.
get_path_effects()[source]
get_paths()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_pickradius()[source]
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer)[source]
Like Artist.get_window_extent, but includes any clipping. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()) Returns
Bbox
The enclosing bounding box (in figure pixel coordinates).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_transforms()[source]
get_url()[source]
Return the url.
get_urls()[source]
Return a list of URLs, one for each element of the collection. The list contains None for elements without a URL. See Hyperlinks for an example.
get_visible()[source]
Return the visibility.
get_window_extent(renderer)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
propertynorm
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
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>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, norm=<UNSET>, offset_transform=<UNSET>, offsets=<UNSET>, path_effects=<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
alpha array-like or scalar or None
animated bool
antialiased or aa or antialiaseds bool or list of bools
array array-like or None
capstyle CapStyle or {'butt', 'projecting', 'round'}
clim (vmin: float, vmax: float)
clip_box Bbox
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 or ec or edgecolors color or list of colors or 'face'
facecolor or facecolors or fc color or list of colors
figure Figure
gid str
hatch {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
in_layout bool
joinstyle JoinStyle or {'miter', 'round', 'bevel'}
label object
linestyle or dashes or linestyles or ls str or tuple or list thereof
linewidth or linewidths or lw float or list of floats
norm Normalize or None
offset_transform Transform
offsets (N, 2) or (2,) array-like
path_effects AbstractPathEffect
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
set_aa(aa)[source]
Alias for set_antialiased.
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphaarray-like or scalar or None
All values must be within the 0-1 range, inclusive. Masked values and nans are not supported.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_antialiased(aa)[source]
Set the antialiasing state for rendering. Parameters
aabool or list of bools
set_antialiaseds(aa)[source]
Alias for set_antialiased.
set_array(A)[source]
Set the value array from array-like A. Parameters
Aarray-like or None
The values that are mapped to colors. The base class ScalarMappable does not make any assumptions on the dimensionality and shape of the value array A.
set_capstyle(cs)[source]
Set the CapStyle for the collection (for all its elements). Parameters
csCapStyle or {'butt', 'projecting', 'round'}
set_clim(vmin=None, vmax=None)[source]
Set the norm limits for image scaling. Parameters
vmin, vmaxfloat
The limits. The limits may also be passed as a tuple (vmin, vmax) as a single positional argument.
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_cmap(cmap)[source]
Set the colormap for luminance data. Parameters
cmapColormap or str or None
set_color(c)[source]
Set both the edgecolor and the facecolor. Parameters
ccolor or list of rgba tuples
See also
Collection.set_facecolor, Collection.set_edgecolor
For setting the edge or face color individually.
set_dashes(ls)[source]
Alias for set_linestyle.
set_ec(c)[source]
Alias for set_edgecolor.
set_edgecolor(c)[source]
Set the edgecolor(s) of the collection. Parameters
ccolor or list of colors or 'face'
The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor.
set_edgecolors(c)[source]
Alias for set_edgecolor.
set_facecolor(c)[source]
Set the facecolor(s) of the collection. c can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is 'none', the patch will not be filled. Parameters
ccolor or list of colors
set_facecolors(c)[source]
Alias for set_facecolor.
set_fc(c)[source]
Alias for set_facecolor.
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_hatch(hatch)[source]
Set the hatching pattern hatch can be one of: / - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters
hatch{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_joinstyle(js)[source]
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'}
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linestyle(ls)[source]
Set the linestyle(s) for the collection.
linestyle description
'-' or 'solid' solid line
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dotted line
':' or 'dotted' dotted line Alternatively a dash tuple of the following form can be provided: (offset, onoffseq),
where onoffseq is an even length tuple of on and off ink in points. Parameters
lsstr or tuple or list thereof
Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See Line2D.set_linestyle for a complete description.
set_linestyles(ls)[source]
Alias for set_linestyle.
set_linewidth(lw)[source]
Set the linewidth(s) for the collection. lw can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters
lwfloat or list of floats
set_linewidths(lw)[source]
Alias for set_linewidth.
set_ls(ls)[source]
Alias for set_linestyle.
set_lw(lw)[source]
Alias for set_linewidth.
set_norm(norm)[source]
Set the normalization instance. Parameters
normNormalize or None
Notes If there are any colorbars using the mappable for this norm, setting the norm of the mappable will reset the norm, locator, and formatters on the colorbar to default.
set_offset_transform(transOffset)[source]
Set the artist offset transform. Parameters
transOffsetTransform
set_offsets(offsets)[source]
Set the offsets for the collection. Parameters
offsets(N, 2) or (2,) array-like
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_paths()[source]
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_pickradius(pr)[source]
Set the pick radius used for containment tests. Parameters
prfloat
Pick radius, in points.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_urls(urls)[source]
Parameters
urlslist of str or None
Notes URLs are currently only implemented by the SVG backend. They are ignored by all other backends.
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
to_rgba(x, alpha=None, bytes=False, norm=True)[source]
Return a normalized rgba array corresponding to x. In the normal case, x is a 1D or 2D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable. There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If x is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the alpha kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the alpha kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4. In either case, if bytes is False (default), the rgba array will be floats in the 0-1 range; if it is True, the returned rgba array will be uint8 in the 0 to 255 range. If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
update_scalarmappable()[source]
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate.
zorder=0 | |
doc_29711 |
Return an array (ndim >= 1) laid out in Fortran order in memory. Parameters
aarray_like
Input array.
dtypestr or dtype object, optional
By default, the data-type is inferred from the input data.
likearray_like
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns
outndarray
The input a in Fortran, or column-major, order. See also ascontiguousarray
Convert input to a contiguous (C order) array. asanyarray
Convert input to an ndarray with either row or column-major memory order. require
Return an ndarray that satisfies requirements. ndarray.flags
Information about the memory layout of the array. Examples >>> x = np.arange(6).reshape(2,3)
>>> y = np.asfortranarray(x)
>>> x.flags['F_CONTIGUOUS']
False
>>> y.flags['F_CONTIGUOUS']
True
Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays. | |
doc_29712 | Returns a SpatialReference object corresponding to the SRID of the geometry or None. | |
doc_29713 |
This is the quantized version of LayerNorm. Additional args:
scale - quantization scale of the output, type: double.
zero_point - quantization zero point of the output, type: long. | |
doc_29714 | This is a standard context defined by the General Decimal Arithmetic Specification. Precision is set to nine. Rounding is set to ROUND_HALF_EVEN. All flags are cleared. No traps are enabled (so that exceptions are not raised during computations). Because the traps are disabled, this context is useful for applications that prefer to have result value of NaN or Infinity instead of raising exceptions. This allows an application to complete a run in the presence of conditions that would otherwise halt the program. | |
doc_29715 |
Encode character string in the Series/Index using indicated encoding. Equivalent to str.encode(). Parameters
encoding:str
errors:str, optional
Returns
encoded:Series/Index of objects | |
doc_29716 |
Create a 3D contour plot. Note This method currently produces incorrect output due to a longstanding bug in 3D PolyCollection rendering. Parameters
X, Y, Zarray-like
Input data. See tricontour for acceptable data shapes.
extend3dbool, default: False
Whether to extend contour in 3D.
strideint
Step size for extending contour.
zdir{'x', 'y', 'z'}, default: 'z'
The direction to use.
offsetfloat, optional
If specified, plot a projection of the contour lines at this position in a plane normal to zdir.
dataindexable object, optional
If given, all parameters also accept a string s, which is interpreted as data[s] (unless this raises an exception). *args, **kwargs
Other arguments are forwarded to matplotlib.axes.Axes.tricontour. Returns
matplotlib.tri.tricontour.TriContourSet | |
doc_29717 | CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol. ISO-TP constants, documented in the Linux documentation. Availability: Linux >= 2.6.25. New in version 3.7. | |
doc_29718 | If tzinfo is None, returns None, else returns self.tzinfo.tzname(None), or raises an exception if the latter doesn’t return None or a string object. | |
doc_29719 | Base class which can be inherited by SAX parsers. | |
doc_29720 |
Casts all floating point parameters and buffers to half datatype. Returns
self Return type
Module | |
doc_29721 | Make the response conditional to the request. This method works best if an etag was defined for the response already. The add_etag method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is anything but GET or HEAD. For optimal performance when handling range requests, it’s recommended that your response data object implements seekable, seek and tell methods as described by io.IOBase. Objects returned by wrap_file() automatically implement those methods. It does not remove the body of the response because that’s something the __call__() function does for us automatically. Returns self so that you can do return resp.make_conditional(req) but modifies the object in-place. Parameters
request_or_environ (WSGIEnvironment) – a request object or WSGI environment to be used to make the response conditional against.
accept_ranges (Union[bool, str]) – This parameter dictates the value of Accept-Ranges header. If False (default), the header is not set. If True, it will be set to "bytes". If None, it will be set to "none". If it’s a string, it will use this value.
complete_length (Optional[int]) – Will be used only in valid Range Requests. It will set Content-Range complete length value and compute Content-Length real value. This parameter is mandatory for successful Range Requests completion. Raises
RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied. Return type
Response Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error. | |
doc_29722 | tf.experimental.numpy.arctan(
x
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.arctan. | |
doc_29723 | This flag can be OR’ed with any other scheduling policy. When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default. | |
doc_29724 |
This is the quantized version of InstanceNorm1d. Additional args:
scale - quantization scale of the output, type: double.
zero_point - quantization zero point of the output, type: long. | |
doc_29725 |
Call predict_proba on the estimator with the best found parameters. Only available if refit=True and the underlying estimator supports predict_proba. Parameters
Xindexable, length n_samples
Must fulfill the input assumptions of the underlying estimator. | |
doc_29726 | Creates a text iterator. The iterator loops over this element and all subelements, in document order, and returns all inner text. New in version 3.2. | |
doc_29727 | temporarily set which modifier keys are pressed set_mods(int) -> None Create a bitmask of the modifier key constants you want to impose on your program. | |
doc_29728 | Returns an fp32 Tensor by dequantizing a quantized Tensor Parameters
tensor (Tensor) – A quantized Tensor
torch.dequantize(tensors) → sequence of Tensors
Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors Parameters
tensors (sequence of Tensors) – A list of quantized Tensors | |
doc_29729 | Create an archive file (such as zip or tar) and return its name. base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the zlib module is available), “tar”, “gztar” (if the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma module is available). root_dir is a directory that will be the root directory of the archive, all paths in the archive will be relative to it; for example, we typically chdir into root_dir before creating the archive. base_dir is the directory where we start archiving from; i.e. base_dir will be the common prefix of all files and directories in the archive. base_dir must be given relative to root_dir. See Archiving example with base_dir for how to use base_dir and root_dir together. root_dir and base_dir both default to the current directory. If dry_run is true, no archive is created, but the operations that would be executed are logged to logger. owner and group are used when creating a tar archive. By default, uses the current owner and group. logger must be an object compatible with PEP 282, usually an instance of logging.Logger. The verbose argument is unused and deprecated. Raises an auditing event shutil.make_archive with arguments base_name, format, root_dir, base_dir. Changed in version 3.8: The modern pax (POSIX.1-2001) format is now used instead of the legacy GNU format for archives created with format="tar". | |
doc_29730 |
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. May return None if no sketch parameters were set. | |
doc_29731 |
Roll provided date backward to next offset only if not on offset. Returns
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp. | |
doc_29732 |
Get this Axis' tick labels. Parameters
minorbool
Whether to return the minor or the major ticklabels.
whichNone, ('minor', 'major', 'both')
Overrides minor. Selects which ticklabels to return Returns
list of Text
Notes The tick label strings are not populated until a draw method has been called. See also: draw and draw.
Examples using matplotlib.axis.Axis.get_ticklabels
Image Masked
Fig Axes Customize Simple
Artist tutorial | |
doc_29733 |
Convert hsv values to rgb. Parameters
hsv(..., 3) array-like
All values assumed to be in range [0, 1] Returns
(..., 3) ndarray
Colors converted to RGB values in range [0, 1]
Examples using matplotlib.colors.hsv_to_rgb
3D voxel / volumetric plot with cylindrical coordinates | |
doc_29734 |
Add multiple tools to the container. Parameters
containerContainer
backend_bases.ToolContainerBase object that will get the tools added.
toolslist, optional
List in the form [[group1, [tool1, tool2 ...]], [group2, [...]]] where the tools [tool1, tool2, ...] will display in group1. See add_tool for details. | |
doc_29735 | If set, a new dict will be created for the frame’s f_locals when the code object is executed. | |
doc_29736 | A tuple of integers the length of ndim giving the size in bytes to access each element for each dimension of the array. Changed in version 3.3: An empty tuple instead of None when ndim = 0. | |
doc_29737 | The headers received with the request. | |
doc_29738 |
Parameters
fpsint, default: 5
Movie frame rate (per second).
codecstr or None, default: rcParams["animation.codec"] (default: 'h264')
The codec to use.
bitrateint, default: rcParams["animation.bitrate"] (default: -1)
The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
extra_argslist of str or None, optional
Extra command-line arguments passed to the underlying movie encoder. The default, None, means to use rcParams["animation.[name-of-encoder]_args"] for the builtin writers.
metadatadict[str, str], default: {}
A dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment. | |
doc_29739 | Accept: application/json
Might receive an error response indicating that the DELETE method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 42
{"detail": "Method 'DELETE' not allowed."}
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY setting. An example validation error might look like this: HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 94
{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
Custom exception handling You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 62
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
In order to alter the style of the response, you could write the following custom exception handler: from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response
The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view']. The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER setting key. For example: REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
If not specified, the 'EXCEPTION_HANDLER' setting defaults to the standard exception handler provided by REST framework: REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails. API Reference APIException Signature: APIException() The base class for all exceptions raised inside an APIView class or @api_view. To provide a custom exception, subclass APIException and set the .status_code, .default_detail, and default_code attributes on the class. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so: from rest_framework.exceptions import APIException
class ServiceUnavailable(APIException):
status_code = 503
default_detail = 'Service temporarily unavailable, try again later.'
default_code = 'service_unavailable'
Inspecting API exceptions There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project. The available attributes and methods are:
.detail - Return the textual description of the error.
.get_codes() - Return the code identifier of the error.
.get_full_details() - Return both the textual description and the code identifier. In most cases the error detail will be a simple item: >>> print(exc.detail)
You do not have permission to perform this action.
>>> print(exc.get_codes())
permission_denied
>>> print(exc.get_full_details())
{'message':'You do not have permission to perform this action.','code':'permission_denied'}
In the case of validation errors the error detail will be either a list or dictionary of items: >>> print(exc.detail)
{"name":"This field is required.","age":"A valid integer is required."}
>>> print(exc.get_codes())
{"name":"required","age":"invalid"}
>>> print(exc.get_full_details())
{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
ParseError Signature: ParseError(detail=None, code=None) Raised if the request contains malformed data when accessing request.data. By default this exception results in a response with the HTTP status code "400 Bad Request". AuthenticationFailed Signature: AuthenticationFailed(detail=None, code=None) Raised when an incoming request includes incorrect authentication. By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details. NotAuthenticated Signature: NotAuthenticated(detail=None, code=None) Raised when an unauthenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details. PermissionDenied Signature: PermissionDenied(detail=None, code=None) Raised when an authenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "403 Forbidden". NotFound Signature: NotFound(detail=None, code=None) Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404 Django exception. By default this exception results in a response with the HTTP status code "404 Not Found". MethodNotAllowed Signature: MethodNotAllowed(method, detail=None, code=None) Raised when an incoming request occurs that does not map to a handler method on the view. By default this exception results in a response with the HTTP status code "405 Method Not Allowed". NotAcceptable Signature: NotAcceptable(detail=None, code=None) Raised when an incoming request occurs with an Accept header that cannot be satisfied by any of the available renderers. By default this exception results in a response with the HTTP status code "406 Not Acceptable". UnsupportedMediaType Signature: UnsupportedMediaType(media_type, detail=None, code=None) Raised if there are no parsers that can handle the content type of the request data when accessing request.data. By default this exception results in a response with the HTTP status code "415 Unsupported Media Type". Throttled Signature: Throttled(wait=None, detail=None, code=None) Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code "429 Too Many Requests". ValidationError Signature: ValidationError(detail, code=None) The ValidationError exception is slightly different from the other APIException classes: The detail argument is mandatory, not optional. The detail argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the validate() method of a serializer. For example. raise serializers.ValidationError({'name': 'Please enter a valid name.'})
By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.')
The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument: serializer.is_valid(raise_exception=True)
The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code "400 Bad Request". Generic Error Views Django REST Framework provides two error views suitable for providing generic JSON 500 Server Error and 400 Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an API-only application.) Use these as per Django's Customizing error views documentation. rest_framework.exceptions.server_error Returns a response with status code 500 and application/json content type. Set as handler500: handler500 = 'rest_framework.exceptions.server_error'
rest_framework.exceptions.bad_request Returns a response with status code 400 and application/json content type. Set as handler400: handler400 = 'rest_framework.exceptions.bad_request'
exceptions.py | |
doc_29740 | Moves all model parameters and buffers to the XPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized. Parameters
device (int, optional) – if specified, all parameters will be copied to that device Returns
self Return type
Module | |
doc_29741 |
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
alpha scalar or None
animated bool
annotation_clip bool or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
figure unknown
fontsize unknown
gid str
in_layout bool
label object
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float | |
doc_29742 | Defines the type of class returned by the get_lookup() method. It must be a Field instance. | |
doc_29743 | Equivalent to KEY_READ. | |
doc_29744 | The prefix that the application is mounted under, without a trailing slash. path comes after this. | |
doc_29745 | Concatenate the tokens of the list split_command and return a string. This function is the inverse of split(). >>> from shlex import join
>>> print(join(['echo', '-n', 'Multiple words']))
echo -n 'Multiple words'
The returned value is shell-escaped to protect against injection vulnerabilities (see quote()). New in version 3.8. | |
doc_29746 |
Initialize self. See help(type(self)) for accurate signature. | |
doc_29747 |
Motion blurred clock. This photograph of a wall clock was taken while moving the camera in an aproximately horizontal direction. It may be used to illustrate inverse filters and deconvolution. Released into the public domain by the photographer (Stefan van der Walt). Returns
clock(300, 400) uint8 ndarray
Clock image. | |
doc_29748 |
Move ticks and ticklabels (if present) to the top of the axes.
Examples using matplotlib.axis.XAxis.tick_top
Broken Axis
Title positioning | |
doc_29749 | tf.experimental.numpy.ceil(
x
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.ceil. | |
doc_29750 |
Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate. | |
doc_29751 | tf.experimental.numpy.hypot(
x1, x2
)
Unsupported arguments: out, where, casting, order, dtype, subok, signature, extobj. See the NumPy documentation for numpy.hypot. | |
doc_29752 | Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute probability set to True. Parameters
Xarray-like of shape (n_samples, n_features)
For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train). Returns
Tndarray of shape (n_samples, n_classes)
Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_. Notes The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets. | |
doc_29753 |
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called. | |
doc_29754 |
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 | |
doc_29755 |
Set the antialiasing state for rendering. Parameters
aabool or list of bools | |
doc_29756 | See Migration guide for more details. tf.compat.v1.debugging.assert_negative
tf.compat.v1.assert_negative(
x, data=None, summarize=None, message=None, name=None
)
When running in graph mode, you should add a dependency on this operation to ensure that it runs. Example of adding a dependency to an operation: with tf.control_dependencies([tf.debugging.assert_negative(x, y)]):
output = tf.reduce_sum(x)
Negative means, for every element x[i] of x, we have x[i] < 0. If x is empty this is trivially satisfied.
Args
x Numeric Tensor.
data The tensors to print out if the condition is False. Defaults to error message and first few entries of x.
summarize Print this many entries of each tensor.
message A string to prefix to the default message.
name A name for this operation (optional). Defaults to "assert_negative".
Returns Op that raises InvalidArgumentError if x < 0 is False.
Raises
InvalidArgumentError if the check can be performed immediately and x < 0 is False. The check can be performed immediately during eager execution or if x is statically known. Eager Compatibility returns None | |
doc_29757 | See Migration guide for more details. tf.compat.v1.clip_by_value
tf.clip_by_value(
t, clip_value_min, clip_value_max, name=None
)
Given a tensor t, this operation returns a tensor of the same type and shape as t with its values clipped to clip_value_min and clip_value_max. Any values less than clip_value_min are set to clip_value_min. Any values greater than clip_value_max are set to clip_value_max.
Note: clip_value_min needs to be smaller or equal to clip_value_max for correct results.
For example: Basic usage passes a scalar as the min and max value.
t = tf.constant([[-10., -1., 0.], [0., 2., 10.]])
t2 = tf.clip_by_value(t, clip_value_min=-1, clip_value_max=1)
t2.numpy()
array([[-1., -1., 0.],
[ 0., 1., 1.]], dtype=float32)
The min and max can be the same size as t, or broadcastable to that size.
t = tf.constant([[-1, 0., 10.], [-1, 0, 10]])
clip_min = [[2],[1]]
t3 = tf.clip_by_value(t, clip_value_min=clip_min, clip_value_max=100)
t3.numpy()
array([[ 2., 2., 10.],
[ 1., 1., 10.]], dtype=float32)
Broadcasting fails, intentionally, if you would expand the dimensions of t
t = tf.constant([[-1, 0., 10.], [-1, 0, 10]])
clip_min = [[[2, 1]]] # Has a third axis
t4 = tf.clip_by_value(t, clip_value_min=clip_min, clip_value_max=100)
Traceback (most recent call last):
InvalidArgumentError: Incompatible shapes: [2,3] vs. [1,1,2]
It throws a TypeError if you try to clip an int to a float value (tf.cast the input to float first).
t = tf.constant([[1, 2], [3, 4]], dtype=tf.int32)
t5 = tf.clip_by_value(t, clip_value_min=-3.1, clip_value_max=3.1)
Traceback (most recent call last):
TypeError: Cannot convert ...
Args
t A Tensor or IndexedSlices.
clip_value_min The minimum value to clip to. A scalar Tensor or one that is broadcastable to the shape of t.
clip_value_max The maximum value to clip to. A scalar Tensor or one that is broadcastable to the shape of t.
name A name for the operation (optional).
Returns A clipped Tensor or IndexedSlices.
Raises tf.errors.InvalidArgumentError: If the clip tensors would trigger array broadcasting that would make the returned tensor larger than the input. TypeError If dtype of the input is int32 and dtype of the clip_value_min or clip_value_max is float32 | |
doc_29758 | class sklearn.ensemble.BaggingRegressor(base_estimator=None, n_estimators=10, *, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0) [source]
A Bagging regressor. A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide. New in version 0.15. Parameters
base_estimatorobject, default=None
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeRegressor.
n_estimatorsint, default=10
The number of base estimators in the ensemble.
max_samplesint or float, default=1.0
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details). If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples.
max_featuresint or float, default=1.0
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details). If int, then draw max_features features. If float, then draw max_features * X.shape[1] features.
bootstrapbool, default=True
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
bootstrap_featuresbool, default=False
Whether features are drawn with replacement.
oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization error.
warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new ensemble. See the Glossary.
n_jobsint, default=None
The number of jobs to run in parallel for both fit and predict. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance or None, default=None
Controls the random resampling of the original dataset (sample wise and feature wise). If the base estimator accepts a random_state attribute, a different seed is generated for each instance in the ensemble. Pass an int for reproducible output across multiple function calls. See Glossary.
verboseint, default=0
Controls the verbosity when fitting and predicting. Attributes
base_estimator_estimator
The base estimator from which the ensemble is grown.
n_features_int
The number of features when fit is performed.
estimators_list of estimators
The collection of fitted sub-estimators.
estimators_samples_list of arrays
The subset of drawn samples for each base estimator.
estimators_features_list of arrays
The subset of drawn features for each base estimator.
oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
oob_prediction_ndarray of shape (n_samples,)
Prediction computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_prediction_ might contain NaN. This attribute exists only when oob_score is True. References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012. Examples >>> from sklearn.svm import SVR
>>> from sklearn.ensemble import BaggingRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_samples=100, n_features=4,
... n_informative=2, n_targets=1,
... random_state=0, shuffle=False)
>>> regr = BaggingRegressor(base_estimator=SVR(),
... n_estimators=10, random_state=0).fit(X, y)
>>> regr.predict([[0, 0, 0, 0]])
array([-2.8720...])
Methods
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression target for X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
property estimators_samples_
The subset of drawn samples for each base estimator. Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples. Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.
fit(X, y, sample_weight=None) [source]
Build a Bagging ensemble of estimators from the training
set (X, y). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting. Returns
selfobject
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
predict(X) [source]
Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns
yndarray of shape (n_samples,)
The predicted values.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance.
Examples using sklearn.ensemble.BaggingRegressor
Single estimator versus bagging: bias-variance decomposition | |
doc_29759 |
Bases: matplotlib.dates.DateLocator On autoscale, this class picks the best DateLocator to set the view limits and the tick locations. Attributes
intervalddict
Mapping of tick frequencies to multiples allowed for that ticking. The default is self.intervald = {
YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
1000, 2000, 4000, 5000, 10000],
MONTHLY : [1, 2, 3, 4, 6],
DAILY : [1, 2, 3, 7, 14, 21],
HOURLY : [1, 2, 3, 4, 6, 12],
MINUTELY: [1, 5, 10, 15, 30],
SECONDLY: [1, 5, 10, 15, 30],
MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500,
1000, 2000, 5000, 10000, 20000, 50000,
100000, 200000, 500000, 1000000],
}
where the keys are defined in dateutil.rrule. The interval is used to specify multiples that are appropriate for the frequency of ticking. For instance, every 7 days is sensible for daily ticks, but for minutes/seconds, 15 or 30 make sense. When customizing, you should only modify the values for the existing keys. You should not add or delete entries. Example for forcing ticks every 3 hours: locator = AutoDateLocator()
locator.intervald[HOURLY] = [3] # only show every 3 hours
Parameters
tzdatetime.tzinfo
Ticks timezone.
minticksint
The minimum number of ticks desired; controls whether ticks occur yearly, monthly, etc.
maxticksint
The maximum number of ticks desired; controls the interval between ticks (ticking every other, every 3, etc.). For fine-grained control, this can be a dictionary mapping individual rrule frequency constants (YEARLY, MONTHLY, etc.) to their own maximum number of ticks. This can be used to keep the number of ticks appropriate to the format chosen in AutoDateFormatter. Any frequency not specified in this dictionary is given a default value.
interval_multiplesbool, default: True
Whether ticks should be chosen to be multiple of the interval, locking them to 'nicer' locations. For example, this will force the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done at 6 hour intervals. get_locator(dmin, dmax)[source]
Pick the best locator based on a distance.
nonsingular(vmin, vmax)[source]
Given the proposed upper and lower extent, adjust the range if it is too close to being singular (i.e. a range of ~0).
tick_values(vmin, vmax)[source]
Return the values of the located ticks given vmin and vmax. Note To get tick locations with the vmin and vmax values defined automatically for the associated axis simply call the Locator instance: >>> print(type(loc))
<type 'Locator'>
>>> print(loc())
[1, 2, 3, 4] | |
doc_29760 |
Return True if any value in the group is truthful, else False. Parameters
skipna:bool, default True
Flag to ignore nan values during truth testing. Returns
Series or DataFrame
DataFrame or Series of boolean values, where a value is True if any element is True within its respective group, False otherwise. See also Series.groupby
Apply a function groupby to a Series. DataFrame.groupby
Apply a function groupby to each row or column of a DataFrame. | |
doc_29761 | This module contains table contents for the standard sequence tables: AdminExecuteSequence, AdminUISequence, AdvtExecuteSequence, InstallExecuteSequence, and InstallUISequence. | |
doc_29762 | Return True if the Python interpreter is shutting down, False otherwise. New in version 3.5. | |
doc_29763 |
The masked constant is a special case of MaskedArray, with a float datatype and a null shape. It is used to test whether a specific entry of a masked array is masked, or to mask one or several entries of a masked array: >>> x = ma.array([1, 2, 3], mask=[0, 1, 0])
>>> x[1] is ma.masked
True
>>> x[-1] = ma.masked
>>> x
masked_array(data=[1, --, --],
mask=[False, True, True],
fill_value=999999)
numpy.ma.nomask
Value indicating that a masked array has no invalid entry. nomask is used internally to speed up computations when the mask is not needed. It is represented internally as np.False_.
numpy.ma.masked_print_options
String used in lieu of missing data when a masked array is printed. By default, this string is '--'. | |
doc_29764 |
Disconnect events. | |
doc_29765 |
Return repr(self). | |
doc_29766 | See Migration guide for more details. tf.compat.v1.data.experimental.group_by_window
tf.data.experimental.group_by_window(
key_func, reduce_func, window_size=None, window_size_func=None
)
This transformation maps each consecutive element in a dataset to a key using key_func and groups the elements by key. It then applies reduce_func to at most window_size_func(key) elements matching the same key. All except the final window for each key will contain window_size_func(key) elements; the final window may be smaller. You may provide either a constant window_size or a window size determined by the key through window_size_func.
Args
key_func A function mapping a nested structure of tensors (having shapes and types defined by self.output_shapes and self.output_types) to a scalar tf.int64 tensor.
reduce_func A function mapping a key and a dataset of up to window_size consecutive elements matching that key to another dataset.
window_size A tf.int64 scalar tf.Tensor, representing the number of consecutive elements matching the same key to combine in a single batch, which will be passed to reduce_func. Mutually exclusive with window_size_func.
window_size_func A function mapping a key to a tf.int64 scalar tf.Tensor, representing the number of consecutive elements matching the same key to combine in a single batch, which will be passed to reduce_func. Mutually exclusive with window_size.
Returns A Dataset transformation function, which can be passed to tf.data.Dataset.apply.
Raises
ValueError if neither or both of {window_size, window_size_func} are passed. | |
doc_29767 |
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool | |
doc_29768 | Change the hardware gamma ramps with a custom lookup set_gamma_ramp(red, green, blue) -> bool Set the red, green, and blue gamma ramps with an explicit lookup table. Each argument should be sequence of 256 integers. The integers should range between 0 and 0xffff. Not all systems and hardware support gamma ramps, if the function succeeds it will return True. | |
doc_29769 |
Set the JoinStyle for the collection (for all its elements). Parameters
jsJoinStyle or {'miter', 'round', 'bevel'} | |
doc_29770 | See Migration guide for more details. tf.compat.v1.raw_ops.Expm1
tf.raw_ops.Expm1(
x, name=None
)
i.e. exp(x) - 1 or e^(x) - 1, where x is the input tensor. e denotes Euler's number and is approximately equal to 2.718281. x = tf.constant(2.0)
tf.math.expm1(x) ==> 6.389056
x = tf.constant([2.0, 8.0])
tf.math.expm1(x) ==> array([6.389056, 2979.958], dtype=float32)
x = tf.constant(1 + 1j)
tf.math.expm1(x) ==> (0.46869393991588515+2.2873552871788423j)
Args
x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, complex64, complex128.
name A name for the operation (optional).
Returns A Tensor. Has the same type as x. | |
doc_29771 |
Set the lower value of the slider to max. Parameters
maxfloat | |
doc_29772 |
Set the animated state of the handles artist. | |
doc_29773 |
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array. | |
doc_29774 | See Migration guide for more details. tf.compat.v1.raw_ops.ResourceApplyAdagradV2
tf.raw_ops.ResourceApplyAdagradV2(
var, accum, lr, epsilon, grad, use_locking=False, update_slots=True, name=None
)
accum += grad * grad var -= lr * grad * (1 / (sqrt(accum) + epsilon))
Args
var A Tensor of type resource. Should be from a Variable().
accum A Tensor of type resource. Should be from a Variable().
lr A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. Scaling factor. Must be a scalar.
epsilon A Tensor. Must have the same type as lr. Constant factor. Must be a scalar.
grad A Tensor. Must have the same type as lr. The gradient.
use_locking An optional bool. Defaults to False. If True, updating of the var and accum tensors will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention.
update_slots An optional bool. Defaults to True.
name A name for the operation (optional).
Returns The created Operation. | |
doc_29775 |
Restore the original view. For convenience of being directly connected as a GUI callback, which often get passed additional parameters, this method accepts arbitrary parameters, but does not use them. | |
doc_29776 | A subclass of ConnectionError, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno EPIPE and ESHUTDOWN. | |
doc_29777 | The Font class represents a named font. Font instances are given unique names and can be specified by their family, size, and style configuration. Named fonts are Tk’s method of creating and identifying fonts as a single object, rather than specifying a font by its attributes with each occurrence. arguments: additional keyword options (ignored if font is specified):
actual(option=None, displayof=None)
Return the attributes of the font.
cget(option)
Retrieve an attribute of the font.
config(**options)
Modify attributes of the font.
copy()
Return new instance of the current font.
measure(text, displayof=None)
Return amount of space the text would occupy on the specified display when formatted in the current font. If no display is specified then the main application window is assumed.
metrics(*options, **kw)
Return font-specific data. Options include:
ascent - distance between baseline and highest point that a
character of the font can occupy
descent - distance between baseline and lowest point that a
character of the font can occupy
linespace - minimum vertical separation necessary between any two
characters of the font that ensures no vertical overlap between lines. fixed - 1 if font is fixed-width else 0 | |
doc_29778 | tf.compat.v1.train.generate_checkpoint_state_proto(
save_dir, model_checkpoint_path, all_model_checkpoint_paths=None,
all_model_checkpoint_timestamps=None, last_preserved_timestamp=None
)
Args
save_dir Directory where the model was saved.
model_checkpoint_path The checkpoint file.
all_model_checkpoint_paths List of strings. Paths to all not-yet-deleted checkpoints, sorted from oldest to newest. If this is a non-empty list, the last element must be equal to model_checkpoint_path. These paths are also saved in the CheckpointState proto.
all_model_checkpoint_timestamps A list of floats, indicating the number of seconds since the Epoch when each checkpoint was generated.
last_preserved_timestamp A float, indicating the number of seconds since the Epoch when the last preserved checkpoint was written, e.g. due to a keep_checkpoint_every_n_hours parameter (see tf.train.CheckpointManager for an implementation).
Returns CheckpointState proto with model_checkpoint_path and all_model_checkpoint_paths updated to either absolute paths or relative paths to the current save_dir.
Raises
ValueError If all_model_checkpoint_timestamps was provided but its length does not match all_model_checkpoint_paths. | |
doc_29779 | A bytes object that contains any data that was not consumed by the last decompress() call because it exceeded the limit for the uncompressed data buffer. This data has not yet been seen by the zlib machinery, so you must feed it (possibly with further data concatenated to it) back to a subsequent decompress() method call in order to get correct output. | |
doc_29780 |
Roll provided date backward to next offset only if not on offset. Returns
TimeStamp
Rolled timestamp if not on offset, otherwise unchanged timestamp. | |
doc_29781 | The same as imap() except that the ordering of the results from the returned iterator should be considered arbitrary. (Only when there is only one worker process is the order guaranteed to be “correct”.) | |
doc_29782 | test if a type of event is blocked from the queue get_blocked(type) -> bool get_blocked(typelist) -> bool Returns True if the given event type is blocked from the queue. If a sequence of event types is passed, this will return True if any of those event types are blocked. | |
doc_29783 |
Return the AxisInfo for unit. unit is a tzinfo instance or None. The axis argument is required but not used. | |
doc_29784 | 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100
}
Note that you need to set both the pagination class, and the page size that should be used. Both DEFAULT_PAGINATION_CLASS and PAGE_SIZE are None by default. You can also set the pagination class on an individual view by using the pagination_class attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis. Modifying the pagination style If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 10000
class StandardResultsSetPagination(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 1000
You can then apply your new style to a view using the pagination_class attribute: class BillingRecordsView(generics.ListAPIView):
queryset = Billing.objects.all()
serializer_class = BillingRecordsSerializer
pagination_class = LargeResultsSetPagination
Or apply the style globally, using the DEFAULT_PAGINATION_CLASS settings key. For example: REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'
}
API Reference PageNumberPagination This pagination style accepts a single number page number in the request query parameters. Request: GET https://api.example.org/accounts/?page=4
Response: HTTP 200 OK
{
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
…
]
}
Setup To enable the PageNumberPagination style globally, use the following configuration, and set the PAGE_SIZE as desired: REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100
}
On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis. Configuration The PageNumberPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the PageNumberPagination class, and then enable your custom pagination class as above.
django_paginator_class - The Django Paginator class to use. Default is django.core.paginator.Paginator, which should be fine for most use cases.
page_size - A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key.
page_query_param - A string value indicating the name of the query parameter to use for the pagination control.
page_size_query_param - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to None, indicating that the client may not control the requested page size.
max_page_size - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if page_size_query_param is also set.
last_page_strings - A list or tuple of string values indicating values that may be used with the page_query_param to request the final page in the set. Defaults to ('last',)
template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to "rest_framework/pagination/numbers.html". LimitOffsetPagination This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an "offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. Request: GET https://api.example.org/accounts/?limit=100&offset=400
Response: HTTP 200 OK
{
"count": 1023
"next": "https://api.example.org/accounts/?limit=100&offset=500",
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
"results": [
…
]
}
Setup To enable the LimitOffsetPagination style globally, use the following configuration: REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
}
Optionally, you may also set a PAGE_SIZE key. If the PAGE_SIZE parameter is also used then the limit query parameter will be optional, and may be omitted by the client. On GenericAPIView subclasses you may also set the pagination_class attribute to select LimitOffsetPagination on a per-view basis. Configuration The LimitOffsetPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the LimitOffsetPagination class, and then enable your custom pagination class as above.
default_limit - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the PAGE_SIZE settings key.
limit_query_param - A string value indicating the name of the "limit" query parameter. Defaults to 'limit'.
offset_query_param - A string value indicating the name of the "offset" query parameter. Defaults to 'offset'.
max_limit - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to None.
template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to "rest_framework/pagination/numbers.html". CursorPagination The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: Provides a consistent pagination view. When used properly CursorPagination ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. Details and limitations Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by "-created". This assumes that there must be a 'created' timestamp field on the model instances, and will present a "timeline" style paginated view, with the most recently added items first. You can modify the ordering by overriding the 'ordering' attribute on the pagination class, or by using the OrderingFilter filter class together with CursorPagination. When used with OrderingFilter you should strongly consider restricting the fields that the user may order by. Proper usage of cursor pagination should have an ordering field that satisfies the following: Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. Should be a non-nullable value that can be coerced to a string. Should not be a float. Precision errors easily lead to incorrect results. Hint: use decimals instead. (If you already have a float field and must paginate on that, an example CursorPagination subclass that uses decimals to limit precision is available here.) The field should have a database index. Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the "Building cursors for the Disqus API" blog post gives a good overview of the basic approach. Setup To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
'PAGE_SIZE': 100
}
On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis. Configuration The CursorPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the CursorPagination class, and then enable your custom pagination class as above.
page_size = A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key.
cursor_query_param = A string value indicating the name of the "cursor" query parameter. Defaults to 'cursor'.
ordering = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: ordering = 'slug'. Defaults to -created. This value may also be overridden by using OrderingFilter on the view.
template = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to "rest_framework/pagination/previous_and_next.html". Custom pagination styles To create a custom pagination serializer class, you should inherit the subclass pagination.BasePagination, override the paginate_queryset(self, queryset, request, view=None), and get_paginated_response(self, data) methods: The paginate_queryset method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page. The get_paginated_response method is passed to the serialized page data and should return a Response instance. Note that the paginate_queryset method may set state on the pagination instance, that may later be used by the get_paginated_response method. Example Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
'count': self.page.paginator.count,
'results': data
})
We'd then need to setup the custom class in our configuration: REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',
'PAGE_SIZE': 100
}
Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an OrderedDict when constructing the body of paginated responses, but this is optional. Using your custom pagination class To have your custom pagination class be used by default, use the DEFAULT_PAGINATION_CLASS setting: REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',
'PAGE_SIZE': 100
}
API responses for list endpoints will now include a Link header, instead of including the pagination links as part of the body of the response, for example: A custom pagination style, using the 'Link' header' Pagination & schemas You can also make the pagination controls available to the schema autogeneration that REST framework provides, by implementing a get_schema_fields() method. This method should have the following signature: get_schema_fields(self, view) The method should return a list of coreapi.Field instances. HTML pagination controls By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The PageNumberPagination and LimitOffsetPagination classes display a list of page numbers with previous and next controls. The CursorPagination class displays a simpler style that only displays a previous and next control. Customizing the controls You can override the templates that render the HTML pagination controls. The two built-in styles are: rest_framework/pagination/numbers.html rest_framework/pagination/previous_and_next.html Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting template = None as an attribute on the class. You'll then need to configure your DEFAULT_PAGINATION_CLASS settings key to use your custom class as the default pagination style. Low-level API The low-level API for determining if a pagination class should display the controls or not is exposed as a display_page_controls attribute on the pagination instance. Custom pagination classes should be set to True in the paginate_queryset method if they require the HTML pagination controls to be displayed. The .to_html() and .get_html_context() methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered. Third party packages The following third party packages are also available. DRF-extensions The DRF-extensions package includes a PaginateByMaxMixin mixin class that allows your API clients to specify ?page_size=max to obtain the maximum allowed page size. drf-proxy-pagination The drf-proxy-pagination package includes a ProxyPagination class which allows to choose pagination class with a query parameter. link-header-pagination The django-rest-framework-link-header-pagination package includes a LinkHeaderPagination class which provides pagination via an HTTP Link header as described in Github's developer documentation. pagination.py | |
doc_29785 |
Roll provided date forward to next offset only if not on offset. | |
doc_29786 | A subclass of GeoModelAdmin that uses a Spherical Mercator projection with OpenStreetMap street data tiles. Deprecated since version 4.0: This class is deprecated. Use GISModelAdmin instead. | |
doc_29787 | Just like a ChoiceField, except TypedChoiceField takes two extra arguments, coerce and empty_value. Default widget: Select
Empty value: Whatever you’ve given as empty_value. Normalizes to: A value of the type provided by the coerce argument. Validates that the given value exists in the list of choices and can be coerced. Error message keys: required, invalid_choice
Takes extra arguments:
coerce
A function that takes one argument and returns a coerced value. Examples include the built-in int, float, bool and other types. Defaults to an identity function. Note that coercion happens after input validation, so it is possible to coerce to a value not present in choices.
empty_value
The value to use to represent “empty.” Defaults to the empty string; None is another common choice here. Note that this value will not be coerced by the function given in the coerce argument, so choose it accordingly. | |
doc_29788 | Specify the size in bytes of audio samples. | |
doc_29789 | See Migration guide for more details. tf.compat.v1.linalg.lu
tf.linalg.lu(
input, output_idx_type=tf.dtypes.int32, name=None
)
The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The input has to be invertible. The output consists of two tensors LU and P containing the LU decomposition of all input submatrices [..., :, :]. LU encodes the lower triangular and upper triangular factors. For each input submatrix of shape [M, M], L is a lower triangular matrix of shape [M, M] with unit diagonal whose entries correspond to the strictly lower triangular part of LU. U is a upper triangular matrix of shape [M, M] whose entries correspond to the upper triangular part, including the diagonal, of LU. P represents a permutation matrix encoded as a list of indices each between 0 and M-1, inclusive. If P_mat denotes the permutation matrix corresponding to P, then the L, U and P satisfies P_mat * input = L * U.
Args
input A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. A tensor of shape [..., M, M] whose inner-most 2 dimensions form matrices of size [M, M].
output_idx_type An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32.
name A name for the operation (optional).
Returns A tuple of Tensor objects (lu, p). lu A Tensor. Has the same type as input.
p A Tensor of type output_idx_type. | |
doc_29790 |
Perform flood filling on an image. Starting at a specific seed_point, connected points equal or within tolerance of the seed value are found, then set to new_value. Parameters
imagendarray
An n-dimensional array.
seed_pointtuple or int
The point in image used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer.
new_valueimage type
New value to set the entire fill. This must be chosen in agreement with the dtype of image.
selemndarray, optional
A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as image. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected).
connectivityint, optional
A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to connectivity are considered neighbors. Ignored if selem is not None.
tolerancefloat or int, optional
If None (default), adjacent values must be strictly equal to the value of image at seed_point to be filled. This is fastest. If a tolerance is provided, adjacent points with values within plus or minus tolerance from the seed point are filled (inclusive).
in_placebool, optional
If True, flood filling is applied to image in place. If False, the flood filled result is returned without modifying the input image (default).
inplacebool, optional
This parameter is deprecated and will be removed in version 0.19.0 in favor of in_place. If True, flood filling is applied to image inplace. If False, the flood filled result is returned without modifying the input image (default). Returns
filledndarray
An array with the same shape as image is returned, with values in areas connected to and equal (or within tolerance of) the seed point replaced with new_value. Notes The conceptual analogy of this operation is the ‘paint bucket’ tool in many raster graphics programs. Examples >>> from skimage.morphology import flood_fill
>>> image = np.zeros((4, 7), dtype=int)
>>> image[1:3, 1:3] = 1
>>> image[3, 0] = 1
>>> image[1:3, 4:6] = 2
>>> image[3, 6] = 3
>>> image
array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 2, 2, 0],
[0, 1, 1, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, with full connectivity (diagonals included): >>> flood_fill(image, (1, 1), 5)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[5, 0, 0, 0, 0, 0, 3]])
Fill connected ones with 5, excluding diagonal points (connectivity 1): >>> flood_fill(image, (1, 1), 5, connectivity=1)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 5, 5, 0, 2, 2, 0],
[0, 5, 5, 0, 2, 2, 0],
[1, 0, 0, 0, 0, 0, 3]])
Fill with a tolerance: >>> flood_fill(image, (0, 0), 5, tolerance=1)
array([[5, 5, 5, 5, 5, 5, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 2, 2, 5],
[5, 5, 5, 5, 5, 5, 3]]) | |
doc_29791 |
Return whether the artist is animated. | |
doc_29792 |
Maximum likelihood covariance estimator Read more in the User Guide. Parameters
store_precisionbool, default=True
Specifies if the estimated precision is stored.
assume_centeredbool, default=False
If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False (default), data are centered before computation. Attributes
location_ndarray of shape (n_features,)
Estimated location, i.e. the estimated mean.
covariance_ndarray of shape (n_features, n_features)
Estimated covariance matrix
precision_ndarray of shape (n_features, n_features)
Estimated pseudo-inverse matrix. (stored only if store_precision is True) Examples >>> import numpy as np
>>> from sklearn.covariance import EmpiricalCovariance
>>> from sklearn.datasets import make_gaussian_quantiles
>>> real_cov = np.array([[.8, .3],
... [.3, .4]])
>>> rng = np.random.RandomState(0)
>>> X = rng.multivariate_normal(mean=[0, 0],
... cov=real_cov,
... size=500)
>>> cov = EmpiricalCovariance().fit(X)
>>> cov.covariance_
array([[0.7569..., 0.2818...],
[0.2818..., 0.3928...]])
>>> cov.location_
array([0.0622..., 0.0193...])
Methods
error_norm(comp_cov[, norm, scaling, squared]) Computes the Mean Squared Error between two covariance estimators.
fit(X[, y]) Fits the Maximum Likelihood Estimator covariance model according to the given training data and parameters.
get_params([deep]) Get parameters for this estimator.
get_precision() Getter for the precision matrix.
mahalanobis(X) Computes the squared Mahalanobis distances of given observations.
score(X_test[, y]) Computes the log-likelihood of a Gaussian data set with self.covariance_ as an estimator of its covariance matrix.
set_params(**params) Set the parameters of this estimator.
error_norm(comp_cov, norm='frobenius', scaling=True, squared=True) [source]
Computes the Mean Squared Error between two covariance estimators. (In the sense of the Frobenius norm). Parameters
comp_covarray-like of shape (n_features, n_features)
The covariance to compare with.
norm{“frobenius”, “spectral”}, default=”frobenius”
The type of norm used to compute the error. Available error types: - ‘frobenius’ (default): sqrt(tr(A^t.A)) - ‘spectral’: sqrt(max(eigenvalues(A^t.A)) where A is the error (comp_cov - self.covariance_).
scalingbool, default=True
If True (default), the squared error norm is divided by n_features. If False, the squared error norm is not rescaled.
squaredbool, default=True
Whether to compute the squared error norm or the error norm. If True (default), the squared error norm is returned. If False, the error norm is returned. Returns
resultfloat
The Mean Squared Error (in the sense of the Frobenius norm) between self and comp_cov covariance estimators.
fit(X, y=None) [source]
Fits the Maximum Likelihood Estimator covariance model according to the given training data and parameters. Parameters
Xarray-like of shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
yIgnored
Not used, present for API consistency by convention. Returns
selfobject
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
get_precision() [source]
Getter for the precision matrix. Returns
precision_array-like of shape (n_features, n_features)
The precision matrix associated to the current covariance object.
mahalanobis(X) [source]
Computes the squared Mahalanobis distances of given observations. Parameters
Xarray-like of shape (n_samples, n_features)
The observations, the Mahalanobis distances of the which we compute. Observations are assumed to be drawn from the same distribution than the data used in fit. Returns
distndarray of shape (n_samples,)
Squared Mahalanobis distances of the observations.
score(X_test, y=None) [source]
Computes the log-likelihood of a Gaussian data set with self.covariance_ as an estimator of its covariance matrix. Parameters
X_testarray-like of shape (n_samples, n_features)
Test data of which we compute the likelihood, where n_samples is the number of samples and n_features is the number of features. X_test is assumed to be drawn from the same distribution than the data used in fit (including centering).
yIgnored
Not used, present for API consistency by convention. Returns
resfloat
The likelihood of the data set with self.covariance_ as an estimator of its covariance matrix.
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_29793 | set the color palette for an 8-bit Surface set_palette([RGB, RGB, RGB, ...]) -> None Set the full palette for an 8-bit Surface. This will replace the colors in the existing palette. A partial palette can be passed and only the first colors in the original palette will be changed. This function has no effect on a Surface with more than 8-bits per pixel. | |
doc_29794 |
Normalize value data in the [vmin, vmax] interval into the [0.0, 1.0] interval and return it. Parameters
value
Data to normalize.
clipbool
If None, defaults to self.clip (which defaults to False). Notes If not already initialized, self.vmin and self.vmax are initialized using self.autoscale_None(value). | |
doc_29795 | See Migration guide for more details. tf.compat.v1.raw_ops.SdcaFprint
tf.raw_ops.SdcaFprint(
input, name=None
)
Args
input A Tensor of type string. vector of strings to compute fingerprints on.
name A name for the operation (optional).
Returns A Tensor of type int64. | |
doc_29796 |
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_29797 |
Replace values where the condition is False. Parameters
cond:bool Series/DataFrame, array-like, or callable
Where cond is True, keep the original value. Where False, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
other:scalar, Series/DataFrame, or callable
Entries where cond is False are replaced with corresponding value from other. If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
inplace:bool, default False
Whether to perform the operation in place on the data.
axis:int, default None
Alignment axis if needed.
level:int, default None
Alignment level if needed.
errors:str, {‘raise’, ‘ignore’}, default ‘raise’
Note that currently this parameter won’t affect the results and will always coerce to a suitable dtype. ‘raise’ : allow exceptions to be raised. ‘ignore’ : suppress exceptions. On error return original object.
try_cast:bool, default None
Try to cast the result back to the input type (if possible). Deprecated since version 1.3.0: Manually cast back if necessary. Returns
Same type as caller or None if inplace=True.
See also DataFrame.mask()
Return an object of same shape as self. Notes The where method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is True the element is used; otherwise the corresponding element from the DataFrame other is used. The signature for DataFrame.where() differs from numpy.where(). Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2). For further details and examples see the where documentation in indexing. Examples
>>> s = pd.Series(range(5))
>>> s.where(s > 0)
0 NaN
1 1.0
2 2.0
3 3.0
4 4.0
dtype: float64
>>> s.mask(s > 0)
0 0.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
>>> s.where(s > 1, 10)
0 10
1 10
2 2
3 3
4 4
dtype: int64
>>> s.mask(s > 1, 10)
0 0
1 1
2 10
3 10
4 10
dtype: int64
>>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
>>> df
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
>>> m = df % 3 == 0
>>> df.where(m, -df)
A B
0 0 -1
1 -2 3
2 -4 -5
3 6 -7
4 -8 9
>>> df.where(m, -df) == np.where(m, df, -df)
A B
0 True True
1 True True
2 True True
3 True True
4 True True
>>> df.where(m, -df) == df.mask(~m, -df)
A B
0 True True
1 True True
2 True True
3 True True
4 True True | |
doc_29798 | empty sequences and collections: '', (), [], {}, set(), range(0)
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.) Boolean Operations — and, or, not
These are the Boolean operations, ordered by ascending priority:
Operation Result Notes
x or y if x is false, then y, else x (1)
x and y if x is false, then x, else y (2)
not x if x is false, then True, else False (3) Notes: This is a short-circuit operator, so it only evaluates the second argument if the first one is false. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error. Comparisons There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and
y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). This table summarizes the comparison operations:
Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity Objects of different types, except different numeric types, never compare equal. The == operator is always defined but for some object types (for example, class objects) is equivalent to is. The <, <=, > and >= operators are only defined where they make sense; for example, they raise a TypeError exception when one of the arguments is a complex number. Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method. Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __lt__(), __le__(), __gt__(), and __ge__() (in general, __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators). The behavior of the is and is not operators cannot be customized; also they can be applied to any two objects and never raise an exception. Two more operations with the same syntactic priority, in and not in, are supported by types that are iterable or implement the __contains__() method. Numeric Types — int, float, complex There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in sys.float_info. Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number z, use z.real and z.imag. (The standard library includes the additional numeric types fractions.Fraction, for rationals, and decimal.Decimal, for floating-point numbers with user-definable precision.) Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending 'j' or 'J' to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts. Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. 2 The constructors int(), float(), and complex() can be used to produce numbers of a specific type. All numeric types (except complex) support the following operations (for priorities of the operations, see Operator precedence):
Operation Result Notes Full documentation
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y floored quotient of x and y (1)
x % y remainder of x / y (2)
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x abs()
int(x) x converted to integer (3)(6) int()
float(x) x converted to floating point (4)(6) float()
complex(re, im) a complex number with real part re, imaginary part im. im defaults to zero. (6) complex()
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y) (2) divmod()
pow(x, y) x to the power y (5) pow()
x ** y x to the power y (5) Notes: Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0. Not for complex numbers. Instead convert to floats using abs() if appropriate. Conversion from floating point to integer may round or truncate as in C; see functions math.floor() and math.ceil() for well-defined conversions. float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity. Python defines pow(0, 0) and 0 ** 0 to be 1, as is common for programming languages.
The numeric literals accepted include the digits 0 to 9 or any Unicode equivalent (code points with the Nd property). See https://www.unicode.org/Public/13.0.0/ucd/extracted/DerivedNumericType.txt for a complete list of code points with the Nd property. All numbers.Real types (int and float) also include the following operations:
Operation Result
math.trunc(x) x truncated to Integral
round(x[,
n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
math.floor(x) the greatest Integral <= x
math.ceil(x) the least Integral >= x For additional numeric operations see the math and cmath modules. Bitwise Operations on Integer Types Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits. The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -). This table lists the bitwise operations sorted in ascending priority:
Operation Result Notes
x | y bitwise or of x and y (4)
x ^ y bitwise exclusive or of x and y (4)
x & y bitwise and of x and y (4)
x << n x shifted left by n bits (1)(2)
x >> n x shifted right by n bits (1)(3)
~x the bits of x inverted Notes: Negative shift counts are illegal and cause a ValueError to be raised. A left shift by n bits is equivalent to multiplication by pow(2, n). A right shift by n bits is equivalent to floor division by pow(2, n). Performing these calculations with at least one extra sign extension bit in a finite two’s complement representation (a working bit-width of 1 + max(x.bit_length(), y.bit_length()) or more) is sufficient to get the same result as if there were an infinite number of sign bits. Additional Methods on Integer Types The int type implements the numbers.Integral abstract base class. In addition, it provides a few more methods:
int.bit_length()
Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros: >>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6
More precisely, if x is nonzero, then x.bit_length() is the unique positive integer k such that 2**(k-1) <= abs(x) < 2**k. Equivalently, when abs(x) is small enough to have a correctly rounded logarithm, then k = 1 + int(log(abs(x), 2)). If x is zero, then x.bit_length() returns 0. Equivalent to: def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
New in version 3.1.
int.to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer. >>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. The signed argument determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. The default value for signed is False. New in version 3.2.
classmethod int.from_bytes(bytes, byteorder, *, signed=False)
Return the integer represented by the given array of bytes. >>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
The argument bytes must either be a bytes-like object or an iterable producing bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. The signed argument indicates whether two’s complement is used to represent the integer. New in version 3.2.
int.as_integer_ratio()
Return a pair of integers whose ratio is exactly equal to the original integer and with a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and 1 as the denominator. New in version 3.8.
Additional Methods on Float The float type implements the numbers.Real abstract base class. float also has the following additional methods.
float.as_integer_ratio()
Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises OverflowError on infinities and a ValueError on NaNs.
float.is_integer()
Return True if the float instance is finite with integral value, and False otherwise: >>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.
float.hex()
Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading 0x and a trailing p and exponent.
classmethod float.fromhex(s)
Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace.
Note that float.hex() is an instance method, while float.fromhex() is a class method. A hexadecimal string takes the form: [sign] ['0x'] integer ['.' fraction] ['p' exponent]
where the optional sign may by either + or -, integer and fraction are strings of hexadecimal digits, and exponent is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of float.hex() is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s %a format character or Java’s Double.toHexString are accepted by float.fromhex(). Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string 0x3.a7p10 represents the floating-point number (3 + 10./16 + 7./16**2) * 2.0**10, or 3740.0: >>> float.fromhex('0x3.a7p10')
3740.0
Applying the reverse conversion to 3740.0 gives a different hexadecimal string representing the same number: >>> float.hex(3740.0)
'0x1.d380000000000p+11'
Hashing of numeric types For numbers x and y, possibly of different types, it’s a requirement that hash(x) == hash(y) whenever x == y (see the __hash__() method documentation for more details). For ease of implementation and efficiency across a variety of numeric types (including int, float, decimal.Decimal and fractions.Fraction) Python’s hash for numeric types is based on a single mathematical function that’s defined for any rational number, and hence applies to all instances of int and fractions.Fraction, and all finite instances of float and decimal.Decimal. Essentially, this function is given by reduction modulo P for a fixed prime P. The value of P is made available to Python as the modulus attribute of sys.hash_info. CPython implementation detail: Currently, the prime used is P = 2**31 - 1 on machines with 32-bit C longs and P = 2**61 - 1 on machines with 64-bit C longs. Here are the rules in detail: If x = m / n is a nonnegative rational number and n is not divisible by P, define hash(x) as m * invmod(n, P) % P, where invmod(n,
P) gives the inverse of n modulo P. If x = m / n is a nonnegative rational number and n is divisible by P (but m is not) then n has no inverse modulo P and the rule above doesn’t apply; in this case define hash(x) to be the constant value sys.hash_info.inf. If x = m / n is a negative rational number define hash(x) as -hash(-x). If the resulting hash is -1, replace it with -2. The particular values sys.hash_info.inf, -sys.hash_info.inf and sys.hash_info.nan are used as hash values for positive infinity, negative infinity, or nans (respectively). (All hashable nans have the same hash value.) For a complex number z, the hash values of the real and imaginary parts are combined by computing hash(z.real) +
sys.hash_info.imag * hash(z.imag), reduced modulo 2**sys.hash_info.width so that it lies in range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
1)). Again, if the result is -1, it’s replaced with -2. To clarify the above rules, here’s some example Python code, equivalent to the built-in hash, for computing the hash of a rational number, float, or complex: import sys, math
def hash_fraction(m, n):
"""Compute the hash of a rational number m / n.
Assumes m and n are integers, with n positive.
Equivalent to hash(fractions.Fraction(m, n)).
"""
P = sys.hash_info.modulus
# Remove common factors of P. (Unnecessary if m and n already coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P
if n % P == 0:
hash_value = sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
if m < 0:
hash_value = -hash_value
if hash_value == -1:
hash_value = -2
return hash_value
def hash_float(x):
"""Compute the hash of a float x."""
if math.isnan(x):
return sys.hash_info.nan
elif math.isinf(x):
return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
else:
return hash_fraction(*x.as_integer_ratio())
def hash_complex(z):
"""Compute the hash of a complex number z."""
hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
# do a signed reduction modulo 2**sys.hash_info.width
M = 2**(sys.hash_info.width - 1)
hash_value = (hash_value & (M - 1)) - (hash_value & M)
if hash_value == -1:
hash_value = -2
return hash_value
Iterator Types Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods. One method needs to be defined for container objects to provide iteration support:
container.__iter__()
Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
iterator.__next__()
Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol. Once an iterator’s __next__() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken. Generator Types Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and __next__() methods. More information about generators can be found in the documentation for the yield expression. Sequence Types — list, tuple, range There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of binary data and text strings are described in dedicated sections. Common Sequence Operations The operations in the following table are supported by most sequence types, both mutable and immutable. The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types. This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s. The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations. 3
Operation Result Notes
x in s True if an item of s is equal to x, else False (1)
x not in s False if an item of s is equal to x, else True (1)
s + t the concatenation of s and t (6)(7)
s * n or n * s equivalent to adding s to itself n times (2)(7)
s[i] ith item of s, origin 0 (3)
s[i:j] slice of s from i to j (3)(4)
s[i:j:k] slice of s from i to j with step k (3)(5)
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before index j) (8)
s.count(x) total number of occurrences of x in s Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.) Notes:
While the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing: >>> "gg" in "eggs"
True
Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider: >>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way: >>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
Further explanation is available in the FAQ entry How do I create a multidimensional list?. If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0. The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty. The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below: if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism if concatenating tuple objects, extend a list instead for other types, investigate the relevant class documentation Some sequence types (such as range) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition.
index raises ValueError when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using s[i:j].index(x), only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice. Immutable Sequence Types The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the hash() built-in. This support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances. Attempting to hash an immutable sequence that contains unhashable values will result in TypeError. Mutable Sequence Types The operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types. In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).
Operation Result Notes
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t (1)
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:]) (5)
s.copy() creates a shallow copy of s (same as s[:]) (5)
s.extend(t) or s += t extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times (6)
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop([i]) retrieves the item at i and also removes it from s (2)
s.remove(x) remove the first item from s where s[i] is equal to x (3)
s.reverse() reverses the items of s in place (4) Notes:
t must have the same length as the slice it is replacing. The optional argument i defaults to -1, so that by default the last item is removed and returned.
remove() raises ValueError when x is not found in s. The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.
clear() and copy() are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as dict and set). copy() is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it. New in version 3.3: clear() and copy() methods. The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations. Lists Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).
class list([iterable])
Lists may be constructed in several ways: Using a pair of square brackets to denote the empty list: []
Using square brackets, separating items with commas: [a], [a, b, c]
Using a list comprehension: [x for x in iterable]
Using the type constructor: list() or list(iterable)
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, []. Many other operations also produce lists, including the sorted() built-in. Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method:
sort(*, key=None, reverse=False)
This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state). sort() accepts two arguments that can only be passed by keyword (keyword-only arguments): key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value. The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function. reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed. This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance). The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). For sorting examples and a brief sorting tutorial, see Sorting HOW TO. CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.
Tuples Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).
class tuple([iterable])
Tuples may be constructed in a number of ways: Using a pair of parentheses to denote the empty tuple: ()
Using a trailing comma for a singleton tuple: a, or (a,)
Separating items with commas: a, b, c or (a, b, c)
Using the tuple() built-in: tuple() or tuple(iterable)
The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns (1, 2, 3). If no argument is given, the constructor creates a new empty tuple, (). Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b, c) is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument. Tuples implement all of the common sequence operations.
For heterogeneous collections of data where access by name is clearer than access by index, collections.namedtuple() may be a more appropriate choice than a simple tuple object. Ranges The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
class range(stop)
class range(start, stop[, step])
The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised. For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop. For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop. A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices. Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError. Range examples: >>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).
start
The value of the start parameter (or 0 if the parameter was not supplied)
stop
The value of the stop parameter
step
The value of the step parameter (or 1 if the parameter was not supplied)
The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed). Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see Sequence Types — list, tuple, range): >>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18
Testing range objects for equality with == and != compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different start, stop and step attributes, for example range(0) == range(2, 1, 3) or range(0, 3, 2) == range(0, 4, 2).) Changed in version 3.2: Implement the Sequence ABC. Support slicing and negative indices. Test int objects for membership in constant time instead of iterating through all items. Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity). New in version 3.3: The start, stop and step attributes. See also The linspace recipe shows how to implement a lazy version of range suitable for floating point applications. Text Sequence Type — str Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways: Single quotes: 'allows embedded "double" quotes'
Double quotes: "allows embedded 'single' quotes". Triple quoted: '''Three single quotes''', """Three double quotes"""
Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal. String literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, ("spam " "eggs") == "spam eggs". See String and Bytes literals for more about the various forms of string literal, including supported escape sequences, and the r (“raw”) prefix that disables most escape sequence processing. Strings may also be created from other objects using the str constructor. Since there is no separate “character” type, indexing a string produces strings of length 1. That is, for a non-empty string s, s[0] == s[0:1]. There is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments. Changed in version 3.3: For backwards compatibility with the Python 2 series, the u prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the r prefix.
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows. If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object). If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects. Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example: >>> str(b'Zoot!')
"b'Zoot!'"
For more information on the str class and its methods, see Text Sequence Type — str and the String Methods section below. To output formatted strings, see the Formatted string literals and Format String Syntax sections. In addition, see the Text Processing Services section.
String Methods Strings implement all of the common sequence operations, along with the additional methods described below. Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see str.format(), Format String Syntax and Custom String Formatting) and the other based on C printf style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (printf-style String Formatting). The Text Processing Services section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the re module).
str.capitalize()
Return a copy of the string with its first character capitalized and the rest lowercased. Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.
str.casefold()
Return a casefolded copy of the string. Casefolded strings may be used for caseless matching. Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss". The casefolding algorithm is described in section 3.13 of the Unicode Standard. New in version 3.3.
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
str.encode(encoding="utf-8", errors="strict")
Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings. By default, the errors argument is not checked for best performances, but only used at the first encoding error. Enable the Python Development Mode, or use a debug build to check errors. Changed in version 3.1: Support for keyword arguments added. Changed in version 3.9: The errors is now checked in development mode and in debug mode.
str.endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
str.expandtabs(tabsize=8)
Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed. >>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. Note The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator: >>> 'Py' in 'Python'
True
str.format(*args, **kwargs)
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument. >>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
See Format String Syntax for a description of the various formatting options that can be specified in format strings. Note When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: '{:n}'.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads. Changed in version 3.7: When formatting a number with the n type, the function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.
str.format_map(mapping)
Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass: >>> class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'
New in version 3.2.
str.index(sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.
str.isalnum()
Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().
str.isalpha()
Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.
str.isascii()
Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F. New in version 3.7.
str.isdecimal()
Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.
str.isdigit()
Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
str.isidentifier()
Return True if the string is a valid identifier according to the language definition, section Identifiers and keywords. Call keyword.iskeyword() to test whether string s is a reserved identifier, such as def and class. Example: >>> from keyword import iskeyword
>>> 'hello'.isidentifier(), iskeyword('hello')
True, False
>>> 'def'.isidentifier(), iskeyword('def')
True, True
str.islower()
Return True if all cased characters 4 in the string are lowercase and there is at least one cased character, False otherwise.
str.isnumeric()
Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
str.isprintable()
Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)
str.isspace()
Return True if there are only whitespace characters in the string and there is at least one character, False otherwise. A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.
str.istitle()
Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.
str.isupper()
Return True if all cased characters 4 in the string are uppercase and there is at least one cased character, False otherwise. >>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False
str.join(iterable)
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
str.ljust(width[, fillchar])
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
str.lower()
Return a copy of the string with all the cased characters 4 converted to lowercase. The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped: >>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
See str.removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example: >>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'
static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
str.partition(sep)
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
str.removeprefix(prefix, /)
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string: >>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
New in version 3.9.
str.removesuffix(suffix, /)
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string: >>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
New in version 3.9.
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
str.rfind(sub[, start[, end]])
Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
str.rindex(sub[, start[, end]])
Like rfind() but raises ValueError when the substring sub is not found.
str.rjust(width[, fillchar])
Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
str.rpartition(sep)
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.
str.rsplit(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.
str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
See str.removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example: >>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty'
str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. For example: >>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. For example: >>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3']
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.
Representation Description
\n Line Feed
\r Carriage Return
\r\n Carriage Return + Line Feed
\v or \x0b Line Tabulation
\f or \x0c Form Feed
\x1c File Separator
\x1d Group Separator
\x1e Record Separator
\x85 Next Line (C1 Control Code)
\u2028 Line Separator
\u2029 Paragraph Separator Changed in version 3.2: \v and \f added to list of line boundaries. For example: >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line: >>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']
For comparison, split('\n') gives: >>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']
str.startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example: >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.swapcase()
Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.
str.title()
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase. For example: >>> 'Hello world'.title()
'Hello World'
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result: >>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
A workaround for apostrophes can be constructed using regular expressions: >>> import re
>>> def titlecase(s):
... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0).capitalize(),
... s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
str.translate(table)
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__(), typically a mapping or sequence. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None, to delete the character from the return string; or raise a LookupError exception, to map the character to itself. You can use str.maketrans() to create a translation map from character-to-character mappings in different formats. See also the codecs module for a more flexible approach to custom character mappings.
str.upper()
Return a copy of the string with all the cased characters 4 converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase). The uppercasing algorithm used is described in section 3.13 of the Unicode Standard.
str.zfill(width)
Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s). For example: >>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'
printf-style String Formatting Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility. String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language. If format requires a single argument, values may be a single non-tuple object. 5 Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary). A conversion specifier contains two or more characters and has the following components, which must occur in this order: The '%' character, which marks the start of the specifier. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)). Conversion flags (optional), which affect the result of some conversion types. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision. Length modifier (optional). Conversion type. When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example: >>> print('%(language)s has %(number)03d quote types.' %
... {'language': "Python", "number": 2})
Python has 002 quote types.
In this case no * specifiers may occur in a format (since they require a sequential parameter list). The conversion flag characters are:
Flag Meaning
'#' The value conversion will use the “alternate form” (where defined below).
'0' The conversion will be zero padded for numeric values.
'-' The converted value is left adjusted (overrides the '0' conversion if both are given).
' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
'+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag). A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d. The conversion types are:
Conversion Meaning Notes
'd' Signed integer decimal.
'i' Signed integer decimal.
'o' Signed octal value. (1)
'u' Obsolete type – it is identical to 'd'. (6)
'x' Signed hexadecimal (lowercase). (2)
'X' Signed hexadecimal (uppercase). (2)
'e' Floating point exponential format (lowercase). (3)
'E' Floating point exponential format (uppercase). (3)
'f' Floating point decimal format. (3)
'F' Floating point decimal format. (3)
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'c' Single character (accepts integer or single character string).
'r' String (converts any Python object using repr()). (5)
's' String (converts any Python object using str()). (5)
'a' String (converts any Python object using ascii()). (5)
'%' No argument is converted, results in a '%' character in the result. Notes: The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit. The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the first digit.
The alternate form causes the result to always contain a decimal point, even if no digits follow it. The precision determines the number of digits after the decimal point and defaults to 6.
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be. The precision determines the number of significant digits before and after the decimal point and defaults to 6. If precision is N, the output is truncated to N characters. See PEP 237. Since Python strings have an explicit length, %s conversions do not assume that '\0' is the end of the string. Changed in version 3.1: %f conversions for numbers whose absolute value is over 1e50 are no longer replaced by %g conversions. Binary Sequence Types — bytes, bytearray, memoryview The core built-in types for manipulating binary data are bytes and bytearray. They are supported by memoryview which uses the buffer protocol to access the memory of other binary objects without needing to make a copy. The array module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values. Bytes Objects Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.
class bytes([source[, encoding[, errors]]])
Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added: Single quotes: b'still allows embedded "double" quotes'
Double quotes: b"still allows embedded 'single' quotes". Triple quoted: b'''3 single quotes''', b"""3 double quotes"""
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence. As with string literals, bytes literals may also use a r prefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences. While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption). In addition to the literal forms, bytes objects can be created in a number of other ways: A zero-filled bytes object of a specified length: bytes(10)
From an iterable of integers: bytes(range(20))
Copying existing binary data via the buffer protocol: bytes(obj)
Also see the bytes built-in. Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:
classmethod fromhex(string)
This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytes.fromhex('2Ef0 F1f2 ')
b'.\xf0\xf1\xf2'
Changed in version 3.7: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces.
A reverse conversion function exists to transform a bytes object into its hexadecimal representation.
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left. >>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
New in version 3.5. Changed in version 3.8: bytes.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1) The representation of bytes objects uses the literal format (b'...') since it is often more useful than e.g. bytes([46, 46, 46]). You can always convert a bytes object into a list of integers using list(b). Note For Python 2.x users: In the Python 2.x series, a variety of implicit conversions between 8-bit strings (the closest thing 2.x offers to a built-in binary data type) and Unicode strings were permitted. This was a backwards compatibility workaround to account for the fact that Python originally only supported 8-bit text, and Unicode text was a later addition. In Python 3.x, those implicit conversions are gone - conversions between 8-bit binary data and Unicode text must be explicit, and bytes and string objects will always compare unequal. Bytearray Objects bytearray objects are a mutable counterpart to bytes objects.
class bytearray([source[, encoding[, errors]]])
There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor: Creating an empty instance: bytearray()
Creating a zero-filled instance with a given length: bytearray(10)
From an iterable of integers: bytearray(range(20))
Copying existing binary data via the buffer protocol: bytearray(b'Hi!')
As bytearray objects are mutable, they support the mutable sequence operations in addition to the common bytes and bytearray operations described in Bytes and Bytearray Operations. Also see the bytearray built-in. Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:
classmethod fromhex(string)
This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytearray.fromhex('2Ef0 F1f2 ')
bytearray(b'.\xf0\xf1\xf2')
Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.
A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'
New in version 3.5. Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b, b[0] will be an integer, while b[0:1] will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1) The representation of bytearray objects uses the bytes literal format (bytearray(b'...')) since it is often more useful than e.g. bytearray([46, 46, 46]). You can always convert a bytearray object into a list of integers using list(b). Bytes and Bytearray Operations Both bytes and bytearray objects support the common sequence operations. They interoperate not just with operands of the same type, but with any bytes-like object. Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands. Note The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write: a = "abc"
b = a.replace("a", "f")
and: a = b"abc"
b = a.replace(b"a", b"f")
Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below. Note Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption. The following methods on bytes and bytearray objects can be used with arbitrary binary data.
bytes.count(sub[, start[, end]])
bytearray.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255. Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
bytes.removeprefix(prefix, /)
bytearray.removeprefix(prefix, /)
If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data: >>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
The prefix may be any bytes-like object. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. New in version 3.9.
bytes.removesuffix(suffix, /)
bytearray.removesuffix(suffix, /)
If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data: >>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
The suffix may be any bytes-like object. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. New in version 3.9.
bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")
Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings. By default, the errors argument is not checked for best performances, but only used at the first decoding error. Enable the Python Development Mode, or use a debug build to check errors. Note Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object. Changed in version 3.1: Added support for keyword arguments. Changed in version 3.9: The errors is now checked in development mode and in debug mode.
bytes.endswith(suffix[, start[, end]])
bytearray.endswith(suffix[, start[, end]])
Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. The suffix(es) to search for may be any bytes-like object.
bytes.find(sub[, start[, end]])
bytearray.find(sub[, start[, end]])
Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255. Note The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator: >>> b'Py' in b'Python'
True
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
bytes.index(sub[, start[, end]])
bytearray.index(sub[, start[, end]])
Like find(), but raise ValueError when the subsequence is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255. Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
bytes.join(iterable)
bytearray.join(iterable)
Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A TypeError will be raised if there are any values in iterable that are not bytes-like objects, including str objects. The separator between elements is the contents of the bytes or bytearray object providing this method.
static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)
This static method returns a translation table usable for bytes.translate() that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length. New in version 3.1.
bytes.partition(sep)
bytearray.partition(sep)
Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects. The separator to search for may be any bytes-like object.
bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])
Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. The subsequence to search for and its replacement may be any bytes-like object. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])
Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255. Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])
Like rfind() but raises ValueError when the subsequence sub is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255. Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
bytes.rpartition(sep)
bytearray.rpartition(sep)
Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence. The separator to search for may be any bytes-like object.
bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])
Return True if the binary data starts with the specified prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. The prefix(es) to search for may be any bytes-like object.
bytes.translate(table, /, delete=b'')
bytearray.translate(table, /, delete=b'')
Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256. You can use the bytes.maketrans() method to create a translation table. Set the table argument to None for translations that only delete characters: >>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
Changed in version 3.6: delete is now supported as a keyword argument.
The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.
bytes.center(width[, fillbyte])
bytearray.center(width[, fillbyte])
Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s). Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])
Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s). Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.lstrip([chars])
bytearray.lstrip([chars])
Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped: >>> b' spacious '.lstrip()
b'spacious '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
The binary sequence of byte values to remove may be any bytes-like object. See removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example: >>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])
Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s). Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.
bytes.rstrip([chars])
bytearray.rstrip([chars])
Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> b' spacious '.rstrip()
b' spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
The binary sequence of byte values to remove may be any bytes-like object. See removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example: >>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence (for example, b'1<>2<>3'.split(b'<>') returns [b'1', b'2', b'3']). Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object. For example: >>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns []. For example: >>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b' 1 2 3 '.split()
[b'1', b'2', b'3']
bytes.strip([chars])
bytearray.strip([chars])
Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> b' spacious '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
The binary sequence of byte values to remove may be any bytes-like object. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.
bytes.capitalize()
bytearray.capitalize()
Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)
Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed: >>> b'01\t012\t0123\t01234'.expandtabs()
b'01 012 0123 01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01 012 0123 01234'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.isalnum()
bytearray.isalnum()
Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'. For example: >>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False
bytes.isalpha()
bytearray.isalpha()
Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. For example: >>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False
bytes.isascii()
bytearray.isascii()
Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F. New in version 3.7.
bytes.isdigit()
bytearray.isdigit()
Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'. For example: >>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False
bytes.islower()
bytearray.islower()
Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise. For example: >>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
bytes.isspace()
bytearray.isspace()
Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).
bytes.istitle()
bytearray.istitle()
Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of “titlecase”. For example: >>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False
bytes.isupper()
bytearray.isupper()
Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise. For example: >>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
bytes.lower()
bytearray.lower()
Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart. For example: >>> b'Hello World'.lower()
b'hello world'
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)
Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true. For example: >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line: >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])
bytes.swapcase()
bytearray.swapcase()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa. For example: >>> b'Hello World'.swapcase()
b'hELLO wORLD'
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Unlike str.swapcase(), it is always the case that bin.swapcase().swapcase() == bin for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.title()
bytearray.title()
Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified. For example: >>> b'Hello world'.title()
b'Hello World'
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased. The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result: >>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
A workaround for apostrophes can be constructed using regular expressions: >>> import re
>>> def titlecase(s):
... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0)[0:1].upper() +
... mo.group(0)[1:].lower(),
... s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.upper()
bytearray.upper()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart. For example: >>> b'Hello World'.upper()
b'HELLO WORLD'
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
bytes.zfill(width)
bytearray.zfill(width)
Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq). For example: >>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
printf-style Bytes Formatting Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). If the value being printed may be a tuple or dictionary, wrap it in a tuple. Bytes objects (bytes/bytearray) have one unique built-in operation: the % operator (modulo). This is also known as the bytes formatting or interpolation operator. Given format % values (where format is a bytes object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language. If format requires a single argument, values may be a single non-tuple object. 5 Otherwise, values must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary). A conversion specifier contains two or more characters and has the following components, which must occur in this order: The '%' character, which marks the start of the specifier. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)). Conversion flags (optional), which affect the result of some conversion types. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision. Length modifier (optional). Conversion type. When the right argument is a dictionary (or other mapping type), then the formats in the bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example: >>> print(b'%(language)s has %(number)03d quote types.' %
... {b'language': b"Python", b"number": 2})
b'Python has 002 quote types.'
In this case no * specifiers may occur in a format (since they require a sequential parameter list). The conversion flag characters are:
Flag Meaning
'#' The value conversion will use the “alternate form” (where defined below).
'0' The conversion will be zero padded for numeric values.
'-' The converted value is left adjusted (overrides the '0' conversion if both are given).
' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
'+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag). A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d. The conversion types are:
Conversion Meaning Notes
'd' Signed integer decimal.
'i' Signed integer decimal.
'o' Signed octal value. (1)
'u' Obsolete type – it is identical to 'd'. (8)
'x' Signed hexadecimal (lowercase). (2)
'X' Signed hexadecimal (uppercase). (2)
'e' Floating point exponential format (lowercase). (3)
'E' Floating point exponential format (uppercase). (3)
'f' Floating point decimal format. (3)
'F' Floating point decimal format. (3)
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'c' Single byte (accepts integer or single byte objects).
'b' Bytes (any object that follows the buffer protocol or has __bytes__()). (5)
's' 's' is an alias for 'b' and should only be used for Python2/3 code bases. (6)
'a' Bytes (converts any Python object using repr(obj).encode('ascii','backslashreplace)). (5)
'r' 'r' is an alias for 'a' and should only be used for Python2/3 code bases. (7)
'%' No argument is converted, results in a '%' character in the result. Notes: The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit. The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the first digit.
The alternate form causes the result to always contain a decimal point, even if no digits follow it. The precision determines the number of digits after the decimal point and defaults to 6.
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be. The precision determines the number of significant digits before and after the decimal point and defaults to 6. If precision is N, the output is truncated to N characters.
b'%s' is deprecated, but will not be removed during the 3.x series.
b'%r' is deprecated, but will not be removed during the 3.x series. See PEP 237. Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. See also PEP 461 - Adding % formatting to bytes and bytearray New in version 3.5. Memory Views memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.
class memoryview(obj)
Create a memoryview that references obj. obj must support the buffer protocol. Built-in objects that support the buffer protocol include bytes and bytearray. A memoryview has the notion of an element, which is the atomic memory unit handled by the originating object obj. For many simple types such as bytes and bytearray, an element is a single byte, but other types such as array.array may have bigger elements. len(view) is equal to the length of tolist. If view.ndim = 0, the length is 1. If view.ndim = 1, the length is equal to the number of elements in the view. For higher dimensions, the length is equal to the length of the nested list representation of the view. The itemsize attribute will give you the number of bytes in a single element. A memoryview supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview: >>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'
If format is one of the native format specifiers from the struct module, indexing with an integer or a tuple of integers is also supported and returns a single element with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly ndim integers where ndim is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple. Here is an example with a non-byte format: >>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]
If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed: >>> data = bytearray(b'abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = ord(b'z')
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = b'123'
>>> data
bytearray(b'z123fg')
>>> v[2:3] = b'spam'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different structures
>>> v[2:6] = b'spam'
>>> data
bytearray(b'z1spam')
One-dimensional memoryviews of hashable (read-only) types with formats ‘B’, ‘b’ or ‘c’ are also hashable. The hash is defined as hash(m) == hash(m.tobytes()): >>> v = memoryview(b'abcefg')
>>> hash(v) == hash(b'abcefg')
True
>>> hash(v[2:4]) == hash(b'ce')
True
>>> hash(v[::-2]) == hash(b'abcefg'[::-2])
True
Changed in version 3.3: One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats ‘B’, ‘b’ or ‘c’ are now hashable. Changed in version 3.4: memoryview is now registered automatically with collections.abc.Sequence Changed in version 3.5: memoryviews can now be indexed with tuple of integers. memoryview has several methods:
__eq__(exporter)
A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands’ respective format codes are interpreted using struct syntax. For the subset of struct format strings currently supported by tolist(), v and w are equal if v.tolist() == w.tolist(): >>> import array
>>> a = array.array('I', [1, 2, 3, 4, 5])
>>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
>>> c = array.array('b', [5, 3, 1])
>>> x = memoryview(a)
>>> y = memoryview(b)
>>> x == a == y == b
True
>>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
True
>>> z = y[::-2]
>>> z == c
True
>>> z.tolist() == c.tolist()
True
If either format string is not supported by the struct module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical): >>> from ctypes import BigEndianStructure, c_long
>>> class BEPoint(BigEndianStructure):
... _fields_ = [("x", c_long), ("y", c_long)]
...
>>> point = BEPoint(100, 200)
>>> a = memoryview(point)
>>> b = memoryview(point)
>>> a == point
False
>>> a == b
False
Note that, as with floating point numbers, v is w does not imply v == w for memoryview objects. Changed in version 3.3: Previous versions compared the raw memory disregarding the item format and the logical array structure.
tobytes(order=None)
Return the data in the buffer as a bytestring. This is equivalent to calling the bytes constructor on the memoryview. >>> m = memoryview(b"abc")
>>> m.tobytes()
b'abc'
>>> bytes(m)
b'abc'
For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes. tobytes() supports all format strings, including those that are not in struct module syntax. New in version 3.8: order can be {‘C’, ‘F’, ‘A’}. When order is ‘C’ or ‘F’, the data of the original array is converted to C or Fortran order. For contiguous views, ‘A’ returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first. order=None is the same as order=’C’.
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the buffer. >>> m = memoryview(b"abc")
>>> m.hex()
'616263'
New in version 3.5. Changed in version 3.8: Similar to bytes.hex(), memoryview.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
tolist()
Return the data in the buffer as a list of elements. >>> memoryview(b'abc').tolist()
[97, 98, 99]
>>> import array
>>> a = array.array('d', [1.1, 2.2, 3.3])
>>> m = memoryview(a)
>>> m.tolist()
[1.1, 2.2, 3.3]
Changed in version 3.3: tolist() now supports all single character native formats in struct module syntax as well as multi-dimensional representations.
toreadonly()
Return a readonly version of the memoryview object. The original memoryview object is unchanged. >>> m = memoryview(bytearray(b'abc'))
>>> mm = m.toreadonly()
>>> mm.tolist()
[89, 98, 99]
>>> mm[0] = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> m[0] = 43
>>> mm.tolist()
[43, 98, 99]
New in version 3.8.
release()
Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a bytearray would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible. After this method has been called, any further operation on the view raises a ValueError (except release() itself which can be called multiple times): >>> m = memoryview(b'abc')
>>> m.release()
>>> m[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object
The context management protocol can be used for a similar effect, using the with statement: >>> with memoryview(b'abc') as m:
... m[0]
...
97
>>> m[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object
New in version 3.2.
cast(format[, shape])
Cast a memoryview to a new format or shape. shape defaults to [byte_length//new_itemsize], which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-contiguous and C-contiguous -> 1D. The destination format is restricted to a single element native format in struct syntax. One of the formats must be a byte format (‘B’, ‘b’ or ‘c’). The byte length of the result must be the same as the original length. Cast 1D/long to 1D/unsigned bytes: >>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24
Cast 1D/unsigned bytes to 1D/char: >>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: memoryview: invalid value for format "B"
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')
Cast 1D/bytes to 3D/ints to 1D/signed char: >>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48
Cast 1D/unsigned long to 2D/unsigned long: >>> buf = struct.pack("L"*6, *list(range(6)))
>>> x = memoryview(buf)
>>> y = x.cast('L', shape=[2,3])
>>> len(y)
2
>>> y.nbytes
48
>>> y.tolist()
[[0, 1, 2], [3, 4, 5]]
New in version 3.3. Changed in version 3.5: The source format is no longer restricted when casting to a byte view.
There are also several readonly attributes available:
obj
The underlying object of the memoryview: >>> b = bytearray(b'xyz')
>>> m = memoryview(b)
>>> m.obj is b
True
New in version 3.3.
nbytes
nbytes == product(shape) * itemsize == len(m.tobytes()). This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal to len(m): >>> import array
>>> a = array.array('i', [1,2,3,4,5])
>>> m = memoryview(a)
>>> len(m)
5
>>> m.nbytes
20
>>> y = m[::2]
>>> len(y)
3
>>> y.nbytes
12
>>> len(y.tobytes())
12
Multi-dimensional arrays: >>> import struct
>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
>>> x = memoryview(buf)
>>> y = x.cast('d', shape=[3,4])
>>> y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>> len(y)
3
>>> y.nbytes
96
New in version 3.3.
readonly
A bool indicating whether the memory is read only.
format
A string containing the format (in struct module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g. tolist()) are restricted to native single element formats. Changed in version 3.3: format 'B' is now handled according to the struct module syntax. This means that memoryview(b'abc')[0] == b'abc'[0] == 97.
itemsize
The size in bytes of each element of the memoryview: >>> import array, struct
>>> m = memoryview(array.array('H', [32000, 32001, 32002]))
>>> m.itemsize
2
>>> m[0]
32000
>>> struct.calcsize('H') == m.itemsize
True
ndim
An integer indicating how many dimensions of a multi-dimensional array the memory represents.
shape
A tuple of integers the length of ndim giving the shape of the memory as an N-dimensional array. Changed in version 3.3: An empty tuple instead of None when ndim = 0.
strides
A tuple of integers the length of ndim giving the size in bytes to access each element for each dimension of the array. Changed in version 3.3: An empty tuple instead of None when ndim = 0.
suboffsets
Used internally for PIL-style arrays. The value is informational only.
c_contiguous
A bool indicating whether the memory is C-contiguous. New in version 3.3.
f_contiguous
A bool indicating whether the memory is Fortran contiguous. New in version 3.3.
contiguous
A bool indicating whether the memory is contiguous. New in version 3.3.
Set Types — set, frozenset A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.) Like other collections, sets support x in set, len(set), and for x in
set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior. There are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set. Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor. The constructors for both classes work the same:
class set([iterable])
class frozenset([iterable])
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned. Sets can be created by several means: Use a comma-separated list of elements within braces: {'jack', 'sjoerd'}
Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}
Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo'])
Instances of set and frozenset provide the following operations:
len(s)
Return the number of elements in set s (cardinality of s).
x in s
Test x for membership in s.
x not in s
Test x for non-membership in s.
isdisjoint(other)
Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
issubset(other)
set <= other
Test whether every element in the set is in other.
set < other
Test whether the set is a proper subset of other, that is, set <= other and set != other.
issuperset(other)
set >= other
Test whether every element in other is in the set.
set > other
Test whether the set is a proper superset of other, that is, set >=
other and set != other.
union(*others)
set | other | ...
Return a new set with elements from the set and all others.
intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.
difference(*others)
set - other - ...
Return a new set with elements in the set that are not in the others.
symmetric_difference(other)
set ^ other
Return a new set with elements in either the set or other but not both.
copy()
Return a shallow copy of the set.
Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs'). Both set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal). Instances of set are compared to instances of frozenset based on their members. For example, set('abc') == frozenset('abc') returns True and so does set('abc') in set([frozenset('abc')]). The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: a<b, a==b, or a>b. Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets. Set elements, like dictionary keys, must be hashable. Binary operations that mix set instances with frozenset return the type of the first operand. For example: frozenset('ab') |
set('bc') returns an instance of frozenset. The following table lists operations available for set that do not apply to immutable instances of frozenset:
update(*others)
set |= other | ...
Update the set, adding elements from all others.
intersection_update(*others)
set &= other & ...
Update the set, keeping only elements found in it and all others.
difference_update(*others)
set -= other | ...
Update the set, removing elements found in others.
symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in both.
add(elem)
Add element elem to the set.
remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.
discard(elem)
Remove element elem from the set if it is present.
pop()
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
clear()
Remove all elements from the set.
Note, the non-operator versions of the update(), intersection_update(), difference_update(), and symmetric_difference_update() methods will accept any iterable as an argument. Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.
Mapping Types — dict A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. (For other containers see the built-in list, set, and tuple classes, and the collections module.) A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.) Dictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098:
'jack', 4127: 'sjoerd'}, or by the dict constructor.
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments. Dictionaries can be created by several means: Use a comma-separated list of key: value pairs within braces: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}
Use a dict comprehension: {}, {x: x ** 2 for x in range(10)}
Use the type constructor: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)
If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary. If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument. To illustrate, the following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3}: >>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> f = dict({'one': 1, 'three': 3}, two=2)
>>> a == b == c == d == e == f
True
Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used. These are the operations that dictionaries support (and therefore, custom mapping types should support too):
list(d)
Return a list of all the keys used in the dictionary d.
len(d)
Return the number of items in the dictionary d.
d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map. If a subclass of dict defines a method __missing__() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable: >>> class Counter(dict):
... def __missing__(self, key):
... return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1
The example above shows part of the implementation of collections.Counter. A different __missing__ method is used by collections.defaultdict.
d[key] = value
Set d[key] to value.
del d[key]
Remove d[key] from d. Raises a KeyError if key is not in the map.
key in d
Return True if d has a key key, else False.
key not in d
Equivalent to not key in d.
iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).
clear()
Remove all items from the dictionary.
copy()
Return a shallow copy of the dictionary.
classmethod fromkeys(iterable[, value])
Create a new dictionary with keys from iterable and values set to value. fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
items()
Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.
keys()
Return a new view of the dictionary’s keys. See the documentation of view objects.
pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
popitem()
Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError. Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.
reversed(d)
Return a reverse iterator over the keys of the dictionary. This is a shortcut for reversed(d.keys()). New in version 3.8.
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
values()
Return a new view of the dictionary’s values. See the documentation of view objects. An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself: >>> d = {'a': 1}
>>> d.values() == d.values()
False
d | other
Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys. New in version 3.9.
d |= other
Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys. New in version 3.9.
Dictionaries compare equal if and only if they have the same (key,
value) pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError. Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end. >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6. Dictionaries and dictionary views are reversible. >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
Changed in version 3.8: Dictionaries are now reversible.
See also types.MappingProxyType can be used to create a read-only view of a dict. Dictionary view objects The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. Dictionary views can be iterated over to yield their respective data, and support membership tests:
len(dictview)
Return the number of entries in the dictionary.
iter(dictview)
Return an iterator over the keys, values or items (represented as tuples of (key, value)) in the dictionary. Keys and values are iterated over in insertion order. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()]. Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
x in dictview
Return True if x is in the underlying dictionary’s keys, values or items (in the latter case, x should be a (key, value) tuple).
reversed(dictview)
Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion. Changed in version 3.8: Dictionary views are now reversible.
Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^). An example of dictionary view usage: >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()
>>> # iteration
>>> n = 0
>>> for val in values:
... n += val
>>> print(n)
504
>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'}
{'juice', 'sausage', 'bacon', 'spam'}
Context Manager Types Python’s with statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends:
contextmanager.__enter__()
Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the as clause of with statements using this context manager. An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow open() to be used as the context expression in a with statement. An example of a context manager that returns a related object is the one returned by decimal.localcontext(). These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the with statement without affecting code outside the with statement.
contextmanager.__exit__(exc_type, exc_val, exc_tb)
Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the with statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are None. Returning a true value from this method will cause the with statement to suppress the exception and continue execution with the statement immediately following the with statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement. The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an __exit__() method has actually failed.
Python defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the contextlib module for some examples. Python’s generators and the contextlib.contextmanager decorator provide a convenient way to implement these protocols. If a generator function is decorated with the contextlib.contextmanager decorator, it will return a context manager implementing the necessary __enter__() and __exit__() methods, rather than the iterator produced by an undecorated generator function. Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible. Generic Alias Type GenericAlias objects are created by subscripting a class (usually a container), such as list[int]. They are intended primarily for type annotations. Usually, the subscription of container objects calls the method __getitem__() of the object. However, the subscription of some containers’ classes may call the classmethod __class_getitem__() of the class instead. The classmethod __class_getitem__() should return a GenericAlias object. Note If the __getitem__() of the class’ metaclass is present, it will take precedence over the __class_getitem__() defined in the class (see PEP 560 for more details). The GenericAlias object acts as a proxy for generic types, implementing parameterized generics - a specific instance of a generic which provides the types for container elements. The user-exposed type for the GenericAlias object can be accessed from types.GenericAlias and used for isinstance() checks. It can also be used to create GenericAlias objects directly.
T[X, Y, ...]
Creates a GenericAlias representing a type T containing elements of types X, Y, and more depending on the T used. For example, a function expecting a list containing float elements: def average(values: list[float]) -> float:
return sum(values) / len(values)
Another example for mapping objects, using a dict, which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects a dict with keys of type str and values of type int: def send_post_request(url: str, body: dict[str, int]) -> None:
...
The builtin functions isinstance() and issubclass() do not accept GenericAlias types for their second argument: >>> isinstance([1, 2], list[str])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() argument 2 cannot be a parameterized generic
The Python runtime does not enforce type annotations. This extends to generic types and their type parameters. When creating an object from a GenericAlias, container elements are not checked against their type. For example, the following code is discouraged, but will run without errors: >>> t = list[str]
>>> t([1, 2, 3])
[1, 2, 3]
Furthermore, parameterized generics erase type parameters during object creation: >>> t = list[str]
>>> type(t)
<class 'types.GenericAlias'>
>>> l = t()
>>> type(l)
<class 'list'>
Calling repr() or str() on a generic shows the parameterized type: >>> repr(list[int])
'list[int]'
>>> str(list[int])
'list[int]'
The __getitem__() method of generics will raise an exception to disallow mistakes like dict[str][str]: >>> dict[str][str]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: There are no type variables left in dict[str]
However, such expressions are valid when type variables are used. The index must have as many elements as there are type variable items in the GenericAlias object’s __args__. >>> from typing import TypeVar
>>> Y = TypeVar('Y')
>>> dict[str, Y][int]
dict[str, int]
Standard Generic Collections These standard library collections support parameterized generics. tuple list dict set frozenset type collections.deque collections.defaultdict collections.OrderedDict collections.Counter collections.ChainMap collections.abc.Awaitable collections.abc.Coroutine collections.abc.AsyncIterable collections.abc.AsyncIterator collections.abc.AsyncGenerator collections.abc.Iterable collections.abc.Iterator collections.abc.Generator collections.abc.Reversible collections.abc.Container collections.abc.Collection collections.abc.Callable collections.abc.Set collections.abc.MutableSet collections.abc.Mapping collections.abc.MutableMapping collections.abc.Sequence collections.abc.MutableSequence collections.abc.ByteString collections.abc.MappingView collections.abc.KeysView collections.abc.ItemsView collections.abc.ValuesView contextlib.AbstractContextManager contextlib.AbstractAsyncContextManager re.Pattern re.Match Special Attributes of Generic Alias All parameterized generics implement special read-only attributes.
genericalias.__origin__
This attribute points at the non-parameterized generic class: >>> list[int].__origin__
<class 'list'>
genericalias.__args__
This attribute is a tuple (possibly of length 1) of generic types passed to the original __class_getitem__() of the generic container: >>> dict[str, list[int]].__args__
(<class 'str'>, list[int])
genericalias.__parameters__
This attribute is a lazily computed tuple (possibly empty) of unique type variables found in __args__: >>> from typing import TypeVar
>>> T = TypeVar('T')
>>> list[T].__parameters__
(~T,)
See also
PEP 585 – “Type Hinting Generics In Standard Collections”
__class_getitem__() – Used to implement parameterized generics.
Generics – Generics in the typing module. New in version 3.9. Other Built-in Types The interpreter supports several other kinds of objects. Most of these support only one or two operations. Modules The only special operation on a module is attribute access: m.name, where m is a module and name accesses a name defined in m’s symbol table. Module attributes can be assigned to. (Note that the import statement is not, strictly speaking, an operation on a module object; import
foo does not require a module object named foo to exist, rather it requires an (external) definition for a module named foo somewhere.) A special attribute of every module is __dict__. This is the dictionary containing the module’s symbol table. Modifying this dictionary will actually change the module’s symbol table, but direct assignment to the __dict__ attribute is not possible (you can write m.__dict__['a'] = 1, which defines m.a to be 1, but you can’t write m.__dict__ = {}). Modifying __dict__ directly is not recommended. Modules built into the interpreter are written like this: <module 'sys'
(built-in)>. If loaded from a file, they are written as <module 'os' from
'/usr/local/lib/pythonX.Y/os.pyc'>. Classes and Class Instances See Objects, values and types and Class definitions for these. Functions Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list). There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types. See Function definitions for more information. Methods Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as append() on lists) and class instance methods. Built-in methods are described with the types that support them. If you access a method (a function defined in a class namespace) through an instance, you get a special object: a bound method (also called instance method) object. When called, it will add the self argument to the argument list. Bound methods have two special read-only attributes: m.__self__ is the object on which the method operates, and m.__func__ is the function implementing the method. Calling m(arg-1, arg-2, ..., arg-n) is completely equivalent to calling m.__func__(m.__self__, arg-1, arg-2, ...,
arg-n). Like function objects, bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (meth.__func__), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an AttributeError being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object: >>> class C:
... def method(self):
... pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method' # can't set on the method
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'
See The standard type hierarchy for more information. Code Objects Code objects are used by the implementation to represent “pseudo-compiled” executable Python code such as a function body. They differ from function objects because they don’t contain a reference to their global execution environment. Code objects are returned by the built-in compile() function and can be extracted from function objects through their __code__ attribute. See also the code module. A code object can be executed or evaluated by passing it (instead of a source string) to the exec() or eval() built-in functions. See The standard type hierarchy for more information. Type Objects Type objects represent the various object types. An object’s type is accessed by the built-in function type(). There are no special operations on types. The standard module types defines names for all standard built-in types. Types are written like this: <class 'int'>. The Null Object This object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name). type(None)() produces the same singleton. It is written as None. The Ellipsis Object This object is commonly used by slicing (see Slicings). It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)() produces the Ellipsis singleton. It is written as Ellipsis or .... The NotImplemented Object This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See Comparisons for more information. There is exactly one NotImplemented object. type(NotImplemented)() produces the singleton instance. It is written as NotImplemented. Boolean Values Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above). They are written as False and True, respectively. Internal Objects See The standard type hierarchy for this information. It describes stack frame objects, traceback objects, and slice objects. Special Attributes The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the dir() built-in function.
object.__dict__
A dictionary or other mapping object used to store an object’s (writable) attributes.
instance.__class__
The class to which a class instance belongs.
class.__bases__
The tuple of base classes of a class object.
definition.__name__
The name of the class, function, method, descriptor, or generator instance.
definition.__qualname__
The qualified name of the class, function, method, descriptor, or generator instance. New in version 3.3.
class.__mro__
This attribute is a tuple of classes that are considered when looking for base classes during method resolution.
class.mro()
This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__.
class.__subclasses__()
Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example: >>> int.__subclasses__()
[<class 'bool'>]
Footnotes
1
Additional information on these special methods may be found in the Python Reference Manual (Basic customization).
2
As a consequence, the list [1, 2] is considered equal to [1.0, 2.0], and similarly for tuples.
3
They must have since the parser can’t tell the type of the operands.
4(1,2,3,4)
Cased characters are those with general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase).
5(1,2)
To format only a tuple you should therefore provide a singleton tuple whose only element is the tuple to be formatted. | |
doc_29799 | Returns whether the kernel is stationary. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.