pyorps.utils package

Submodules

pyorps.utils.neighborhood module

PYORPS: An Open-Source Tool for Automated Power Line Routing

References: [1] Hofmann, M., Stetz, T., Kammer, F., Repo, S.: ‘PYORPS: An Open-Source Tool for

Automated Power Line Routing’, CIRED 2025 - 28th Conference and Exhibition on Electricity Distribution, 16 - 19 June 2025, Geneva, Switzerland

[2] Goodchild, M. F.: ‘An evaluation of lattice solutions to the problem of corridor

location’, Environment and Planning A: Economy and Space, 1977, 9, (7), pp 727-738

pyorps.utils.neighborhood.calculate_errors(directions, phi)[source]

Calculate elongation error and maximum deviation for a given set of directions and path angle.

Parameters:
  • directions (List[float]) – Sorted list of all possible move directions in radians

  • phi (float) – The path direction in radians

Returns:

A dictionary with the calculated errors

Return type:

Dict[str, float]

References

[2]

pyorps.utils.neighborhood.elongation_error(theta_j, theta_j_plus_1, phi)[source]

Calculate the elongation error for a lattice path using Goodchild’s formulation.

The elongation error is given by: e(φ) = (sin(θ_{j+1} - φ) + sin(φ - θ_j)) / sin(θ_{j+1} - θ_j)

Parameters:
  • theta_j (float) – Lower adjacent direction in radians

  • theta_j_plus_1 (float) – Upper adjacent direction in radians

  • phi (float) – Path direction in radians

Returns:

The elongation error

Return type:

float

References

[2]

pyorps.utils.neighborhood.find_adjacent_directions(phi, directions)[source]

Find the adjacent directions θ_j and θ_{j+1} such that θ_j < φ < θ_{j+1}.

Parameters:
  • phi (float) – The path direction in radians

  • directions (List[float]) – Sorted list of all possible move directions in radians

Returns:

A tuple (θ_j, θ_{j+1})

Return type:

Tuple[float, float]

pyorps.utils.neighborhood.find_max_errors(directions)[source]

Find the maximum elongation error and maximum deviation for a given set of directions.

Parameters:

directions (List[float]) – Sorted list of all possible move directions in radians

Returns:

A dictionary with the maximum calculated errors

Return type:

Dict[str, float]

pyorps.utils.neighborhood.get_move_directions(moves)[source]

Get all possible move directions in radians for a given move set.

Parameters:

moves (np.ndarray) – Array of move vectors

Returns:

A sorted list of angles in radians [0, 2π)

Return type:

List[float]

pyorps.utils.neighborhood.get_neighborhood_steps(k, directed=True)[source]

Generate the steps for a k-neighborhood.

Parameters:
  • k (Union[int, str]) – The neighborhood parameter (k >= 0)

  • directed (bool) – If True, includes all possible step directions; if False, includes a minimal set of steps that ensures bidirectional connectivity in the graph

Returns:

A numpy array with dtype int8 containing all steps

Return type:

np.ndarray

References

[1]

pyorps.utils.neighborhood.max_deviation(theta_j, theta_j_plus_1, phi)[source]

Calculate the maximum deviation for a lattice path using Goodchild’s formulation.

The maximum deviation is given by: δ(φ) = (sin(θ_{j+1} - φ) * sin(φ - θ_j)) / sin(θ_{j+1} - θ_j)

Parameters:
  • theta_j (float) – Lower adjacent direction in radians

  • theta_j_plus_1 (float) – Upper adjacent direction in radians

  • phi (float) – Path direction in radians

Returns:

The maximum deviation

Return type:

float

References

[2]

pyorps.utils.neighborhood.normalize_angle(angle)[source]

Normalize an angle to the range [0, 2π).

Parameters:

angle (float) – Input angle in radians

Returns:

Normalized angle in the range [0, 2π)

Return type:

float

pyorps.utils.plotting module

PYORPS: An Open-Source Tool for Automated Power Line Routing

Reference: [1] Hofmann, M., Stetz, T., Kammer, F., Repo, S.: ‘PYORPS: An Open-Source Tool for

Automated Power Line Routing’, CIRED 2025 - 28th Conference and Exhibition on Electricity Distribution, 16 - 19 June 2025, Geneva, Switzerland

class pyorps.utils.plotting.Any(*args, **kwargs)[source]

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class pyorps.utils.plotting.Axes(fig, *args, facecolor=None, frameon=True, sharex=None, sharey=None, label='', xscale=None, yscale=None, box_aspect=None, forward_navigation_events='auto', **kwargs)[source]

Bases: _AxesBase

An Axes object encapsulates all the elements of an individual (sub-)plot in a figure.

It contains most of the (sub-)plot elements: ~.axis.Axis, ~.axis.Tick, ~.lines.Line2D, ~.text.Text, ~.patches.Polygon, etc., and sets the coordinate system.

Like all visible elements in a figure, Axes is an .Artist subclass.

The Axes instance supports callbacks through a callbacks attribute which is a ~.cbook.CallbackRegistry instance. The events you can connect to are ‘xlim_changed’ and ‘ylim_changed’ and the callback will be called with func(ax) where ax is the Axes instance.

Note

As a user, you do not instantiate Axes directly, but use Axes creation methods instead; e.g. from .pyplot or .Figure: ~.pyplot.subplots, ~.pyplot.subplot_mosaic or .Figure.add_axes.

class ArtistList(axes, prop_name, valid_types=None, invalid_types=None)

Bases: Sequence

A sublist of Axes children based on their type.

The type-specific children sublists were made immutable in Matplotlib 3.7. In the future these artist lists may be replaced by tuples. Use as if this is a tuple already.

__init__(axes, prop_name, valid_types=None, invalid_types=None)
Parameters:
  • axes (~matplotlib.axes.Axes) – The Axes from which this sublist will pull the children Artists.

  • prop_name (str) – The property name used to access this sublist from the Axes; used to generate deprecation warnings.

  • valid_types (list of type, optional) – A list of types that determine which children will be returned by this sublist. If specified, then the Artists in the sublist must be instances of any of these types. If unspecified, then any type of Artist is valid (unless limited by invalid_types.)

  • invalid_types (tuple, optional) – A list of types that determine which children will not be returned by this sublist. If specified, then Artists in the sublist will never be an instance of these types. Otherwise, no types will be excluded.

count(value) integer -- return number of occurrences of value
index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

__init__(fig, *args, facecolor=None, frameon=True, sharex=None, sharey=None, label='', xscale=None, yscale=None, box_aspect=None, forward_navigation_events='auto', **kwargs)

Build an Axes in a figure.

Parameters:
  • fig (~matplotlib.figure.Figure) – The Axes is built in the .Figure fig.

  • *args

    *args can be a single (left, bottom, width, height) rectangle or a single .Bbox. This specifies the rectangle (in figure coordinates) where the Axes is positioned.

    *args can also consist of three numbers or a single three-digit number; in the latter case, the digits are considered as independent numbers. The numbers are interpreted as (nrows, ncols, index): (nrows, ncols) specifies the size of an array of subplots, and index is the 1-based index of the subplot being created. Finally, *args can also directly be a .SubplotSpec instance.

  • sharex (~matplotlib.axes.Axes, optional) – The x- or y-~.matplotlib.axis is shared with the x- or y-axis in the input ~.axes.Axes. Note that it is not possible to unshare axes.

  • sharey (~matplotlib.axes.Axes, optional) – The x- or y-~.matplotlib.axis is shared with the x- or y-axis in the input ~.axes.Axes. Note that it is not possible to unshare axes.

  • frameon (bool, default: True) – Whether the Axes frame is visible.

  • box_aspect (float, optional) – Set a fixed aspect for the Axes box, i.e. the ratio of height to width. See ~.axes.Axes.set_box_aspect for details.

  • forward_navigation_events (bool or "auto", default: "auto") – Control whether pan/zoom events are passed through to Axes below this one. “auto” is True for axes with an invisible patch and False otherwise.

  • **kwargs

    Other optional keyword arguments:

    Properties: adjustable: {‘box’, ‘datalim’} agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None anchor: (float, float) or {‘C’, ‘SW’, ‘S’, ‘SE’, ‘E’, ‘NE’, …} animated: bool aspect: {‘auto’, ‘equal’} or float autoscale_on: bool autoscalex_on: unknown autoscaley_on: unknown axes_locator: Callable[[Axes, Renderer], Bbox] axisbelow: bool or ‘line’ box_aspect: float or None clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None facecolor or fc: :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure forward_navigation_events: bool or “auto” frame_on: bool gid: str in_layout: bool label: object mouseover: bool navigate: bool navigate_mode: unknown path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: [left, bottom, width, height] or ~matplotlib.transforms.Bbox prop_cycle: ~cycler.Cycler rasterization_zorder: float or None rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None subplotspec: unknown title: str transform: ~matplotlib.transforms.Transform url: str visible: bool xbound: (lower: float, upper: float) xlabel: str xlim: (left: float, right: float) xmargin: float greater than -0.5 xscale: unknown xticklabels: unknown xticks: unknown ybound: (lower: float, upper: float) ylabel: str ylim: (bottom: float, top: float) ymargin: float greater than -0.5 yscale: unknown yticklabels: unknown yticks: unknown zorder: float

Returns:

The new ~.axes.Axes object.

Return type:

~.axes.Axes

acorr(x, *, data=None, **kwargs)[source]

Plot the autocorrelation of x.

Parameters:
  • x (array-like) – Not run through Matplotlib’s unit conversion, so this should be a unit-less array.

  • detrend (callable, default: .mlab.detrend_none (no detrending)) –

    A detrending function applied to x. It must have the signature

    detrend(x: np.ndarray) -> np.ndarray
    

  • normed (bool, default: True) – If True, input vectors are normalised to unit length.

  • usevlines (bool, default: True) –

    Determines the plot style.

    If True, vertical lines are plotted from 0 to the acorr value using .Axes.vlines. Additionally, a horizontal line is plotted at y=0 using .Axes.axhline.

    If False, markers are plotted at the acorr values using .Axes.plot.

  • maxlags (int, default: 10) – Number of lags to show. If None, will return all 2 * len(x) - 1 lags.

  • linestyle (~matplotlib.lines.Line2D property, optional) – The linestyle for plotting the data points. Only used if usevlines is False.

  • marker (str, default: 'o') – The marker for plotting the data points. Only used if usevlines is False.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x

  • **kwargs – Additional parameters are passed to .Axes.vlines and .Axes.axhline if usevlines is True; otherwise they are passed to .Axes.plot.

Returns:

  • lags (array (length ``2*maxlags+1`)`) – The lag vector.

  • c (array  (length ``2*maxlags+1`)`) – The auto correlation vector.

  • line (.LineCollection or .Line2D) – .Artist added to the Axes of the correlation:

    • .LineCollection if usevlines is True.

    • .Line2D if usevlines is False.

  • b (~matplotlib.lines.Line2D or None) – Horizontal line at 0 if usevlines is True None usevlines is False.

Notes

The cross correlation is performed with numpy.correlate with mode = "full".

add_artist(a)

Add an .Artist to the Axes; return the artist.

Use add_artist only for artists for which there is no dedicated “add” method; and if necessary, use a method such as update_datalim to manually update the ~.Axes.dataLim if the artist is to be included in autoscaling.

If no transform has been specified when creating the artist (e.g. artist.get_transform() == None) then the transform is set to ax.transData.

add_callback(func)

Add a callback function that will be called whenever one of the .Artist’s properties changes.

Parameters:

func (callable) –

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:

The observer id associated with the callback. This id can be used for removing the callback with .remove_callback later.

Return type:

int

See also

remove_callback

add_child_axes(ax)

Add an .Axes to the Axes’ children; return the child Axes.

This is the lowlevel version. See .axes.Axes.inset_axes.

add_collection(collection, autolim=True)

Add a .Collection to the Axes; return the collection.

add_container(container)

Add a .Container to the Axes’ containers; return the container.

add_image(image)

Add an .AxesImage to the Axes; return the image.

add_line(line)

Add a .Line2D to the Axes; return the line.

add_patch(p)

Add a .Patch to the Axes; return the patch.

add_table(tab)

Add a .Table to the Axes; return the table.

angle_spectrum(x, *, Fs=None, Fc=None, window=None, pad_to=None, sides=None, data=None, **kwargs)[source]

Plot the angle spectrum.

Compute the angle spectrum (wrapped phase spectrum) of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.

Parameters:
  • x (1-D array or sequence) – Array or sequence containing the data.

  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

  • spectrum (1-D array) – The values for the angle spectrum in radians (real valued).

  • freqs (1-D array) – The frequencies corresponding to the elements in spectrum.

  • line (~matplotlib.lines.Line2D) – The line created by this function.

See also

magnitude_spectrum

Plots the magnitudes of the corresponding frequencies.

phase_spectrum

Plots the unwrapped version of this function.

specgram

Can plot the angle spectrum of segments within the signal in a colormap.

annotate(text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)[source]

Annotate the point xy with text text.

In the simplest form, the text is placed at xy.

Optionally, the text can be displayed in another position xytext. An arrow pointing from the text to the annotated point xy can then be added by defining arrowprops.

Parameters:
  • text (str) – The text of the annotation.

  • xy ((float, float)) – The point (x, y) to annotate. The coordinate system is determined by xycoords.

  • xytext ((float, float), default: *xy*) – The position (x, y) to place the text at. The coordinate system is determined by textcoords.

  • xycoords (single or two-tuple of str or .Artist or .Transform or callable, default: 'data') –

    The coordinate system that xy is given in. The following types of values are supported:

    • One of the following strings:

      Value

      Description

      ’figure points’

      Points from the lower left of the figure

      ’figure pixels’

      Pixels from the lower left of the figure

      ’figure fraction’

      Fraction of figure from lower left

      ’subfigure points’

      Points from the lower left of the subfigure

      ’subfigure pixels’

      Pixels from the lower left of the subfigure

      ’subfigure fraction’

      Fraction of subfigure from lower left

      ’axes points’

      Points from lower left corner of the Axes

      ’axes pixels’

      Pixels from lower left corner of the Axes

      ’axes fraction’

      Fraction of Axes from lower left

      ’data’

      Use the coordinate system of the object being annotated (default)

      ’polar’

      (theta, r) if not native ‘data’ coordinates

      Note that ‘subfigure pixels’ and ‘figure pixels’ are the same for the parent figure, so users who want code that is usable in a subfigure can use ‘subfigure pixels’.

    • An .Artist: xy is interpreted as a fraction of the artist’s ~matplotlib.transforms.Bbox. E.g. (0, 0) would be the lower left corner of the bounding box and (0.5, 1) would be the center top of the bounding box.

    • A .Transform to transform xy to screen coordinates.

    • A function with one of the following signatures:

      def transform(renderer) -> Bbox
      def transform(renderer) -> Transform
      

      where renderer is a .RendererBase subclass.

      The result of the function is interpreted like the .Artist and .Transform cases above.

    • A tuple (xcoords, ycoords) specifying separate coordinate systems for x and y. xcoords and ycoords must each be of one of the above described types.

    See plotting-guide-annotation for more details.

  • textcoords (single or two-tuple of str or .Artist or .Transform or callable, default: value of *xycoords*) –

    The coordinate system that xytext is given in.

    All xycoords values are valid as well as the following strings:

    Value

    Description

    ’offset points’

    Offset, in points, from the xy value

    ’offset pixels’

    Offset, in pixels, from the xy value

    ’offset fontsize’

    Offset, relative to fontsize, from the xy value

  • arrowprops (dict, optional) –

    The properties used to draw a .FancyArrowPatch arrow between the positions xy and xytext. Defaults to None, i.e. no arrow is drawn.

    For historical reasons there are two different ways to specify arrows, “simple” and “fancy”:

    Simple arrow:

    If arrowprops does not contain the key ‘arrowstyle’ the allowed keys are:

    Key

    Description

    width

    The width of the arrow in points

    headwidth

    The width of the base of the arrow head in points

    headlength

    The length of the arrow head in points

    shrink

    Fraction of total length to shrink from both ends

    ?

    Any .FancyArrowPatch property

    The arrow is attached to the edge of the text box, the exact position (corners or centers) depending on where it’s pointing to.

    Fancy arrow:

    This is used if ‘arrowstyle’ is provided in the arrowprops.

    Valid keys are the following .FancyArrowPatch parameters:

    Key

    Description

    arrowstyle

    The arrow style

    connectionstyle

    The connection style

    relpos

    See below; default is (0.5, 0.5)

    patchA

    Default is bounding box of the text

    patchB

    Default is None

    shrinkA

    In points. Default is 2 points

    shrinkB

    In points. Default is 2 points

    mutation_scale

    Default is text size (in points)

    mutation_aspect

    Default is 1

    ?

    Any .FancyArrowPatch property

    The exact starting point position of the arrow is defined by relpos. It’s a tuple of relative coordinates of the text box, where (0, 0) is the lower left corner and (1, 1) is the upper right corner. Values <0 and >1 are supported and specify points outside the text box. By default (0.5, 0.5), so the starting point is centered in the text box.

  • annotation_clip (bool or None, default: None) –

    Whether to clip (i.e. not draw) the annotation when the annotation point xy is outside the Axes area.

    • If True, the annotation will be clipped when xy is outside the Axes.

    • If False, the annotation will always be drawn.

    • If None, the annotation will be clipped when xy is outside the Axes and xycoords is ‘data’.

  • **kwargs – Additional kwargs are passed to .Text.

Return type:

.Annotation

See also

annotations

apply_aspect(position=None)

Adjust the Axes for a specified data aspect ratio.

Depending on .get_adjustable this will modify either the Axes box (position) or the view limits. In the former case, ~matplotlib.axes.Axes.get_anchor will affect the position.

Parameters:

position (None or Bbox) –

Note

This parameter exists for historic reasons and is considered internal. End users should not use it.

If not None, this defines the position of the Axes within the figure as a Bbox. See ~.Axes.get_position for further details.

Notes

This is called automatically when each Axes is drawn. You may need to call it yourself if you need to update the Axes position and/or view limits before the Figure is drawn.

An alternative with a broader scope is .Figure.draw_without_rendering, which updates all stale components of a figure, not only the positioning / view limits of a single Axes.

See also

matplotlib.axes.Axes.set_aspect

For a description of aspect ratio handling.

matplotlib.axes.Axes.set_adjustable

Set how the Axes adjusts to achieve the required aspect ratio.

matplotlib.axes.Axes.set_anchor

Set the position in case of extra space.

matplotlib.figure.Figure.draw_without_rendering

Update all stale components of a figure.

Examples

A typical usage example would be the following. ~.Axes.imshow sets the aspect to 1, but adapting the Axes position and extent to reflect this is deferred until rendering for performance reasons. If you want to know the Axes size before, you need to call .apply_aspect to get the correct values.

>>> fig, ax = plt.subplots()
>>> ax.imshow(np.zeros((3, 3)))
>>> ax.bbox.width, ax.bbox.height
(496.0, 369.59999999999997)
>>> ax.apply_aspect()
>>> ax.bbox.width, ax.bbox.height
(369.59999999999997, 369.59999999999997)
arrow(x, y, dx, dy, **kwargs)[source]

[Discouraged] Add an arrow to the Axes.

This draws an arrow from (x, y) to (x+dx, y+dy).

Discouraged

The use of this method is discouraged because it is not guaranteed that the arrow renders reasonably. For example, the resulting arrow is affected by the Axes aspect ratio and limits, which may distort the arrow.

Consider using ~.Axes.annotate without a text instead, e.g.

ax.annotate("", xytext=(0, 0), xy=(0.5, 0.5),
            arrowprops=dict(arrowstyle="->"))
Parameters:
  • x (float) – The x and y coordinates of the arrow base.

  • y (float) – The x and y coordinates of the arrow base.

  • dx (float) – The length of the arrow along x and y direction.

  • dy (float) – The length of the arrow along x and y direction.

  • width (float, default: 0.001) – Width of full arrow tail.

  • length_includes_head (bool, default: False) – True if head is to be counted in calculating the length.

  • head_width (float or None, default: 3*width) – Total width of the full arrow head.

  • head_length (float or None, default: 1.5*head_width) – Length of arrow head.

  • shape ({'full', 'left', 'right'}, default: 'full') – Draw the left-half, right-half, or full arrow.

  • overhang (float, default: 0) – Fraction that the arrow is swept back (0 overhang means triangular shape). Can be negative or greater than one.

  • head_starts_at_zero (bool, default: False) – If True, the head starts being drawn at coordinate 0 instead of ending at coordinate 0.

  • **kwargs

    .Patch properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: unknown animated: bool antialiased or aa: bool or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float

Returns:

The created .FancyArrow object.

Return type:

.FancyArrow

property artists
autoscale(enable=True, axis='both', tight=None)

Autoscale the axis view to the data (toggle).

Convenience method for simple axis view autoscaling. It turns autoscaling on or off, and then, if autoscaling for either axis is on, it performs the autoscaling on the specified axis or Axes.

Parameters:
  • enable (bool or None, default: True) – True turns autoscaling on, False turns it off. None leaves the autoscaling state unchanged.

  • axis ({'both', 'x', 'y'}, default: 'both') – The axis on which to operate. (For 3D Axes, axis can also be set to ‘z’, and ‘both’ refers to all three Axes.)

  • tight (bool or None, default: None) – If True, first set the margins to zero. Then, this argument is forwarded to ~.axes.Axes.autoscale_view (regardless of its value); see the description of its behavior there.

autoscale_view(tight=None, scalex=True, scaley=True)

Autoscale the view limits using the data limits.

Parameters:
  • tight (bool or None) –

    If True, only expand the axis limits using the margins. Note that unlike for autoscale, tight=True does not set the margins to zero.

    If False and :rc:`axes.autolimit_mode` is ‘round_numbers’, then after expansion by the margins, further expand the axis limits using the axis major locator.

    If None (the default), reuse the value set in the previous call to autoscale_view (the initial value is False, but the default style sets :rc:`axes.autolimit_mode` to ‘data’, in which case this behaves like True).

  • scalex (bool, default: True) – Whether to autoscale the x-axis.

  • scaley (bool, default: True) – Whether to autoscale the y-axis.

Notes

The autoscaling preserves any preexisting axis direction reversal.

The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. In that case, use matplotlib.axes.Axes.relim() prior to calling autoscale_view.

If the views of the Axes are fixed, e.g. via set_xlim, they will not be changed by autoscale_view(). See matplotlib.axes.Axes.autoscale() for an alternative.

property axes

The ~.axes.Axes instance the artist resides in, or None.

axhline(y=0, xmin=0, xmax=1, **kwargs)[source]

Add a horizontal line spanning the whole or fraction of the Axes.

Note: If you want to set x-limits in data coordinates, use ~.Axes.hlines instead.

Parameters:
  • y (float, default: 0) – y position in data coordinates.

  • xmin (float, default: 0) – The start x-position in axes coordinates. Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.

  • xmax (float, default: 1) – The end x-position in axes coordinates. Should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.

  • **kwargs

    Valid keyword arguments are .Line2D properties, except for ‘transform’:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

A .Line2D specified via two points (xmin, y), (xmax, y). Its transform is set such that x is in axes coordinates and y is in data coordinates.

This is still a generic line and the horizontal character is only realized through using identical y values for both points. Thus, if you want to change the y value later, you have to provide two values line.set_ydata([3, 3]).

Return type:

~matplotlib.lines.Line2D

See also

hlines

Add horizontal lines in data coordinates.

axhspan

Add a horizontal span (rectangle) across the axis.

axline

Add a line with an arbitrary slope.

Examples

  • draw a thick red hline at ‘y’ = 0 that spans the xrange:

    >>> axhline(linewidth=4, color='r')
    
  • draw a default hline at ‘y’ = 1 that spans the xrange:

    >>> axhline(y=1)
    
  • draw a default hline at ‘y’ = .5 that spans the middle half of the xrange:

    >>> axhline(y=.5, xmin=0.25, xmax=0.75)
    
axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs)[source]

Add a horizontal span (rectangle) across the Axes.

The rectangle spans from ymin to ymax vertically, and, by default, the whole x-axis horizontally. The x-span can be set using xmin (default: 0) and xmax (default: 1) which are in axis units; e.g. xmin = 0.5 always refers to the middle of the x-axis regardless of the limits set by ~.Axes.set_xlim.

Parameters:
  • ymin (float) – Lower y-coordinate of the span, in data units.

  • ymax (float) – Upper y-coordinate of the span, in data units.

  • xmin (float, default: 0) – Lower x-coordinate of the span, in x-axis (0-1) units.

  • xmax (float, default: 1) – Upper x-coordinate of the span, in x-axis (0-1) units.

  • **kwargs (~matplotlib.patches.Rectangle properties)

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

Returns:

Horizontal span (rectangle) from (xmin, ymin) to (xmax, ymax).

Return type:

~matplotlib.patches.Rectangle

See also

axvspan

Add a vertical span across the Axes.

axis(arg=None, /, *, emit=True, **kwargs)

Convenience method to get or set some axis properties.

Call signatures:

xmin, xmax, ymin, ymax = axis()
xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax])
xmin, xmax, ymin, ymax = axis(option)
xmin, xmax, ymin, ymax = axis(**kwargs)
Parameters:
  • xmin (float, optional) –

    The axis limits to be set. This can also be achieved using

    ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
    

  • xmax (float, optional) –

    The axis limits to be set. This can also be achieved using

    ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
    

  • ymin (float, optional) –

    The axis limits to be set. This can also be achieved using

    ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
    

  • ymax (float, optional) –

    The axis limits to be set. This can also be achieved using

    ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
    

  • option (bool or str) –

    If a bool, turns axis lines and labels on or off. If a string, possible values are:

    Value

    Description

    ’off’ or False

    Hide all axis decorations, i.e. axis labels, spines, tick marks, tick labels, and grid lines. This is the same as ~.Axes.set_axis_off().

    ’on’ or True

    Do not hide all axis decorations, i.e. axis labels, spines, tick marks, tick labels, and grid lines. This is the same as ~.Axes.set_axis_on().

    ’equal’

    Set equal scaling (i.e., make circles circular) by changing the axis limits. This is the same as ax.set_aspect('equal', adjustable='datalim'). Explicit data limits may not be respected in this case.

    ’scaled’

    Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box. This is the same as ax.set_aspect('equal', adjustable='box', anchor='C'). Additionally, further autoscaling will be disabled.

    ’tight’

    Set limits just large enough to show all data, then disable further autoscaling.

    ’auto’

    Automatic scaling (fill plot box with data).

    ’image’

    ’scaled’ with axis limits equal to data limits.

    ’square’

    Square plot; similar to ‘scaled’, but initially forcing xmax-xmin == ymax-ymin.

  • emit (bool, default: True) – Whether observers are notified of the axis limit change. This option is passed on to ~.Axes.set_xlim and ~.Axes.set_ylim.

Returns:

xmin, xmax, ymin, ymax – The axis limits.

Return type:

float

See also

matplotlib.axes.Axes.set_xlim, matplotlib.axes.Axes.set_ylim

Notes

For 3D Axes, this method additionally takes zmin, zmax as parameters and likewise returns them.

axline(xy1, xy2=None, *, slope=None, **kwargs)[source]

Add an infinitely long straight line.

The line can be defined either by two points xy1 and xy2, or by one point xy1 and a slope.

This draws a straight line “on the screen”, regardless of the x and y scales, and is thus also suitable for drawing exponential decays in semilog plots, power laws in loglog plots, etc. However, slope should only be used with linear scales; It has no clear meaning for all other scales, and thus the behavior is undefined. Please specify the line using the points xy1, xy2 for non-linear scales.

The transform keyword argument only applies to the points xy1, xy2. The slope (if given) is always in data coordinates. This can be used e.g. with ax.transAxes for drawing grid lines with a fixed slope.

Parameters:
  • xy1 ((float, float)) – Points for the line to pass through. Either xy2 or slope has to be given.

  • xy2 ((float, float)) – Points for the line to pass through. Either xy2 or slope has to be given.

  • slope (float, optional) – The slope of the line. Either xy2 or slope has to be given.

  • **kwargs

    Valid kwargs are .Line2D properties

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Return type:

.AxLine

See also

axhline

for horizontal lines

axvline

for vertical lines

Examples

Draw a thick red line passing through (0, 0) and (1, 1):

>>> axline((0, 0), (1, 1), linewidth=4, color='r')
axvline(x=0, ymin=0, ymax=1, **kwargs)[source]

Add a vertical line spanning the whole or fraction of the Axes.

Note: If you want to set y-limits in data coordinates, use ~.Axes.vlines instead.

Parameters:
  • x (float, default: 0) – x position in data coordinates.

  • ymin (float, default: 0) – The start y-position in axes coordinates. Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

  • ymax (float, default: 1) – The end y-position in axes coordinates. Should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.

  • **kwargs

    Valid keyword arguments are .Line2D properties, except for ‘transform’:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

A .Line2D specified via two points (x, ymin), (x, ymax). Its transform is set such that x is in data coordinates and y is in axes coordinates.

This is still a generic line and the vertical character is only realized through using identical x values for both points. Thus, if you want to change the x value later, you have to provide two values line.set_xdata([3, 3]).

Return type:

~matplotlib.lines.Line2D

See also

vlines

Add vertical lines in data coordinates.

axvspan

Add a vertical span (rectangle) across the axis.

axline

Add a line with an arbitrary slope.

Examples

  • draw a thick red vline at x = 0 that spans the yrange:

    >>> axvline(linewidth=4, color='r')
    
  • draw a default vline at x = 1 that spans the yrange:

    >>> axvline(x=1)
    
  • draw a default vline at x = .5 that spans the middle half of the yrange:

    >>> axvline(x=.5, ymin=0.25, ymax=0.75)
    
axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)[source]

Add a vertical span (rectangle) across the Axes.

The rectangle spans from xmin to xmax horizontally, and, by default, the whole y-axis vertically. The y-span can be set using ymin (default: 0) and ymax (default: 1) which are in axis units; e.g. ymin = 0.5 always refers to the middle of the y-axis regardless of the limits set by ~.Axes.set_ylim.

Parameters:
  • xmin (float) – Lower x-coordinate of the span, in data units.

  • xmax (float) – Upper x-coordinate of the span, in data units.

  • ymin (float, default: 0) – Lower y-coordinate of the span, in y-axis units (0-1).

  • ymax (float, default: 1) – Upper y-coordinate of the span, in y-axis units (0-1).

  • **kwargs (~matplotlib.patches.Rectangle properties)

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

Returns:

Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax).

Return type:

~matplotlib.patches.Rectangle

See also

axhspan

Add a horizontal span across the Axes.

Examples

Draw a vertical, green, translucent rectangle from x = 1.25 to x = 1.55 that spans the yrange of the Axes.

>>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)[source]

Make a bar plot.

The bars are positioned at x with the given alignment. Their dimensions are given by height and width. The vertical baseline is bottom (default 0).

Many parameters can take either a single value applying to all bars or a sequence of values, one for each bar.

Parameters:
  • x (float or array-like) –

    The x coordinates of the bars. See also align for the alignment of the bars to the coordinates.

    Bars are often used for categorical data, i.e. string labels below the bars. You can provide a list of strings directly to x. bar(['A', 'B', 'C'], [1, 2, 3]) is often a shorter and more convenient notation compared to bar(range(3), [1, 2, 3], tick_label=['A', 'B', 'C']). They are equivalent as long as the names are unique. The explicit tick_label notation draws the names in the sequence given. However, when having duplicate values in categorical x data, these values map to the same numerical x coordinate, and hence the corresponding bars are drawn on top of each other.

  • height (float or array-like) –

    The height(s) of the bars.

    Note that if bottom has units (e.g. datetime), height should be in units that are a difference from the value of bottom (e.g. timedelta).

  • width (float or array-like, default: 0.8) –

    The width(s) of the bars.

    Note that if x has units (e.g. datetime), then width should be in units that are a difference (e.g. timedelta) around the x values.

  • bottom (float or array-like, default: 0) –

    The y coordinate(s) of the bottom side(s) of the bars.

    Note that if bottom has units, then the y-axis will get a Locator and Formatter appropriate for the units (e.g. dates, or categorical).

  • align ({'center', 'edge'}, default: 'center') –

    Alignment of the bars to the x coordinates:

    • ’center’: Center the base on the x positions.

    • ’edge’: Align the left edges of the bars with the x positions.

    To align the bars on the right edge pass a negative width and align='edge'.

  • color (:mpltype:`color` or list of :mpltype:`color`, optional) – The colors of the bar faces. This is an alias for facecolor. If both are given, facecolor takes precedence.

  • facecolor (:mpltype:`color` or list of :mpltype:`color`, optional) – The colors of the bar faces. If both color and facecolor are given, *facecolor takes precedence.

  • edgecolor (:mpltype:`color` or list of :mpltype:`color`, optional) – The colors of the bar edges.

  • linewidth (float or array-like, optional) – Width of the bar edge(s). If 0, don’t draw edges.

  • tick_label (str or list of str, optional) – The tick labels of the bars. Default: None (Use default numeric labels.)

  • label (str or list of str, optional) – A single label is attached to the resulting .BarContainer as a label for the whole dataset. If a list is provided, it must be the same length as x and labels the individual bars. Repeated labels are not de-duplicated and will cause repeated label entries, so this is best used when bars also differ in style (e.g., by passing a list to color.)

  • xerr (float or array-like of shape(N,) or shape(2, N), optional) –

    If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:

    • scalar: symmetric +/- values for all bars

    • shape(N,): symmetric +/- values for each bar

    • shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.

    • None: No errorbar. (Default)

    See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.

  • yerr (float or array-like of shape(N,) or shape(2, N), optional) –

    If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:

    • scalar: symmetric +/- values for all bars

    • shape(N,): symmetric +/- values for each bar

    • shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.

    • None: No errorbar. (Default)

    See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.

  • ecolor (:mpltype:`color` or list of :mpltype:`color`, default: 'black') – The line color of the errorbars.

  • capsize (float, default: :rc:`errorbar.capsize`) – The length of the error bar caps in points.

  • error_kw (dict, optional) – Dictionary of keyword arguments to be passed to the ~.Axes.errorbar method. Values of ecolor or capsize defined here take precedence over the independent keyword arguments.

  • log (bool, default: False) – If True, set the y-axis to be log scale.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs (.Rectangle properties)

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

Returns:

Container with all the bars and optionally errorbars.

Return type:

.BarContainer

See also

barh

Plot a horizontal bar plot.

Notes

Stacked bars can be achieved by passing individual bottom values per bar. See /gallery/lines_bars_and_markers/bar_stacked.

bar_label(container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs)[source]

Label a bar plot.

Adds labels to bars in the given .BarContainer. You may need to adjust the axis limits to fit the labels.

Parameters:
  • container (.BarContainer) – Container with all the bars and optionally errorbars, likely returned from .bar or .barh.

  • labels (array-like, optional) – A list of label texts, that should be displayed. If not given, the label texts will be the data values formatted with fmt.

  • fmt (str or callable, default: '%g') –

    An unnamed %-style or {}-style format string for the label or a function to call with the value as the first argument. When fmt is a string and can be interpreted in both formats, %-style takes precedence over {}-style.

    Added in version 3.7: Support for {}-style format string and callables.

  • label_type ({'edge', 'center'}, default: 'edge') –

    The label type. Possible values:

    • ’edge’: label placed at the end-point of the bar segment, and the value displayed will be the position of that end-point.

    • ’center’: label placed in the center of the bar segment, and the value displayed will be the length of that segment. (useful for stacked bars, i.e., /gallery/lines_bars_and_markers/bar_label_demo)

  • padding (float, default: 0) – Distance of label from the end of the bar, in points.

  • **kwargs – Any remaining keyword arguments are passed through to .Axes.annotate. The alignment parameters ( horizontalalignment / ha, verticalalignment / va) are not supported because the labels are automatically aligned to the bars.

Returns:

A list of .Annotation instances for the labels.

Return type:

list of .Annotation

barbs(*args, data=None, **kwargs)[source]

Plot a 2D field of wind barbs.

Call signature:

barbs([X, Y], U, V, [C], /, **kwargs)

Where X, Y define the barb locations, U, V define the barb directions, and C optionally sets the color.

The arguments X, Y, U, V, C are positional-only and may be 1D or 2D. U, V, C may be masked arrays, but masked X, Y are not supported at present.

Barbs are traditionally used in meteorology as a way to plot the speed and direction of wind observations, but can technically be used to plot any two dimensional vector quantity. As opposed to arrows, which give vector magnitude by the length of the arrow, the barbs give more quantitative information about the vector magnitude by putting slanted lines or a triangle for various increments in magnitude, as show schematically below:

:                   /\    \
:                  /  \    \
:                 /    \    \    \
:                /      \    \    \
:               ------------------------------

The largest increment is given by a triangle (or “flag”). After those come full lines (barbs). The smallest increment is a half line. There is only, of course, ever at most 1 half line. If the magnitude is small and only needs a single half-line and no full lines or triangles, the half-line is offset from the end of the barb so that it can be easily distinguished from barbs with a single full line. The magnitude for the barb shown above would nominally be 65, using the standard increments of 50, 10, and 5.

See also https://en.wikipedia.org/wiki/Wind_barb.

Parameters:
  • X (1D or 2D array-like, optional) –

    The x and y coordinates of the barb locations. See pivot for how the barbs are drawn to the x, y positions.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • Y (1D or 2D array-like, optional) –

    The x and y coordinates of the barb locations. See pivot for how the barbs are drawn to the x, y positions.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • U (1D or 2D array-like) – The x and y components of the barb shaft.

  • V (1D or 2D array-like) – The x and y components of the barb shaft.

  • C (1D or 2D array-like, optional) –

    Numeric data that defines the barb colors by colormapping via norm and cmap.

    This does not support explicit colors. If you want to set colors directly, use barbcolor instead.

  • length (float, default: 7) – Length of the barb in points; the other parts of the barb are scaled against this.

  • pivot ({'tip', 'middle'} or float, default: 'tip') – The part of the arrow that is anchored to the X, Y grid. The barb rotates about this point. This can also be a number, which shifts the start of the barb that many points away from grid point.

  • barbcolor (:mpltype:`color` or color sequence) – The color of all parts of the barb except for the flags. This parameter is analogous to the edgecolor parameter for polygons, which can be used instead. However this parameter will override facecolor.

  • flagcolor (:mpltype:`color` or color sequence) – The color of any flags on the barb. This parameter is analogous to the facecolor parameter for polygons, which can be used instead. However, this parameter will override facecolor. If this is not set (and C has not either) then flagcolor will be set to match barbcolor so that the barb has a uniform color. If C has been set, flagcolor has no effect.

  • sizes (dict, optional) –

    A dictionary of coefficients specifying the ratio of a given feature to the length of the barb. Only those values one wishes to override need to be included. These features include:

    • ’spacing’ - space between features (flags, full/half barbs)

    • ’height’ - height (distance from shaft to top) of a flag or full barb

    • ’width’ - width of a flag, twice the width of a full barb

    • ’emptybarb’ - radius of the circle used for low magnitudes

  • fill_empty (bool, default: False) – Whether the empty barbs (circles) that are drawn should be filled with the flag color. If they are not filled, the center is transparent.

  • rounding (bool, default: True) – Whether the vector magnitude should be rounded when allocating barb components. If True, the magnitude is rounded to the nearest multiple of the half-barb increment. If False, the magnitude is simply truncated to the next lowest multiple.

  • barb_increments (dict, optional) –

    A dictionary of increments specifying values to associate with different parts of the barb. Only those values one wishes to override need to be included.

    • ’half’ - half barbs (Default is 5)

    • ’full’ - full barbs (Default is 10)

    • ’flag’ - flags (default is 50)

  • flip_barb (bool or array-like of bool, default: False) –

    Whether the lines and flags should point opposite to normal. Normal behavior is for the barbs and lines to point right (comes from wind barbs having these features point towards low pressure in the Northern Hemisphere).

    A single value is applied to all barbs. Individual barbs can be flipped by passing a bool array of the same size as U and V.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs

    The barbs can further be customized using .PolyCollection keyword arguments:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Returns:

barbs

Return type:

~matplotlib.quiver.Barbs

barh(y, width, height=0.8, left=None, *, align='center', data=None, **kwargs)[source]

Make a horizontal bar plot.

The bars are positioned at y with the given alignment. Their dimensions are given by width and height. The horizontal baseline is left (default 0).

Many parameters can take either a single value applying to all bars or a sequence of values, one for each bar.

Parameters:
  • y (float or array-like) –

    The y coordinates of the bars. See also align for the alignment of the bars to the coordinates.

    Bars are often used for categorical data, i.e. string labels below the bars. You can provide a list of strings directly to y. barh(['A', 'B', 'C'], [1, 2, 3]) is often a shorter and more convenient notation compared to barh(range(3), [1, 2, 3], tick_label=['A', 'B', 'C']). They are equivalent as long as the names are unique. The explicit tick_label notation draws the names in the sequence given. However, when having duplicate values in categorical y data, these values map to the same numerical y coordinate, and hence the corresponding bars are drawn on top of each other.

  • width (float or array-like) –

    The width(s) of the bars.

    Note that if left has units (e.g. datetime), width should be in units that are a difference from the value of left (e.g. timedelta).

  • height (float or array-like, default: 0.8) –

    The heights of the bars.

    Note that if y has units (e.g. datetime), then height should be in units that are a difference (e.g. timedelta) around the y values.

  • left (float or array-like, default: 0) –

    The x coordinates of the left side(s) of the bars.

    Note that if left has units, then the x-axis will get a Locator and Formatter appropriate for the units (e.g. dates, or categorical).

  • align ({'center', 'edge'}, default: 'center') –

    Alignment of the base to the y coordinates*:

    • ’center’: Center the bars on the y positions.

    • ’edge’: Align the bottom edges of the bars with the y positions.

    To align the bars on the top edge pass a negative height and align='edge'.

  • color (:mpltype:`color` or list of :mpltype:`color`, optional) – The colors of the bar faces.

  • edgecolor (:mpltype:`color` or list of :mpltype:`color`, optional) – The colors of the bar edges.

  • linewidth (float or array-like, optional) – Width of the bar edge(s). If 0, don’t draw edges.

  • tick_label (str or list of str, optional) – The tick labels of the bars. Default: None (Use default numeric labels.)

  • label (str or list of str, optional) – A single label is attached to the resulting .BarContainer as a label for the whole dataset. If a list is provided, it must be the same length as y and labels the individual bars. Repeated labels are not de-duplicated and will cause repeated label entries, so this is best used when bars also differ in style (e.g., by passing a list to color.)

  • xerr (float or array-like of shape(N,) or shape(2, N), optional) –

    If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:

    • scalar: symmetric +/- values for all bars

    • shape(N,): symmetric +/- values for each bar

    • shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.

    • None: No errorbar. (default)

    See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.

  • yerr (float or array-like of shape(N,) or shape(2, N), optional) –

    If not None, add horizontal / vertical errorbars to the bar tips. The values are +/- sizes relative to the data:

    • scalar: symmetric +/- values for all bars

    • shape(N,): symmetric +/- values for each bar

    • shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.

    • None: No errorbar. (default)

    See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.

  • ecolor (:mpltype:`color` or list of :mpltype:`color`, default: 'black') – The line color of the errorbars.

  • capsize (float, default: :rc:`errorbar.capsize`) – The length of the error bar caps in points.

  • error_kw (dict, optional) – Dictionary of keyword arguments to be passed to the ~.Axes.errorbar method. Values of ecolor or capsize defined here take precedence over the independent keyword arguments.

  • log (bool, default: False) – If True, set the x-axis to be log scale.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs (.Rectangle properties)

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

Returns:

Container with all the bars and optionally errorbars.

Return type:

.BarContainer

See also

bar

Plot a vertical bar plot.

Notes

Stacked bars can be achieved by passing individual left values per bar. See /gallery/lines_bars_and_markers/horizontal_barchart_distribution.

boxplot(x, *, notch=None, sym=None, vert=None, orientation='vertical', whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, tick_labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, capwidths=None, label=None, data=None)[source]

Draw a box and whisker plot.

The box extends from the first quartile (Q1) to the third quartile (Q3) of the data, with a line at the median. The whiskers extend from the box to the farthest data point lying within 1.5x the inter-quartile range (IQR) from the box. Flier points are those past the end of the whiskers. See https://en.wikipedia.org/wiki/Box_plot for reference.

     Q1-1.5IQR   Q1   median  Q3   Q3+1.5IQR
                  |-----:-----|
  o      |--------|     :     |--------|    o  o
                  |-----:-----|
flier             <----------->            fliers
                       IQR
Parameters:
  • x (Array or a sequence of vectors.) – The input data. If a 2D array, a boxplot is drawn for each column in x. If a sequence of 1D arrays, a boxplot is drawn for each array in x.

  • notch (bool, default: :rc:`boxplot.notch`) –

    Whether to draw a notched boxplot (True), or a rectangular boxplot (False). The notches represent the confidence interval (CI) around the median. The documentation for bootstrap describes how the locations of the notches are computed by default, but their locations may also be overridden by setting the conf_intervals parameter.

    Note

    In cases where the values of the CI are less than the lower quartile or greater than the upper quartile, the notches will extend beyond the box, giving it a distinctive “flipped” appearance. This is expected behavior and consistent with other statistical visualization packages.

  • sym (str, optional) – The default symbol for flier points. An empty string (‘’) hides the fliers. If None, then the fliers default to ‘b+’. More control is provided by the flierprops parameter.

  • vert (bool, optional) –

    Deprecated since version 3.11: Use orientation instead.

    This is a pending deprecation for 3.10, with full deprecation in 3.11 and removal in 3.13. If this is given during the deprecation period, it overrides the orientation parameter.

    If True, plots the boxes vertically. If False, plots the boxes horizontally.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') –

    If ‘horizontal’, plots the boxes horizontally. Otherwise, plots the boxes vertically.

    Added in version 3.10.

  • whis (float or (float, float), default: 1.5) –

    The position of the whiskers.

    If a float, the lower whisker is at the lowest datum above Q1 - whis*(Q3-Q1), and the upper whisker at the highest datum below Q3 + whis*(Q3-Q1), where Q1 and Q3 are the first and third quartiles. The default value of whis = 1.5 corresponds to Tukey’s original definition of boxplots.

    If a pair of floats, they indicate the percentiles at which to draw the whiskers (e.g., (5, 95)). In particular, setting this to (0, 100) results in whiskers covering the whole range of the data.

    In the edge case where Q1 == Q3, whis is automatically set to (0, 100) (cover the whole range of the data) if autorange is True.

    Beyond the whiskers, data are considered outliers and are plotted as individual points.

  • bootstrap (int, optional) – Specifies whether to bootstrap the confidence intervals around the median for notched boxplots. If bootstrap is None, no bootstrapping is performed, and notches are calculated using a Gaussian-based asymptotic approximation (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and Kendall and Stuart, 1967). Otherwise, bootstrap specifies the number of times to bootstrap the median to determine its 95% confidence intervals. Values between 1000 and 10000 are recommended.

  • usermedians (1D array-like, optional) – A 1D array-like of length len(x). Each entry that is not None forces the value of the median for the corresponding dataset. For entries that are None, the medians are computed by Matplotlib as normal.

  • conf_intervals (array-like, optional) – A 2D array-like of shape (len(x), 2). Each entry that is not None forces the location of the corresponding notch (which is only drawn if notch is True). For entries that are None, the notches are computed by the method specified by the other parameters (e.g., bootstrap).

  • positions (array-like, optional) – The positions of the boxes. The ticks and limits are automatically set to match the positions. Defaults to range(1, N+1) where N is the number of boxes to be drawn.

  • widths (float or array-like) – The widths of the boxes. The default is 0.5, or 0.15*(distance between extreme positions), if that is smaller.

  • patch_artist (bool, default: :rc:`boxplot.patchartist`) – If False produces boxes with the Line2D artist. Otherwise, boxes are drawn with Patch artists.

  • tick_labels (list of str, optional) –

    The tick labels of each boxplot. Ticks are always placed at the box positions. If tick_labels is given, the ticks are labelled accordingly. Otherwise, they keep their numeric values.

    Changed in version 3.9: Renamed from labels, which is deprecated since 3.9 and will be removed in 3.11.

  • manage_ticks (bool, default: True) – If True, the tick locations and labels will be adjusted to match the boxplot positions.

  • autorange (bool, default: False) – When True and the data are distributed such that the 25th and 75th percentiles are equal, whis is set to (0, 100) such that the whisker ends are at the minimum and maximum of the data.

  • meanline (bool, default: :rc:`boxplot.meanline`) – If True (and showmeans is True), will try to render the mean as a line spanning the full width of the box according to meanprops (see below). Not recommended if shownotches is also True. Otherwise, means will be shown as points.

  • zorder (float, default: Line2D.zorder = 2) – The zorder of the boxplot.

  • showcaps (bool, default: :rc:`boxplot.showcaps`) – Show the caps on the ends of whiskers.

  • showbox (bool, default: :rc:`boxplot.showbox`) – Show the central box.

  • showfliers (bool, default: :rc:`boxplot.showfliers`) – Show the outliers beyond the caps.

  • showmeans (bool, default: :rc:`boxplot.showmeans`) – Show the arithmetic means.

  • capprops (dict, default: None) – The style of the caps.

  • capwidths (float or array, default: None) – The widths of the caps.

  • boxprops (dict, default: None) – The style of the box.

  • whiskerprops (dict, default: None) – The style of the whiskers.

  • flierprops (dict, default: None) – The style of the fliers.

  • medianprops (dict, default: None) – The style of the median.

  • meanprops (dict, default: None) – The style of the mean.

  • label (str or list of str, optional) –

    Legend labels. Use a single string when all boxes have the same style and you only want a single legend entry for them. Use a list of strings to label all boxes individually. To be distinguishable, the boxes should be styled individually, which is currently only possible by modifying the returned artists, see e.g. /gallery/statistics/boxplot_demo.

    In the case of a single string, the legend entry will technically be associated with the first box only. By default, the legend will show the median line (result["medians"]); if patch_artist is True, the legend will show the box .Patch artists (result["boxes"]) instead.

    Added in version 3.9.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

Returns:

A dictionary mapping each component of the boxplot to a list of the .Line2D instances created. That dictionary has the following keys (assuming vertical boxplots):

  • boxes: the main body of the boxplot showing the quartiles and the median’s confidence intervals if enabled.

  • medians: horizontal lines at the median of each box.

  • whiskers: the vertical lines extending to the most extreme, non-outlier data points.

  • caps: the horizontal lines at the ends of the whiskers.

  • fliers: points representing data that extend beyond the whiskers (fliers).

  • means: points or lines representing the means.

Return type:

dict

See also

Axes.bxp

Draw a boxplot from pre-computed statistics.

violinplot

Draw an estimate of the probability density function.

broken_barh(xranges, yrange, *, data=None, **kwargs)[source]

Plot a horizontal sequence of rectangles.

A rectangle is drawn for each element of xranges. All rectangles have the same vertical position and size defined by yrange.

Parameters:
  • xranges (sequence of tuples (*xmin*, *xwidth*)) – The x-positions and extents of the rectangles. For each tuple (xmin, xwidth) a rectangle is drawn from xmin to xmin + xwidth.

  • yrange ((*ymin*, *yheight*)) – The y-position and extent for all the rectangles.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs (.PolyCollection properties) –

    Each kwarg can be either a single argument applying to all rectangles, e.g.:

    facecolors='black'
    

    or a sequence of arguments over which is cycled, e.g.:

    facecolors=('black', 'blue')
    

    would create interleaving black and blue rectangles.

    Supported keywords:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Return type:

~.collections.PolyCollection

bxp(bxpstats, positions=None, *, widths=None, vert=None, orientation='vertical', patch_artist=False, shownotches=False, showmeans=False, showcaps=True, showbox=True, showfliers=True, boxprops=None, whiskerprops=None, flierprops=None, medianprops=None, capprops=None, meanprops=None, meanline=False, manage_ticks=True, zorder=None, capwidths=None, label=None)[source]

Draw a box and whisker plot from pre-computed statistics.

The box extends from the first quartile q1 to the third quartile q3 of the data, with a line at the median (med). The whiskers extend from whislow to whishi. Flier points are markers past the end of the whiskers. See https://en.wikipedia.org/wiki/Box_plot for reference.

      whislow    q1    med    q3    whishi
                  |-----:-----|
  o      |--------|     :     |--------|    o  o
                  |-----:-----|
flier                                      fliers

Note

This is a low-level drawing function for when you already have the statistical parameters. If you want a boxplot based on a dataset, use ~.Axes.boxplot instead.

Parameters:
  • bxpstats (list of dicts) –

    A list of dictionaries containing stats for each boxplot. Required keys are:

    • med: Median (float).

    • q1, q3: First & third quartiles (float).

    • whislo, whishi: Lower & upper whisker positions (float).

    Optional keys are:

    • mean: Mean (float). Needed if showmeans=True.

    • fliers: Data beyond the whiskers (array-like). Needed if showfliers=True.

    • cilo, cihi: Lower & upper confidence intervals about the median. Needed if shownotches=True.

    • label: Name of the dataset (str). If available, this will be used a tick label for the boxplot

  • positions (array-like, default: [1, 2, ..., n]) – The positions of the boxes. The ticks and limits are automatically set to match the positions.

  • widths (float or array-like, default: None) – The widths of the boxes. The default is clip(0.15*(distance between extreme positions), 0.15, 0.5).

  • capwidths (float or array-like, default: None) – Either a scalar or a vector and sets the width of each cap. The default is 0.5*(width of the box), see widths.

  • vert (bool, optional) –

    Deprecated since version 3.11: Use orientation instead.

    This is a pending deprecation for 3.10, with full deprecation in 3.11 and removal in 3.13. If this is given during the deprecation period, it overrides the orientation parameter.

    If True, plots the boxes vertically. If False, plots the boxes horizontally.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') –

    If ‘horizontal’, plots the boxes horizontally. Otherwise, plots the boxes vertically.

    Added in version 3.10.

  • patch_artist (bool, default: False) – If False produces boxes with the .Line2D artist. If True produces boxes with the ~matplotlib.patches.Patch artist.

  • shownotches (bool) – Whether to draw the CI notches, the mean value (both default to False), the caps, the box, and the fliers (all three default to True).

  • showmeans (bool) – Whether to draw the CI notches, the mean value (both default to False), the caps, the box, and the fliers (all three default to True).

  • showcaps (bool) – Whether to draw the CI notches, the mean value (both default to False), the caps, the box, and the fliers (all three default to True).

  • showbox (bool) – Whether to draw the CI notches, the mean value (both default to False), the caps, the box, and the fliers (all three default to True).

  • showfliers (bool) – Whether to draw the CI notches, the mean value (both default to False), the caps, the box, and the fliers (all three default to True).

  • boxprops (dict, optional) – Artist properties for the boxes, whiskers, caps, fliers, medians, and means.

  • whiskerprops (dict, optional) – Artist properties for the boxes, whiskers, caps, fliers, medians, and means.

  • capprops (dict, optional) – Artist properties for the boxes, whiskers, caps, fliers, medians, and means.

  • flierprops (dict, optional) – Artist properties for the boxes, whiskers, caps, fliers, medians, and means.

  • medianprops (dict, optional) – Artist properties for the boxes, whiskers, caps, fliers, medians, and means.

  • meanprops (dict, optional) – Artist properties for the boxes, whiskers, caps, fliers, medians, and means.

  • meanline (bool, default: False) – If True (and showmeans is True), will try to render the mean as a line spanning the full width of the box according to meanprops. Not recommended if shownotches is also True. Otherwise, means will be shown as points.

  • manage_ticks (bool, default: True) – If True, the tick locations and labels will be adjusted to match the boxplot positions.

  • label (str or list of str, optional) –

    Legend labels. Use a single string when all boxes have the same style and you only want a single legend entry for them. Use a list of strings to label all boxes individually. To be distinguishable, the boxes should be styled individually, which is currently only possible by modifying the returned artists, see e.g. /gallery/statistics/boxplot_demo.

    In the case of a single string, the legend entry will technically be associated with the first box only. By default, the legend will show the median line (result["medians"]); if patch_artist is True, the legend will show the box .Patch artists (result["boxes"]) instead.

    Added in version 3.9.

  • zorder (float, default: Line2D.zorder = 2) – The zorder of the resulting boxplot.

Returns:

A dictionary mapping each component of the boxplot to a list of the .Line2D instances created. That dictionary has the following keys (assuming vertical boxplots):

  • boxes: main bodies of the boxplot showing the quartiles, and the median’s confidence intervals if enabled.

  • medians: horizontal lines at the median of each box.

  • whiskers: vertical lines up to the last non-outlier data.

  • caps: horizontal lines at the ends of the whiskers.

  • fliers: points representing data beyond the whiskers (fliers).

  • means: points or lines representing the means.

Return type:

dict

See also

boxplot

Draw a boxplot from data instead of pre-computed statistics.

can_pan()

Return whether this Axes supports any pan/zoom button functionality.

can_zoom()

Return whether this Axes supports the zoom box button functionality.

cla()

Clear the Axes.

clabel(CS, levels=None, **kwargs)[source]

Label a contour plot.

Adds labels to line contours in given .ContourSet.

Parameters:
  • CS (.ContourSet instance) – Line contours to label.

  • levels (array-like, optional) – A list of level values, that should be labeled. The list must be a subset of CS.levels. If not given, all levels are labeled.

  • **kwargs – All other parameters are documented in ~.ContourLabeler.clabel.

clear()

Clear the Axes.

cohere(x, y, *, NFFT=256, Fs=2, Fc=0, detrend=<function detrend_none>, window=<function window_hanning>, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, data=None, **kwargs)[source]

Plot the coherence between x and y.

Coherence is the normalized cross spectral density:

\[C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}\]
Parameters:
  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT

  • NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.

  • detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.

  • scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.

  • noverlap (int, default: 0 (no overlap)) – The number of points of overlap between blocks.

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

  • Cxy (1-D array) – The coherence vector.

  • freqs (1-D array) – The frequencies for the elements in Cxy.

References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)

property collections
contains(mouseevent)

Test whether the artist contains the mouse event.

Parameters:

mouseevent (~matplotlib.backend_bases.MouseEvent)

Returns:

  • contains (bool) – Whether any values are within the radius.

  • details (dict) – An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details.

contains_point(point)

Return whether point (pair of pixel coordinates) is inside the Axes patch.

contour(*args, data=None, **kwargs)[source]

Plot contour lines.

Call signature:

contour([X, Y,] Z, /, [levels], **kwargs)

The arguments X, Y, Z are positional-only.

.contour and .contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.

Parameters:
  • X (array-like, optional) –

    The coordinates of the values in Z.

    X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.

    X and Y must both be ordered monotonically.

    If not given, they are assumed to be integer indices, i.e. X = range(N), Y = range(M).

  • Y (array-like, optional) –

    The coordinates of the values in Z.

    X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.

    X and Y must both be ordered monotonically.

    If not given, they are assumed to be integer indices, i.e. X = range(N), Y = range(M).

  • Z ((M, N) array-like) – The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.

  • levels (int or array-like, optional) –

    Determines the number and positions of the contour lines / regions.

    If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between minimum and maximum numeric values of Z.

    If array-like, draw contour lines at the specified levels. The values must be in increasing order.

  • corner_mask (bool, default: :rc:`contour.corner_mask`) – Enable/disable corner masking, which only has an effect if Z is a masked array. If False, any quad touching a masked point is masked out. If True, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.

  • colors (:mpltype:`color` or list of :mpltype:`color`, optional) –

    The colors of the levels, i.e. the lines for .contour and the areas for .contourf.

    The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it’s repeated.

    As a shortcut, a single color may be used in place of one-element lists, i.e. 'red' instead of ['red'] to color all levels with the same color.

    Changed in version 3.10: Previously a single color had to be expressed as a string, but now any valid color format may be passed.

    By default (value None), the colormap specified by cmap will be used.

  • alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if colors is set.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if colors is set.

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –

    The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

    This parameter is ignored if colors is set.

  • origin ({*None*, 'upper', 'lower', 'image'}, default: None) –

    Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.

    • None: Z[0, 0] is at X=0, Y=0 in the lower left corner.

    • ’lower’: Z[0, 0] is at X=0.5, Y=0.5 in the lower left corner.

    • ’upper’: Z[0, 0] is at X=N+0.5, Y=0.5 in the upper left corner.

    • ’image’: Use the value from :rc:`image.origin`.

  • extent ((x0, x1, y0, y1), optional) –

    If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].

    This argument is ignored if X and Y are specified in the call to contour.

  • locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.

  • extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –

    Determines the contourf-coloring of values that are outside the levels range.

    If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.

    Values below min(levels) and above max(levels) are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.

    Note

    An existing .QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call ~.ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .QuadContourSet because it internally calls ~.ContourSet.changed().

    Example:

    x = np.arange(1, 10)
    y = x.reshape(-1, 1)
    h = x * y
    
    cs = plt.contourf(h, levels=[10, 30, 50],
        colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
    cs.cmap.set_over('red')
    cs.cmap.set_under('blue')
    cs.changed()
    

  • xunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • yunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is False. For line contours, it is taken from :rc:`lines.antialiased`.

  • nchunk (int >= 0, optional) – If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.

  • linewidths (float or array-like, default: :rc:`contour.linewidth`) –

    Only applies to .contour.

    The line width of the contour lines.

    If a number, all levels will be plotted with this linewidth.

    If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.

    If None, this falls back to :rc:`lines.linewidth`.

  • linestyles ({*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional) –

    Only applies to .contour.

    If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will instead take their linestyle from the negative_linestyles argument.

    linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.

  • negative_linestyles ({*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional) –

    Only applies to .contour.

    If linestyles is None and the lines are monochrome, this argument specifies the line style for negative contours.

    If negative_linestyles is None, the default is taken from :rc:`contour.negative_linestyle`.

    negative_linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.

  • hatches (list[str], optional) –

    Only applies to .contourf.

    A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour.

  • algorithm ({'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional) –

    Which contouring algorithm to use to calculate the contour lines and polygons. The algorithms are implemented in ContourPy, consult the ContourPy documentation for further information.

    The default is taken from :rc:`contour.algorithm`.

  • clip_path (~matplotlib.patches.Patch or .Path or .TransformedPath) –

    Set the clip path. See ~matplotlib.artist.Artist.set_clip_path.

    Added in version 3.8.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

Return type:

~.contour.QuadContourSet

Notes

  1. .contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to .contour.

  2. .contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:

    z1 < Z <= z2
    

    except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).

  3. .contour and .contourf use a marching squares algorithm to compute contour locations. More information can be found in ContourPy documentation.

contourf(*args, data=None, **kwargs)[source]

Plot filled contours.

Call signature:

contourf([X, Y,] Z, /, [levels], **kwargs)

The arguments X, Y, Z are positional-only.

.contour and .contourf draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions.

Parameters:
  • X (array-like, optional) –

    The coordinates of the values in Z.

    X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.

    X and Y must both be ordered monotonically.

    If not given, they are assumed to be integer indices, i.e. X = range(N), Y = range(M).

  • Y (array-like, optional) –

    The coordinates of the values in Z.

    X and Y must both be 2D with the same shape as Z (e.g. created via numpy.meshgrid), or they must both be 1-D such that len(X) == N is the number of columns in Z and len(Y) == M is the number of rows in Z.

    X and Y must both be ordered monotonically.

    If not given, they are assumed to be integer indices, i.e. X = range(N), Y = range(M).

  • Z ((M, N) array-like) – The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.

  • levels (int or array-like, optional) –

    Determines the number and positions of the contour lines / regions.

    If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between minimum and maximum numeric values of Z.

    If array-like, draw contour lines at the specified levels. The values must be in increasing order.

  • corner_mask (bool, default: :rc:`contour.corner_mask`) – Enable/disable corner masking, which only has an effect if Z is a masked array. If False, any quad touching a masked point is masked out. If True, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual.

  • colors (:mpltype:`color` or list of :mpltype:`color`, optional) –

    The colors of the levels, i.e. the lines for .contour and the areas for .contourf.

    The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it’s repeated.

    As a shortcut, a single color may be used in place of one-element lists, i.e. 'red' instead of ['red'] to color all levels with the same color.

    Changed in version 3.10: Previously a single color had to be expressed as a string, but now any valid color format may be passed.

    By default (value None), the colormap specified by cmap will be used.

  • alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if colors is set.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if colors is set.

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –

    The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

    This parameter is ignored if colors is set.

  • origin ({*None*, 'upper', 'lower', 'image'}, default: None) –

    Determines the orientation and exact position of Z by specifying the position of Z[0, 0]. This is only relevant, if X, Y are not given.

    • None: Z[0, 0] is at X=0, Y=0 in the lower left corner.

    • ’lower’: Z[0, 0] is at X=0.5, Y=0.5 in the lower left corner.

    • ’upper’: Z[0, 0] is at X=N+0.5, Y=0.5 in the upper left corner.

    • ’image’: Use the value from :rc:`image.origin`.

  • extent ((x0, x1, y0, y1), optional) –

    If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of Z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0, 0], and (x1, y1) is the position of Z[-1, -1].

    This argument is ignored if X and Y are specified in the call to contour.

  • locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.

  • extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –

    Determines the contourf-coloring of values that are outside the levels range.

    If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.

    Values below min(levels) and above max(levels) are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.

    Note

    An existing .QuadContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call ~.ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .QuadContourSet because it internally calls ~.ContourSet.changed().

    Example:

    x = np.arange(1, 10)
    y = x.reshape(-1, 1)
    h = x * y
    
    cs = plt.contourf(h, levels=[10, 30, 50],
        colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
    cs.cmap.set_over('red')
    cs.cmap.set_under('blue')
    cs.changed()
    

  • xunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • yunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is False. For line contours, it is taken from :rc:`lines.antialiased`.

  • nchunk (int >= 0, optional) – If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha.

  • linewidths (float or array-like, default: :rc:`contour.linewidth`) –

    Only applies to .contour.

    The line width of the contour lines.

    If a number, all levels will be plotted with this linewidth.

    If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.

    If None, this falls back to :rc:`lines.linewidth`.

  • linestyles ({*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional) –

    Only applies to .contour.

    If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will instead take their linestyle from the negative_linestyles argument.

    linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.

  • negative_linestyles ({*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional) –

    Only applies to .contour.

    If linestyles is None and the lines are monochrome, this argument specifies the line style for negative contours.

    If negative_linestyles is None, the default is taken from :rc:`contour.negative_linestyle`.

    negative_linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.

  • hatches (list[str], optional) –

    Only applies to .contourf.

    A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour.

  • algorithm ({'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional) –

    Which contouring algorithm to use to calculate the contour lines and polygons. The algorithms are implemented in ContourPy, consult the ContourPy documentation for further information.

    The default is taken from :rc:`contour.algorithm`.

  • clip_path (~matplotlib.patches.Patch or .Path or .TransformedPath) –

    Set the clip path. See ~matplotlib.artist.Artist.set_clip_path.

    Added in version 3.8.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

Return type:

~.contour.QuadContourSet

Notes

  1. .contourf differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to .contour.

  2. .contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:

    z1 < Z <= z2
    

    except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).

  3. .contour and .contourf use a marching squares algorithm to compute contour locations. More information can be found in ContourPy documentation.

convert_xunits(x)

Convert x using the unit type of the xaxis.

If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.

convert_yunits(y)

Convert y using the unit type of the yaxis.

If the artist is not contained in an Axes or if the yaxis does not have units, y itself is returned.

csd(x, y, *, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, data=None, **kwargs)[source]

Plot the cross-spectral density.

The cross spectral density \(P_{xy}\) by Welch’s average periodogram method. The vectors x and y are divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The product of the direct FFTs of x and y are averaged over each segment to compute \(P_{xy}\), with a scaling to correct for power loss due to windowing.

If len(x) < NFFT or len(y) < NFFT, they will be zero padded to NFFT.

Parameters:
  • x (1-D arrays or sequences) – Arrays or sequences containing the data.

  • y (1-D arrays or sequences) – Arrays or sequences containing the data.

  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT

  • NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.

  • detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.

  • scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.

  • noverlap (int, default: 0 (no overlap)) – The number of points of overlap between segments.

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • return_line (bool, default: False) – Whether to include the line object plotted in the returned values.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

  • Pxy (1-D array) – The values for the cross spectrum \(P_{xy}\) before scaling (complex valued).

  • freqs (1-D array) – The frequencies corresponding to the elements in Pxy.

  • line (~matplotlib.lines.Line2D) – The line created by this function. Only returned if return_line is True.

See also

psd

is equivalent to setting y = x.

Notes

For plotting, the power is plotted as \(10 \log_{10}(P_{xy})\) for decibels, though \(P_{xy}\) itself is returned.

References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)

dataLim: mtransforms.Bbox

The bounding .Bbox enclosing all data displayed in the Axes.

drag_pan(button, key, x, y)

Called when the mouse moves during a pan operation.

Parameters:
  • button (.MouseButton) – The pressed mouse button.

  • key (str or None) – The pressed key, if any.

  • x (float) – The mouse coordinates in display coords.

  • y (float) – The mouse coordinates in display coords.

Notes

This is intended to be overridden by new projection types.

draw(renderer)

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:

renderer (~matplotlib.backend_bases.RendererBase subclass.)

Notes

This method is overridden in the Artist subclasses.

draw_artist(a)

Efficiently redraw a single artist.

ecdf(x, weights=None, *, complementary=False, orientation='vertical', compress=False, data=None, **kwargs)[source]

Compute and plot the empirical cumulative distribution function of x.

Added in version 3.8.

Parameters:
  • x (1d array-like) – The input data. Infinite entries are kept (and move the relevant end of the ecdf from 0/1), but NaNs and masked values are errors.

  • weights (1d array-like or None, default: None) – The weights of the entries; must have the same shape as x. Weights corresponding to NaN data points are dropped, and then the remaining weights are normalized to sum to 1. If unset, all entries have the same weight.

  • complementary (bool, default: False) – Whether to plot a cumulative distribution function, which increases from 0 to 1 (the default), or a complementary cumulative distribution function, which decreases from 1 to 0.

  • orientation ({"vertical", "horizontal"}, default: "vertical") – Whether the entries are plotted along the x-axis (“vertical”, the default) or the y-axis (“horizontal”). This parameter takes the same values as in ~.Axes.hist.

  • compress (bool, default: False) – Whether multiple entries with the same values are grouped together (with a summed weight) before plotting. This is mainly useful if x contains many identical data points, to decrease the rendering complexity of the plot. If x contains no duplicate points, this has no effect and just uses some time and memory.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, weights

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Return type:

.Line2D

Notes

The ecdf plot can be thought of as a cumulative histogram with one bin per data entry; i.e. it reports on the entire dataset without any arbitrary binning.

If x contains NaNs or masked entries, either remove them first from the array (if they should not taken into account), or replace them by -inf or +inf (if they should be sorted at the beginning or the end of the array).

end_pan()

Called when a pan operation completes (when the mouse button is up.)

Notes

This is intended to be overridden by new projection types.

errorbar(x, y, yerr=None, xerr=None, fmt='', *, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, data=None, **kwargs)[source]

Plot y versus x as lines and/or markers with attached errorbars.

x, y define the data locations, xerr, yerr define the errorbar sizes. By default, this draws the data markers/lines as well as the errorbars. Use fmt=’none’ to draw errorbars without any data markers.

Added in version 3.7: Caps and error lines are drawn in polar coordinates on polar plots.

Parameters:
  • x (float or array-like) – The data positions.

  • y (float or array-like) – The data positions.

  • xerr (float or array-like, shape(N,) or shape(2, N), optional) –

    The errorbar sizes:

    • scalar: Symmetric +/- values for all data points.

    • shape(N,): Symmetric +/-values for each data point.

    • shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.

    • None: No errorbar.

    All values must be >= 0.

    See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.

  • yerr (float or array-like, shape(N,) or shape(2, N), optional) –

    The errorbar sizes:

    • scalar: Symmetric +/- values for all data points.

    • shape(N,): Symmetric +/-values for each data point.

    • shape(2, N): Separate - and + values for each bar. First row contains the lower errors, the second row contains the upper errors.

    • None: No errorbar.

    All values must be >= 0.

    See /gallery/statistics/errorbar_features for an example on the usage of xerr and yerr.

  • fmt (str, default: '') –

    The format for the data points / data lines. See .plot for details.

    Use ‘none’ (case-insensitive) to plot errorbars without any data markers.

  • ecolor (:mpltype:`color`, default: None) – The color of the errorbar lines. If None, use the color of the line connecting the markers.

  • elinewidth (float, default: None) – The linewidth of the errorbar lines. If None, the linewidth of the current style is used.

  • capsize (float, default: :rc:`errorbar.capsize`) – The length of the error bar caps in points.

  • capthick (float, default: None) – An alias to the keyword argument markeredgewidth (a.k.a. mew). This setting is a more sensible name for the property that controls the thickness of the error bar cap in points. For backwards compatibility, if mew or markeredgewidth are given, then they will over-ride capthick. This may change in future releases.

  • barsabove (bool, default: False) – If True, will plot the errorbars above the plot symbols. Default is below.

  • lolims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!

  • uplims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!

  • xlolims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!

  • xuplims (bool or array-like, default: False) – These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be scalars, or array-likes of the same length as xerr and yerr. To use limits with inverted axes, ~.Axes.set_xlim or ~.Axes.set_ylim must be called before errorbar(). Note the tricky parameter names: setting e.g. lolims to True means that the y-value is a lower limit of the True value, so, only an upward-pointing arrow will be drawn!

  • errorevery (int or (int, int), default: 1) – draws error bars on a subset of the data. errorevery =N draws error bars on the points (x[::N], y[::N]). errorevery =(start, N) draws error bars on the points (x[start::N], y[start::N]). e.g. errorevery=(6, 3) adds error bars to the data at (x[6], x[9], x[12], x[15], …). Used to avoid overlapping error bars when two series share x-axis values.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y, xerr, yerr

  • **kwargs

    All other keyword arguments are passed on to the ~.Axes.plot call drawing the markers. For example, this code makes big red squares with thick green edges:

    x, y, yerr = rand(3, 10)
    errorbar(x, y, yerr, marker='s', mfc='red',
             mec='green', ms=20, mew=4)
    

    where mfc, mec, ms and mew are aliases for the longer property names, markerfacecolor, markeredgecolor, markersize and markeredgewidth.

    Valid kwargs for the marker properties are:

    • dashes

    • dash_capstyle

    • dash_joinstyle

    • drawstyle

    • fillstyle

    • linestyle

    • marker

    • markeredgecolor

    • markeredgewidth

    • markerfacecolor

    • markerfacecoloralt

    • markersize

    • markevery

    • solid_capstyle

    • solid_joinstyle

    Refer to the corresponding .Line2D property for more details:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

The container contains:

  • data_line : A ~matplotlib.lines.Line2D instance of x, y plot markers and/or line.

  • caplines : A tuple of ~matplotlib.lines.Line2D instances of the error bar caps.

  • barlinecols : A tuple of .LineCollection with the horizontal and vertical error ranges.

Return type:

.ErrorbarContainer

eventplot(positions, *, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, alpha=None, linestyles='solid', data=None, **kwargs)[source]

Plot identical parallel lines at the given positions.

This type of plot is commonly used in neuroscience for representing neural events, where it is usually called a spike raster, dot raster, or raster plot.

However, it is useful in any situation where you wish to show the timing or position of multiple sets of discrete events, such as the arrival times of people to a business on each day of the month or the date of hurricanes each year of the last century.

Parameters:
  • positions (array-like or list of array-like) –

    A 1D array-like defines the positions of one sequence of events.

    Multiple groups of events may be passed as a list of array-likes. Each group can be styled independently by passing lists of values to lineoffsets, linelengths, linewidths, colors and linestyles.

    Note that positions can be a 2D array, but in practice different event groups usually have different counts so that one will use a list of different-length arrays rather than a 2D array.

  • orientation ({'horizontal', 'vertical'}, default: 'horizontal') –

    The direction of the event sequence:

    • ’horizontal’: the events are arranged horizontally. The indicator lines are vertical.

    • ’vertical’: the events are arranged vertically. The indicator lines are horizontal.

  • lineoffsets (float or array-like, default: 1) –

    The offset of the center of the lines from the origin, in the direction orthogonal to orientation.

    If positions is 2D, this can be a sequence with length matching the length of positions.

  • linelengths (float or array-like, default: 1) –

    The total height of the lines (i.e. the lines stretches from lineoffset - linelength/2 to lineoffset + linelength/2).

    If positions is 2D, this can be a sequence with length matching the length of positions.

  • linewidths (float or array-like, default: :rc:`lines.linewidth`) –

    The line width(s) of the event lines, in points.

    If positions is 2D, this can be a sequence with length matching the length of positions.

  • colors (:mpltype:`color` or list of color, default: :rc:`lines.color`) –

    The color(s) of the event lines.

    If positions is 2D, this can be a sequence with length matching the length of positions.

  • alpha (float or array-like, default: 1) –

    The alpha blending value(s), between 0 (transparent) and 1 (opaque).

    If positions is 2D, this can be a sequence with length matching the length of positions.

  • linestyles (str or tuple or list of such values, default: 'solid') –

    Default is ‘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.

    If positions is 2D, this can be a sequence with length matching the length of positions.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    positions, lineoffsets, linelengths, linewidths, colors, linestyles

  • **kwargs – Other keyword arguments are line collection properties. See .LineCollection for a list of the valid properties.

Returns:

The .EventCollection that were added.

Return type:

list of .EventCollection

Notes

For linelengths, linewidths, colors, alpha and linestyles, if only a single value is given, that value is applied to all lines. If an array-like is given, it must have the same length as positions, and each value will be applied to the corresponding row of the array.

Examples

property figure

The (Sub)Figure that the artist is on. For more control, use the get_figure method.

fill(*args, data=None, **kwargs)[source]

Plot filled polygons.

Parameters:
  • *args (sequence of x, y, [color]) –

    Each polygon is defined by the lists of x and y positions of its nodes, optionally followed by a color specifier. See matplotlib.colors for supported color specifiers. The standard color cycle is used for polygons without a color specifier.

    You can plot multiple polygons by providing multiple x, y, [color] groups.

    For example, each of the following is legal:

    ax.fill(x, y)                    # a polygon with default color
    ax.fill(x, y, "b")               # a blue polygon
    ax.fill(x, y, x2, y2)            # two polygons
    ax.fill(x, y, "b", x2, y2, "r")  # a blue and a red polygon
    

  • data (indexable object, optional) –

    An object with labelled data. If given, provide the label names to plot in x and y, e.g.:

    ax.fill("time", "signal",
            data={"time": [0, 1, 2], "signal": [0, 1, 0]})
    

  • **kwargs (~matplotlib.patches.Polygon properties)

Return type:

list of ~matplotlib.patches.Polygon

Notes

Use fill_between() if you would like to fill the region between two curves.

fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)[source]

Fill the area between two horizontal curves.

The curves are defined by the points (x, y1) and (x, y2). This creates one or multiple polygons describing the filled area.

You may exclude some horizontal sections from filling using where.

By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between x.

Parameters:
  • x (array-like) – The x coordinates of the nodes defining the curves.

  • y1 (array-like or float) – The y coordinates of the nodes defining the first curve.

  • y2 (array-like or float, default: 0) – The y coordinates of the nodes defining the second curve.

  • where (array-like of bool, optional) – Define where to exclude some horizontal regions from being filled. The filled regions are defined by the coordinates x[where]. More precisely, fill between x[i] and x[i+1] if where[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.

  • interpolate (bool, default: False) –

    This option is only relevant if where is used and the two curves are crossing each other.

    Semantically, where is often used for y1 > y2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the x array. Such a polygon cannot describe the above semantics close to the intersection. The x-sections containing the intersection are simply clipped.

    Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.

  • step ({'pre', 'post', 'mid'}, optional) –

    Define step if the filling should be a step function, i.e. constant in between x. The value determines where the step will occur:

    • ’pre’: The y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i].

    • ’post’: The y value is continued constantly to the right from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i].

    • ’mid’: Steps occur half-way between the x positions.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y1, y2, where

  • **kwargs

    All other keyword arguments are passed on to .FillBetweenPolyCollection. They control the .Polygon properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples data: array-like edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Returns:

A .FillBetweenPolyCollection containing the plotted polygons.

Return type:

.FillBetweenPolyCollection

See also

fill_between

Fill between two sets of y-values.

fill_betweenx

Fill between two sets of x-values.

fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)[source]

Fill the area between two vertical curves.

The curves are defined by the points (y, x1) and (y, x2). This creates one or multiple polygons describing the filled area.

You may exclude some vertical sections from filling using where.

By default, the edges connect the given points directly. Use step if the filling should be a step function, i.e. constant in between y.

Parameters:
  • y (array-like) – The y coordinates of the nodes defining the curves.

  • x1 (array-like or float) – The x coordinates of the nodes defining the first curve.

  • x2 (array-like or float, default: 0) – The x coordinates of the nodes defining the second curve.

  • where (array-like of bool, optional) – Define where to exclude some vertical regions from being filled. The filled regions are defined by the coordinates y[where]. More precisely, fill between y[i] and y[i+1] if where[i] and where[i+1]. Note that this definition implies that an isolated True value between two False values in where will not result in filling. Both sides of the True position remain unfilled due to the adjacent False values.

  • interpolate (bool, default: False) –

    This option is only relevant if where is used and the two curves are crossing each other.

    Semantically, where is often used for x1 > x2 or similar. By default, the nodes of the polygon defining the filled region will only be placed at the positions in the y array. Such a polygon cannot describe the above semantics close to the intersection. The y-sections containing the intersection are simply clipped.

    Setting interpolate to True will calculate the actual intersection point and extend the filled region up to this point.

  • step ({'pre', 'post', 'mid'}, optional) –

    Define step if the filling should be a step function, i.e. constant in between y. The value determines where the step will occur:

    • ’pre’: The x value is continued constantly to the left from every y position, i.e. the interval (y[i-1], y[i]] has the value x[i].

    • ’post’: The y value is continued constantly to the right from every y position, i.e. the interval [y[i], y[i+1]) has the value x[i].

    • ’mid’: Steps occur half-way between the y positions.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    y, x1, x2, where

  • **kwargs

    All other keyword arguments are passed on to .FillBetweenPolyCollection. They control the .Polygon properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples data: array-like edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Returns:

A .FillBetweenPolyCollection containing the plotted polygons.

Return type:

.FillBetweenPolyCollection

See also

fill_between

Fill between two sets of y-values.

fill_betweenx

Fill between two sets of x-values.

findobj(match=None, include_self=True)

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_self (bool) – Include self in the list to be checked for a match.

Return type:

list of .Artist

format_coord(x, y)

Return a format string formatting the x, y coordinates.

format_cursor_data(data)

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

format_xdata(x)

Return x formatted as an x-value.

This function will use the .fmt_xdata attribute if it is not None, else will fall back on the xaxis major formatter.

format_ydata(y)

Return y formatted as a y-value.

This function will use the .fmt_ydata attribute if it is not None, else will fall back on the yaxis major formatter.

get_adjustable()

Return whether the Axes will adjust its physical dimension (‘box’) or its data limits (‘datalim’) to achieve the desired aspect ratio.

See also

matplotlib.axes.Axes.set_adjustable

Set how the Axes adjusts to achieve the required aspect ratio.

matplotlib.axes.Axes.set_aspect

For a description of aspect handling.

get_agg_filter()

Return filter function to be used for agg filter.

get_alpha()

Return the alpha value used for blending - not supported on all backends.

get_anchor()

Get the anchor location.

See also

matplotlib.axes.Axes.set_anchor

for a description of the anchor.

matplotlib.axes.Axes.set_aspect

for a description of aspect handling.

get_animated()

Return whether the artist is animated.

get_aspect()

Return the aspect ratio of the Axes scaling.

This is either “auto” or a float giving the ratio of y/x-scale.

get_autoscale_on()

Return True if each axis is autoscaled, False otherwise.

get_autoscalex_on()

Return whether the xaxis is autoscaled.

get_autoscaley_on()

Return whether the yaxis is autoscaled.

get_axes_locator()

Return the axes_locator.

get_axisbelow()

Get whether axis ticks and gridlines are above or below most artists.

Return type:

bool or 'line'

See also

set_axisbelow

get_box_aspect()

Return the Axes box aspect, i.e. the ratio of height to width.

The box aspect is None (i.e. chosen depending on the available figure space) unless explicitly specified.

See also

matplotlib.axes.Axes.set_box_aspect

for a description of box aspect.

matplotlib.axes.Axes.set_aspect

for a description of aspect handling.

get_children()

Return a list of the child .Artists of this .Artist.

get_clip_box()

Return the clipbox.

get_clip_on()

Return whether the artist uses clipping.

get_clip_path()

Return the clip path.

get_cursor_data(event)

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:

event (~matplotlib.backend_bases.MouseEvent)

get_data_ratio()

Return the aspect ratio of the scaled data.

Notes

This method is intended to be overridden by new projection types.

get_default_bbox_extra_artists()

Return a default list of artists that are used for the bounding box calculation.

Artists are excluded either by not being visible or artist.set_in_layout(False).

get_facecolor()

Get the facecolor of the Axes.

get_fc()

Alias for get_facecolor.

get_figure(root=False)

Return the .Figure or .SubFigure instance the artist belongs to.

Parameters:

root (bool, default False) – If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.

get_forward_navigation_events()

Get how pan/zoom events are forwarded to Axes below this one.

get_frame_on()

Get whether the Axes rectangle patch is drawn.

get_gid()

Return the group id.

get_gridspec()

Return the .GridSpec associated with the subplot, or None.

get_images()

Return a list of .AxesImages contained by the Axes.

get_in_layout()

Return boolean flag, True if artist is included in layout calculations.

E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

get_label()

Return the label used for this artist in the legend.

get_legend()

Return the .Legend instance, or None if no legend is defined.

get_legend_handles_labels(legend_handler_map=None)[source]

Return handles and labels for legend

ax.legend() is equivalent to

h, l = ax.get_legend_handles_labels()
ax.legend(h, l)
get_lines()

Return a list of lines contained by the Axes.

get_mouseover()

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

get_navigate()

Get whether the Axes responds to navigation commands.

get_navigate_mode()

Get the navigation toolbar button status: ‘PAN’, ‘ZOOM’, or None.

get_path_effects()
get_picker()

Return the picking behavior of the artist.

The possible values are described in .Artist.set_picker.

See also

Artist.set_picker, Artist.pickable, Artist.pick

get_position(original=False)

Return the position of the Axes within the figure as a .Bbox.

Parameters:

original (bool) – If True, return the original position. Otherwise, return the active position. For an explanation of the positions see .set_position.

Return type:

.Bbox

get_rasterization_zorder()

Return the zorder value below which artists will be rasterized.

get_rasterized()

Return whether the artist is to be rasterized.

get_shared_x_axes()

Return an immutable view on the shared x-axes Grouper.

get_shared_y_axes()

Return an immutable view on the shared y-axes Grouper.

get_sketch_params()

Return the sketch parameters for the artist.

Returns:

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.

Return type:

tuple or None

get_snap()

Return the snap setting.

See .set_snap for details.

get_subplotspec()

Return the .SubplotSpec associated with the subplot, or None.

get_tightbbox(renderer=None, *, call_axes_locator=True, bbox_extra_artists=None, for_layout_only=False)

Return the tight bounding box of the Axes, including axis and their decorators (xlabel, title, etc).

Artists that have artist.set_in_layout(False) are not included in the bbox.

Parameters:
  • renderer (.RendererBase subclass) – renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())

  • bbox_extra_artists (list of .Artist or None) – List of artists to include in the tight bounding box. If None (default), then all artist children of the Axes are included in the tight bounding box.

  • call_axes_locator (bool, default: True) – If call_axes_locator is False, it does not call the _axes_locator attribute, which is necessary to get the correct bounding box. call_axes_locator=False can be used if the caller is only interested in the relative size of the tightbbox compared to the Axes bbox.

  • for_layout_only (default: False) – The bounding box will not include the x-extent of the title and the xlabel, or the y-extent of the ylabel.

Returns:

Bounding box in figure pixel coordinates.

Return type:

.BboxBase

See also

matplotlib.axes.Axes.get_window_extent, matplotlib.axis.Axis.get_tightbbox, matplotlib.spines.Spine.get_window_extent

get_title(loc='center')[source]

Get an Axes title.

Get one of the three available Axes titles. The available titles are positioned above the Axes in the center, flush with the left edge, and flush with the right edge.

Parameters:

loc ({'center', 'left', 'right'}, str, default: 'center') – Which title to return.

Returns:

The title text string.

Return type:

str

get_transform()

Return the .Transform instance used by this artist.

get_transformed_clip_path_and_affine()

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

get_url()

Return the url.

get_visible()

Return the visibility.

get_window_extent(renderer=None)

Return the Axes bounding box in display space.

This bounding box does not include the spines, ticks, ticklabels, or other labels. For a bounding box including these elements use ~matplotlib.axes.Axes.get_tightbbox.

See also

matplotlib.axes.Axes.get_tightbbox, matplotlib.axis.Axis.get_tightbbox, matplotlib.spines.Spine.get_window_extent

get_xaxis()

[Discouraged] Return the XAxis instance.

Discouraged

The use of this function is discouraged. You should instead directly access the attribute ~.Axes.xaxis.

get_xaxis_text1_transform(pad_points)
Returns:

  • transform (Transform) – The transform used for drawing x-axis labels, which will add pad_points of padding (in points) between the axis and the label. The x-direction is in data coordinates and the y-direction is in axis coordinates

  • valign ({'center', 'top', 'bottom', 'baseline', 'center_baseline'}) – The text vertical alignment.

  • halign ({'center', 'left', 'right'}) – The text horizontal alignment.

Notes

This transformation is primarily used by the ~matplotlib.axis.Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.

get_xaxis_text2_transform(pad_points)
Returns:

  • transform (Transform) – The transform used for drawing secondary x-axis labels, which will add pad_points of padding (in points) between the axis and the label. The x-direction is in data coordinates and the y-direction is in axis coordinates

  • valign ({'center', 'top', 'bottom', 'baseline', 'center_baseline'}) – The text vertical alignment.

  • halign ({'center', 'left', 'right'}) – The text horizontal alignment.

Notes

This transformation is primarily used by the ~matplotlib.axis.Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.

get_xaxis_transform(which='grid')

Get the transformation used for drawing x-axis labels, ticks and gridlines. The x-direction is in data coordinates and the y-direction is in axis coordinates.

Note

This transformation is primarily used by the ~matplotlib.axis.Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.

Parameters:

which ({'grid', 'tick1', 'tick2'})

get_xbound()

Return the lower and upper x-axis bounds, in increasing order.

get_xgridlines()

Return the xaxis’ grid lines as a list of .Line2Ds.

get_xlabel()

Get the xlabel text string.

get_xlim()

Return the x-axis view limits.

Returns:

left, right – The current x-axis limits in data coordinates.

Return type:

(float, float)

Notes

The x-axis may be inverted, in which case the left value will be greater than the right value.

get_xmajorticklabels()

Return the xaxis’ major tick labels, as a list of ~.text.Text.

get_xmargin()

Retrieve autoscaling margin of the x-axis.

Added in version 3.9.

Returns:

xmargin

Return type:

float

See also

matplotlib.axes.Axes.set_xmargin

get_xminorticklabels()

Return the xaxis’ minor tick labels, as a list of ~.text.Text.

get_xscale()

Return the xaxis’ scale (as a str).

get_xticklabels(minor=False, which=None)

Get the xaxis’ tick labels.

Parameters:
  • minor (bool) – Whether to return the minor or the major ticklabels.

  • which (None, (``’minor’, ``'major', 'both')) –

    Overrides minor.

    Selects which ticklabels to return

Return type:

list of ~matplotlib.text.Text

get_xticklines(minor=False)

Return the xaxis’ tick lines as a list of .Line2Ds.

get_xticks(*, minor=False)

Return the xaxis’ tick locations in data coordinates.

The locations are not clipped to the current axis limits and hence may contain locations that are not visible in the output.

Parameters:

minor (bool, default: False) – True to return the minor tick directions, False to return the major tick directions.

Return type:

array of tick locations

get_yaxis()

[Discouraged] Return the YAxis instance.

Discouraged

The use of this function is discouraged. You should instead directly access the attribute ~.Axes.yaxis.

get_yaxis_text1_transform(pad_points)
Returns:

  • transform (Transform) – The transform used for drawing y-axis labels, which will add pad_points of padding (in points) between the axis and the label. The x-direction is in axis coordinates and the y-direction is in data coordinates

  • valign ({'center', 'top', 'bottom', 'baseline', 'center_baseline'}) – The text vertical alignment.

  • halign ({'center', 'left', 'right'}) – The text horizontal alignment.

Notes

This transformation is primarily used by the ~matplotlib.axis.Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.

get_yaxis_text2_transform(pad_points)
Returns:

  • transform (Transform) – The transform used for drawing secondart y-axis labels, which will add pad_points of padding (in points) between the axis and the label. The x-direction is in axis coordinates and the y-direction is in data coordinates

  • valign ({'center', 'top', 'bottom', 'baseline', 'center_baseline'}) – The text vertical alignment.

  • halign ({'center', 'left', 'right'}) – The text horizontal alignment.

Notes

This transformation is primarily used by the ~matplotlib.axis.Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.

get_yaxis_transform(which='grid')

Get the transformation used for drawing y-axis labels, ticks and gridlines. The x-direction is in axis coordinates and the y-direction is in data coordinates.

Note

This transformation is primarily used by the ~matplotlib.axis.Axis class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.

Parameters:

which ({'grid', 'tick1', 'tick2'})

get_ybound()

Return the lower and upper y-axis bounds, in increasing order.

get_ygridlines()

Return the yaxis’ grid lines as a list of .Line2Ds.

get_ylabel()

Get the ylabel text string.

get_ylim()

Return the y-axis view limits.

Returns:

bottom, top – The current y-axis limits in data coordinates.

Return type:

(float, float)

Notes

The y-axis may be inverted, in which case the bottom value will be greater than the top value.

get_ymajorticklabels()

Return the yaxis’ major tick labels, as a list of ~.text.Text.

get_ymargin()

Retrieve autoscaling margin of the y-axis.

Added in version 3.9.

Returns:

ymargin

Return type:

float

See also

matplotlib.axes.Axes.set_ymargin

get_yminorticklabels()

Return the yaxis’ minor tick labels, as a list of ~.text.Text.

get_yscale()

Return the yaxis’ scale (as a str).

get_yticklabels(minor=False, which=None)

Get the yaxis’ tick labels.

Parameters:
  • minor (bool) – Whether to return the minor or the major ticklabels.

  • which (None, (``’minor’, ``'major', 'both')) –

    Overrides minor.

    Selects which ticklabels to return

Return type:

list of ~matplotlib.text.Text

get_yticklines(minor=False)

Return the yaxis’ tick lines as a list of .Line2Ds.

get_yticks(*, minor=False)

Return the yaxis’ tick locations in data coordinates.

The locations are not clipped to the current axis limits and hence may contain locations that are not visible in the output.

Parameters:

minor (bool, default: False) – True to return the minor tick directions, False to return the major tick directions.

Return type:

array of tick locations

get_zorder()

Return the artist’s zorder.

grid(visible=None, which='major', axis='both', **kwargs)

Configure the grid lines.

Parameters:
  • visible (bool or None, optional) –

    Whether to show the grid lines. If any kwargs are supplied, it is assumed you want the grid on and visible will be set to True.

    If visible is None and there are no kwargs, this toggles the visibility of the lines.

  • which ({'major', 'minor', 'both'}, optional) – The grid lines to apply the changes on.

  • axis ({'both', 'x', 'y'}, optional) – The axis to apply the changes on.

  • **kwargs (~matplotlib.lines.Line2D properties) –

    Define the line properties of the grid, e.g.:

    grid(color='r', linestyle='-', linewidth=2)
    

    Valid keyword arguments are:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Notes

The axis is drawn as a unit, so the effective zorder for drawing the grid is determined by the zorder of each axis, not by the zorder of the .Line2D objects comprising the grid. Therefore, to set grid zorder, use .set_axisbelow or, for more control, call the ~.Artist.set_zorder method of each axis.

has_data()

Return whether any artists have been added to the Axes.

This should not be used to determine whether the dataLim need to be updated, and may not actually be useful for anything.

have_units()

Return whether units are set on any axis.

hexbin(x, y, C=None, *, gridsize=100, bins=None, xscale='linear', yscale='linear', extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors='face', reduce_C_function=<function mean>, mincnt=None, marginals=False, colorizer=None, data=None, **kwargs)[source]

Make a 2D hexagonal binning plot of points x, y.

If C is None, the value of the hexagon is determined by the number of points in the hexagon. Otherwise, C specifies values at the coordinate (x[i], y[i]). For each hexagon, these values are reduced using reduce_C_function.

Parameters:
  • x (array-like) – The data positions. x and y must be of the same length.

  • y (array-like) – The data positions. x and y must be of the same length.

  • C (array-like, optional) – If given, these values are accumulated in the bins. Otherwise, every point has a value of 1. Must be of the same length as x and y.

  • gridsize (int or (int, int), default: 100) –

    If a single int, the number of hexagons in the x-direction. The number of hexagons in the y-direction is chosen such that the hexagons are approximately regular.

    Alternatively, if a tuple (nx, ny), the number of hexagons in the x-direction and the y-direction. In the y-direction, counting is done along vertically aligned hexagons, not along the zig-zag chains of hexagons; see the following illustration.

    To get approximately regular hexagons, choose \(n_x = \sqrt{3}\,n_y\).

  • bins ('log' or int or sequence, default: None) –

    Discretization of the hexagon values.

    • If None, no binning is applied; the color of each hexagon directly corresponds to its count value.

    • If ‘log’, use a logarithmic scale for the colormap. Internally, \(log_{10}(i+1)\) is used to determine the hexagon color. This is equivalent to norm=LogNorm().

    • If an integer, divide the counts in the specified number of bins, and color the hexagons accordingly.

    • If a sequence of values, the values of the lower bound of the bins to be used.

  • xscale ({'linear', 'log'}, default: 'linear') – Use a linear or log10 scale on the horizontal axis.

  • yscale ({'linear', 'log'}, default: 'linear') – Use a linear or log10 scale on the vertical axis.

  • mincnt (int >= 0, default: *None*) – If not None, only display cells with at least mincnt number of points in the cell.

  • marginals (bool, default: *False*) – If marginals is True, plot the marginal density as colormapped rectangles along the bottom of the x-axis and left of the y-axis.

  • extent (4-tuple of float, default: *None*) –

    The limits of the bins (xmin, xmax, ymin, ymax). The default assigns the limits based on gridsize, x, y, xscale and yscale.

    If xscale or yscale is set to ‘log’, the limits are expected to be the exponent for a power of 10. E.g. for x-limits of 1 and 50 in ‘linear’ scale and y-limits of 10 and 1000 in ‘log’ scale, enter (1, 50, 1, 3).

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) – The Colormap instance or registered colormap name used to map scalar data to colors.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

  • vmin (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • vmax (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • alpha (float between 0 and 1, optional) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • linewidths (float, default: *None*) – If None, defaults to :rc:`patch.linewidth`.

  • edgecolors ({'face', 'none', *None*} or color, default: 'face') –

    The color of the hexagon edges. Possible values are:

    • ’face’: Draw the edges in the same color as the fill color.

    • ’none’: No edges are drawn. This can sometimes lead to unsightly unpainted pixels between the hexagons.

    • None: Draw outlines in the default color.

    • An explicit color.

  • reduce_C_function (callable, default: numpy.mean) –

    The function to aggregate C within the bins. It is ignored if C is not given. This must have the signature:

    def reduce_C_function(C: array) -> float
    

    Commonly used functions are:

    • numpy.mean: average of the points

    • numpy.sum: integral of the point values

    • numpy.amax: value taken from the largest point

    By default will only reduce cells with at least 1 point because some reduction functions (such as numpy.amax) will error/warn with empty input. Changing mincnt will adjust the cutoff, and if set to 0 will pass empty input to the reduction function.

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y, C

  • **kwargs (~matplotlib.collections.PolyCollection properties) –

    All other keyword arguments are passed on to .PolyCollection:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Returns:

A .PolyCollection defining the hexagonal bins.

  • .PolyCollection.get_offsets contains a Mx2 array containing the x, y positions of the M hexagon centers in data coordinates.

  • .PolyCollection.get_array contains the values of the M hexagons.

If marginals is True, horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar.

Return type:

~matplotlib.collections.PolyCollection

See also

hist2d

2D histogram rectangular bins

hist(x, bins=None, *, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, data=None, **kwargs)[source]

Compute and plot a histogram.

This method uses numpy.histogram to bin the data in x and count the number of values in each bin, then draws the distribution either as a .BarContainer or .Polygon. The bins, range, density, and weights parameters are forwarded to numpy.histogram.

If the data has already been binned and counted, use ~.bar or ~.stairs to plot the distribution:

counts, bins = np.histogram(x)
plt.stairs(counts, bins)

Alternatively, plot pre-computed bins and counts using hist() by treating each bin as a single point with a weight equal to its count:

plt.hist(bins[:-1], bins, weights=counts)

The data input x can be a singular array, a list of datasets of potentially different lengths ([x0, x1, …]), or a 2D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form. If the input is an array, then the return value is a tuple (n, bins, patches); if the input is a sequence of arrays, then the return value is a tuple ([n0, n1, …], bins, [patches0, patches1, …]).

Masked arrays are not supported.

Parameters:
  • x ((n,) array or sequence of (n,) arrays) – Input values, this takes either a single array or a sequence of arrays which are not required to be of the same length.

  • bins (int or sequence or str, default: :rc:`hist.bins`) –

    If bins is an integer, it defines the number of equal-width bins in the range.

    If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open. In other words, if bins is:

    [1, 2, 3, 4]
    

    then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.

    If bins is a string, it is one of the binning strategies supported by numpy.histogram_bin_edges: ‘auto’, ‘fd’, ‘doane’, ‘scott’, ‘stone’, ‘rice’, ‘sturges’, or ‘sqrt’.

  • range (tuple or None, default: None) –

    The lower and upper range of the bins. Lower and upper outliers are ignored. If not provided, range is (x.min(), x.max()). Range has no effect if bins is a sequence.

    If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x.

  • density (bool, default: False) –

    If True, draw and return a probability density: each bin will display the bin’s raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1).

    If stacked is also True, the sum of the histograms is normalized to 1.

  • weights ((n,) array-like or None, default: None) – An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.

  • cumulative (bool or -1, default: False) –

    If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints.

    If density is also True then the histogram is normalized such that the last bin equals 1.

    If cumulative is a number less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if density is also True, then the histogram is normalized such that the first bin equals 1.

  • bottom (array-like or float, default: 0) – Location of the bottom of each bin, i.e. bins are drawn from bottom to bottom + hist(x, bins) If a scalar, the bottom of each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0.

  • histtype ({'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar') –

    The type of histogram to draw.

    • ’bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.

    • ’barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.

    • ’step’ generates a lineplot that is by default unfilled.

    • ’stepfilled’ generates a lineplot that is by default filled.

  • align ({'left', 'mid', 'right'}, default: 'mid') –

    The horizontal alignment of the histogram bars.

    • ’left’: bars are centered on the left bin edges.

    • ’mid’: bars are centered between the bin edges.

    • ’right’: bars are centered on the right bin edges.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') – If ‘horizontal’, ~.Axes.barh will be used for bar-type histograms and the bottom kwarg will be the left edges.

  • rwidth (float or None, default: None) –

    The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.

    Ignored if histtype is ‘step’ or ‘stepfilled’.

  • log (bool, default: False) – If True, the histogram axis will be set to a log scale.

  • color (:mpltype:`color` or list of :mpltype:`color` or None, default: None) – Color or sequence of colors, one per dataset. Default (None) uses the standard line color sequence.

  • label (str or list of str, optional) – String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that ~.Axes.legend will work as expected.

  • stacked (bool, default: False) – If True, multiple data are stacked on top of each other If False multiple data are arranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, weights

  • **kwargs

    ~matplotlib.patches.Patch properties. The following properties additionally accept a sequence of values corresponding to the datasets in x: edgecolor, facecolor, linewidth, linestyle, hatch.

    Added in version 3.10: Allowing sequences of values in above listed Patch properties.

Returns:

  • n (array or list of arrays) – The values of the histogram bins. See density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2, ...], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. The dtype of the array n (or of its element arrays) will always be float even if no weighting or normalization is used.

  • bins (array) – The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.

  • patches (.BarContainer or list of a single `.Polygon` or list of such objects) – Container of individual artists used to create the histogram or list of such containers if there are multiple input datasets.

See also

hist2d

2D histogram with rectangular bins

hexbin

2D histogram with hexagonal bins

stairs

Plot a pre-computed histogram

bar

Plot a pre-computed histogram

Notes

For large numbers of bins (>1000), plotting can be significantly accelerated by using ~.Axes.stairs to plot a pre-computed histogram (plt.stairs(*np.histogram(data))), or by setting histtype to ‘step’ or ‘stepfilled’ rather than ‘bar’ or ‘barstacked’.

hist2d(x, y, bins=10, *, range=None, density=False, weights=None, cmin=None, cmax=None, data=None, **kwargs)[source]

Make a 2D histogram plot.

Parameters:
  • x (array-like, shape (n, )) – Input values

  • y (array-like, shape (n, )) – Input values

  • bins (None or int or [int, int] or array-like or [array, array]) –

    The bin specification:

    • If int, the number of bins for the two dimensions (nx = ny = bins).

    • If [int, int], the number of bins in each dimension (nx, ny = bins).

    • If array-like, the bin edges for the two dimensions (x_edges = y_edges = bins).

    • If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).

    The default value is 10.

  • range (array-like shape(2, 2), optional) – The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.

  • density (bool, default: False) – Normalize histogram. See the documentation for the density parameter of ~.Axes.hist for more details.

  • weights (array-like, shape (n, ), optional) – An array of values w_i weighing each sample (x_i, y_i).

  • cmin (float, default: None) – All bins that has count less than cmin or more than cmax will not be displayed (set to NaN before passing to ~.Axes.pcolormesh) and these count values in the return value count histogram will also be set to nan upon return.

  • cmax (float, default: None) – All bins that has count less than cmin or more than cmax will not be displayed (set to NaN before passing to ~.Axes.pcolormesh) and these count values in the return value count histogram will also be set to nan upon return.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) – The Colormap instance or registered colormap name used to map scalar data to colors.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

  • vmin (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • vmax (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

  • alpha (0 <= scalar <= 1 or None, optional) – The alpha blending value.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y, weights

  • **kwargs – Additional parameters are passed along to the ~.Axes.pcolormesh method and ~matplotlib.collections.QuadMesh constructor.

Returns:

  • h (2D array) – The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.

  • xedges (1D array) – The bin edges along the x-axis.

  • yedges (1D array) – The bin edges along the y-axis.

  • image (~.matplotlib.collections.QuadMesh)

See also

hist

1D histogram plotting

hexbin

2D histogram with hexagonal bins

Notes

  • Currently hist2d calculates its own axis limits, and any limits previously set are ignored.

  • Rendering the histogram with a logarithmic color scale is accomplished by passing a .colors.LogNorm instance to the norm keyword argument. Likewise, power-law normalization (similar in effect to gamma correction) can be accomplished with .colors.PowerNorm.

hlines(y, xmin, xmax, colors=None, linestyles='solid', *, label='', data=None, **kwargs)[source]

Plot horizontal lines at each y from xmin to xmax.

Parameters:
  • y (float or array-like) – y-indexes where to plot the lines.

  • xmin (float or array-like) – Respective beginning and end of each line. If scalars are provided, all lines will have the same length.

  • xmax (float or array-like) – Respective beginning and end of each line. If scalars are provided, all lines will have the same length.

  • colors (:mpltype:`color` or list of color , default: :rc:`lines.color`)

  • linestyles ({'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid')

  • label (str, default: '')

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    y, xmin, xmax, colors

  • **kwargs (~matplotlib.collections.LineCollection properties.)

Return type:

~matplotlib.collections.LineCollection

See also

vlines

vertical lines

axhline

horizontal line across the Axes

property images
imshow(X, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, colorizer=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)[source]

Display data as an image, i.e., on a 2D regular raster.

The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. For displaying a grayscale image, set up the colormapping using the parameters cmap='gray', vmin=0, vmax=255.

The number of pixels used to render an image is set by the Axes size and the figure dpi. This can lead to aliasing artifacts when the image is resampled, because the displayed image size will usually not match the size of X (see /gallery/images_contours_and_fields/image_antialiasing). The resampling can be controlled via the interpolation parameter and/or :rc:`image.interpolation`.

Parameters:
  • X (array-like or PIL image) –

    The image data. Supported array shapes are:

    • (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.

    • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).

    • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

    The first two dimensions (M, N) define the rows and columns of the image.

    Out-of-range RGB(A) values are clipped.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if X is RGB(A).

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if X is RGB(A).

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if X is RGB(A).

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if X is RGB(A).

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –

    The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

    This parameter is ignored if X is RGB(A).

  • aspect ({'equal', 'auto'} or float or None, default: None) –

    The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square.

    This parameter is a shortcut for explicitly calling .Axes.set_aspect. See there for further details.

    • ’equal’: Ensures an aspect ratio of 1. Pixels will be square (unless pixel sizes are explicitly made non-square in data coordinates using extent).

    • ’auto’: The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels.

    Normally, None (the default) means to use :rc:`image.aspect`. However, if the image uses a transform that does not contain the axes data transform, then None means to not modify the axes aspect at all (in that case, directly call .Axes.set_aspect if desired).

  • interpolation (str, default: :rc:`image.interpolation`) –

    The interpolation method used.

    Supported values are ‘none’, ‘auto’, ‘nearest’, ‘bilinear’, ‘bicubic’, ‘spline16’, ‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’, ‘lanczos’, ‘blackman’.

    The data X is resampled to the pixel size of the image on the figure canvas, using the interpolation method to either up- or downsample the data.

    If interpolation is ‘none’, then for the ps, pdf, and svg backends no down- or upsampling occurs, and the image data is passed to the backend as a native image. Note that different ps, pdf, and svg viewers may display these raw pixels differently. On other backends, ‘none’ is the same as ‘nearest’.

    If interpolation is the default ‘auto’, then ‘nearest’ interpolation is used if the image is upsampled by more than a factor of three (i.e. the number of display pixels is at least three times the size of the data array). If the upsampling rate is smaller than 3, or the image is downsampled, then ‘hanning’ interpolation is used to act as an anti-aliasing filter, unless the image happens to be upsampled by exactly a factor of two or one.

    See /gallery/images_contours_and_fields/interpolation_methods for an overview of the supported interpolation methods, and /gallery/images_contours_and_fields/image_antialiasing for a discussion of image antialiasing.

    Some interpolation methods require an additional radius parameter, which can be set by filterrad. Additionally, the antigrain image resize filter is controlled by the parameter filternorm.

  • interpolation_stage ({'auto', 'data', 'rgba'}, default: 'auto') –

    Supported values:

    • ’data’: Interpolation is carried out on the data provided by the user This is useful if interpolating between pixels during upsampling.

    • ’rgba’: The interpolation is carried out in RGBA-space after the color-mapping has been applied. This is useful if downsampling and combining pixels visually.

    • ’auto’: Select a suitable interpolation stage automatically. This uses ‘rgba’ when downsampling, or upsampling at a rate less than 3, and ‘data’ when upsampling at a higher rate.

    See /gallery/images_contours_and_fields/image_antialiasing for a discussion of image antialiasing.

  • alpha (float or array-like, optional) – The alpha blending value, between 0 (transparent) and 1 (opaque). If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X.

  • origin ({'upper', 'lower'}, default: :rc:`image.origin`) –

    Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention (the default) ‘upper’ is typically used for matrices and images.

    Note that the vertical axis points upward for ‘lower’ but downward for ‘upper’.

    See the imshow_extent tutorial for examples and a more detailed description.

  • extent (floats (left, right, bottom, top), optional) –

    The bounding box in data coordinates that the image will fill. These values may be unitful and match the units of the Axes. The image is stretched individually along x and y to fill the box.

    The default extent is determined by the following conditions. Pixels have unit size in data coordinates. Their centers are on integer coordinates, and their center coordinates range from 0 to columns-1 horizontally and from 0 to rows-1 vertically.

    Note that the direction of the vertical axis and thus the default values for top and bottom depend on origin:

    • For origin == 'upper' the default is (-0.5, numcols-0.5, numrows-0.5, -0.5).

    • For origin == 'lower' the default is (-0.5, numcols-0.5, -0.5, numrows-0.5).

    See the imshow_extent tutorial for examples and a more detailed description.

  • filternorm (bool, default: True) – A parameter for the antigrain image resize filter (see the antigrain documentation). If filternorm is set, the filter normalizes integer values and corrects the rounding errors. It doesn’t do anything with the source floating point values, it corrects only integers according to the rule of 1.0 which means that any sum of pixel weights must be equal to 1.0. So, the filter function must produce a graph of the proper shape.

  • filterrad (float > 0, default: 4.0) – The filter radius for filters that have a radius parameter, i.e. when interpolation is one of: ‘sinc’, ‘lanczos’ or ‘blackman’.

  • resample (bool, default: :rc:`image.resample`) – When True, use a full resampling method. When False, only resample when the output image is larger than the input image.

  • url (str, optional) – Set the url of the created .AxesImage. See .Artist.set_url.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs (~matplotlib.artist.Artist properties) – These parameters are passed on to the constructor of the .AxesImage artist.

Return type:

~matplotlib.image.AxesImage

See also

matshow

Plot a matrix or an array as an image.

Notes

Unless extent is used, pixel centers will be located at integer coordinates. In other words: the origin will coincide with the center of pixel (0, 0).

There are two common representations for RGB images with an alpha channel:

  • Straight (unassociated) alpha: R, G, and B channels represent the color of the pixel, disregarding its opacity.

  • Premultiplied (associated) alpha: R, G, and B channels represent the color of the pixel, adjusted for its opacity by multiplication.

~matplotlib.pyplot.imshow expects RGB images adopting the straight (unassociated) alpha representation.

in_axes(mouseevent)

Return whether the given event (in display coords) is in the Axes.

indicate_inset(bounds=None, inset_ax=None, *, transform=None, facecolor='none', edgecolor='0.5', alpha=0.5, zorder=None, **kwargs)[source]

Add an inset indicator to the Axes. This is a rectangle on the plot at the position indicated by bounds that optionally has lines that connect the rectangle to an inset Axes (.Axes.inset_axes).

Warning

This method is experimental as of 3.0, and the API may change.

Parameters:
  • bounds ([x0, y0, width, height], optional) – Lower-left corner of rectangle to be marked, and its width and height. If not set, the bounds will be calculated from the data limits of inset_ax, which must be supplied.

  • inset_ax (.Axes, optional) – An optional inset Axes to draw connecting lines to. Two lines are drawn connecting the indicator box to the inset Axes on corners chosen so as to not overlap with the indicator box.

  • transform (.Transform) – Transform for the rectangle coordinates. Defaults to ax.transAxes, i.e. the units of rect are in Axes-relative coordinates.

  • facecolor (:mpltype:`color`, default: 'none') – Facecolor of the rectangle.

  • edgecolor (:mpltype:`color`, default: '0.5') – Color of the rectangle and color of the connecting lines.

  • alpha (float or None, default: 0.5) – Transparency of the rectangle and connector lines. If not None, this overrides any alpha value included in the facecolor and edgecolor parameters.

  • zorder (float, default: 4.99) – Drawing order of the rectangle and connector lines. The default, 4.99, is just below the default level of inset Axes.

  • **kwargs

    Other keyword arguments are passed on to the .Rectangle patch:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

Returns:

inset_indicator – An artist which contains

inset_indicator.rectangle.Rectangle

The indicator frame.

inset_indicator.connectors4-tuple of .patches.ConnectionPatch

The four connector lines connecting to (lower_left, upper_left, lower_right upper_right) corners of inset_ax. Two lines are set with visibility to False, but the user can set the visibility to True if the automatic choice is not deemed correct.

Changed in version 3.10: Previously the rectangle and connectors tuple were returned.

Return type:

.inset.InsetIndicator

indicate_inset_zoom(inset_ax, **kwargs)[source]

Add an inset indicator rectangle to the Axes based on the axis limits for an inset_ax and draw connectors between inset_ax and the rectangle.

Warning

This method is experimental as of 3.0, and the API may change.

Parameters:
  • inset_ax (.Axes) – Inset Axes to draw connecting lines to. Two lines are drawn connecting the indicator box to the inset Axes on corners chosen so as to not overlap with the indicator box.

  • **kwargs – Other keyword arguments are passed on to .Axes.indicate_inset

Returns:

inset_indicator – An artist which contains

inset_indicator.rectangle.Rectangle

The indicator frame.

inset_indicator.connectors4-tuple of .patches.ConnectionPatch

The four connector lines connecting to (lower_left, upper_left, lower_right upper_right) corners of inset_ax. Two lines are set with visibility to False, but the user can set the visibility to True if the automatic choice is not deemed correct.

Changed in version 3.10: Previously the rectangle and connectors tuple were returned.

Return type:

.inset.InsetIndicator

inset_axes(bounds, *, transform=None, zorder=5, **kwargs)[source]

Add a child inset Axes to this existing Axes.

Parameters:
  • bounds ([x0, y0, width, height]) – Lower-left corner of inset Axes, and its width and height.

  • transform (.Transform) – Defaults to ax.transAxes, i.e. the units of rect are in Axes-relative coordinates.

  • projection ({None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional) – The projection type of the inset ~.axes.Axes. str is the name of a custom projection, see ~matplotlib.projections. The default None results in a ‘rectilinear’ projection.

  • polar (bool, default: False) – If True, equivalent to projection=’polar’.

  • axes_class (subclass type of ~.axes.Axes, optional) – The .axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist_users-guide-index for examples.

  • zorder (number) – Defaults to 5 (same as .Axes.legend). Adjust higher or lower to change whether it is above or below data plotted on the parent Axes.

  • **kwargs – Other keyword arguments are passed on to the inset Axes class.

Returns:

The created ~.axes.Axes instance.

Return type:

ax

Examples

This example makes two inset Axes, the first is in Axes-relative coordinates, and the second in data-coordinates:

fig, ax = plt.subplots()
ax.plot(range(10))
axin1 = ax.inset_axes([0.8, 0.1, 0.15, 0.15])
axin2 = ax.inset_axes(
        [5, 7, 2.3, 2.3], transform=ax.transData)
invert_xaxis()

Invert the x-axis.

invert_yaxis()

Invert the y-axis.

is_transform_set()

Return whether the Artist has an explicitly set transform.

This is True after .set_transform has been called.

label_outer(remove_inner_ticks=False)

Only show “outer” labels and tick labels.

x-labels are only kept for subplots on the last row (or first row, if labels are on the top side); y-labels only for subplots on the first column (or last column, if labels are on the right side).

Parameters:

remove_inner_ticks (bool, default: False) –

If True, remove the inner ticks as well (not only tick labels).

Added in version 3.8.

legend(*args, **kwargs)[source]

Place a legend on the Axes.

Call signatures:

legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)

The call signatures correspond to the following different ways to use this method:

1. Automatic detection of elements to be shown in the legend

The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.

In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist:

ax.plot([1, 2, 3], label='Inline label')
ax.legend()

or:

line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.legend()

Note

Specific artists can be excluded from the automatic legend element selection by using a label starting with an underscore, “_”. A string starting with an underscore is the default label for all artists, so calling .Axes.legend without any arguments and without setting the labels manually will result in a UserWarning and an empty legend being drawn.

2. Explicitly listing the artists and labels in the legend

For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:

ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])

3. Explicitly listing the artists in the legend

This is similar to 2, but the labels are taken from the artists’ label properties. Example:

line1, = ax.plot([1, 2, 3], label='label1')
line2, = ax.plot([1, 2, 3], label='label2')
ax.legend(handles=[line1, line2])

4. Labeling existing plot elements

Discouraged

This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.

To make a legend for all artists on an Axes, call this function with an iterable of strings, one for each legend item. For example:

ax.plot([1, 2, 3])
ax.plot([5, 6, 7])
ax.legend(['First line', 'Second line'])
Parameters:
  • handles (list of (.Artist`` or tuple of .Artist), optional) –

    A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

    The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.

    If an entry contains a tuple, then the legend handler for all Artists in the tuple will be placed alongside a single label.

  • labels (list of str, optional) – A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

  • loc (str or pair of floats, default: :rc:`legend.loc`) –

    The location of the legend.

    The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes.

    The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes.

    The string 'center' places the legend at the center of the axes.

    The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.

    The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

    For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each “string” location can also be given as a numeric value:

    Location String

    Location Code

    ’best’ (Axes only)

    0

    ’upper right’

    1

    ’upper left’

    2

    ’lower left’

    3

    ’lower right’

    4

    ’right’

    5

    ’center left’

    6

    ’center right’

    7

    ’lower center’

    8

    ’upper center’

    9

    ’center’

    10

  • bbox_to_anchor (.BboxBase, 2-tuple, or 4-tuple of floats) –

    Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to .Axes.legend) or figure.bbox (if figure.legend). This argument allows arbitrary placement of the legend.

    Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called.

    If a 4-tuple or .BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the Axes (or figure):

    loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
    

    A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend’s upper right-hand corner in the center of the Axes (or figure) the following keywords can be used:

    loc='upper right', bbox_to_anchor=(0.5, 0.5)
    

  • ncols (int, default: 1) –

    The number of columns that the legend has.

    For backward compatibility, the spelling ncol is also supported but it is discouraged. If both are given, ncols takes precedence.

  • prop (None or ~matplotlib.font_manager.FontProperties or dict) – The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

  • fontsize (int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}) – The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.

  • labelcolor (str or list, default: :rc:`legend.labelcolor`) –

    The color of the text in the legend. Either a valid color string (for example, ‘red’), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using ‘linecolor’, ‘markerfacecolor’ (or ‘mfc’), or ‘markeredgecolor’ (or ‘mec’).

    Labelcolor can be set globally using :rc:`legend.labelcolor`. If None, use :rc:`text.color`.

  • numpoints (int, default: :rc:`legend.numpoints`) – The number of marker points in the legend when creating a legend entry for a .Line2D (line).

  • scatterpoints (int, default: :rc:`legend.scatterpoints`) – The number of marker points in the legend when creating a legend entry for a .PathCollection (scatter plot).

  • scatteryoffsets (iterable of floats, default: :py:class:`[0.375`, ``0.5, 0.3125]``) – The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].

  • markerscale (float, default: :rc:`legend.markerscale`) – The relative size of legend markers compared to the originally drawn ones.

  • markerfirst (bool, default: True) – If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.

  • reverse (bool, default: False) –

    If True, the legend labels are displayed in reverse order from the input. If False, the legend labels are displayed in the same order as the input.

    Added in version 3.7.

  • frameon (bool, default: :rc:`legend.frameon`) – Whether the legend should be drawn on a patch (frame).

  • fancybox (bool, default: :rc:`legend.fancybox`) – Whether round edges should be enabled around the .FancyBboxPatch which makes up the legend’s background.

  • shadow (None, bool or dict, default: :rc:`legend.shadow`) – Whether to draw a shadow behind the legend. The shadow can be configured using .Patch keywords. Customization via :rc:`legend.shadow` is currently not supported.

  • framealpha (float, default: :rc:`legend.framealpha`) – The alpha transparency of the legend’s background. If shadow is activated and framealpha is None, the default value is ignored.

  • facecolor ("inherit" or color, default: :rc:`legend.facecolor`) – The legend’s background color. If "inherit", use :rc:`axes.facecolor`.

  • edgecolor ("inherit" or color, default: :rc:`legend.edgecolor`) – The legend’s background patch edge color. If "inherit", use :rc:`axes.edgecolor`.

  • mode ({"expand", None}) – If mode is set to "expand" the legend will be horizontally expanded to fill the Axes area (or bbox_to_anchor if defines the legend’s size).

  • bbox_transform (None or ~matplotlib.transforms.Transform) – The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’ transAxes transform will be used.

  • title (str or None) – The legend’s title. Default is no title (None).

  • title_fontproperties (None or ~matplotlib.font_manager.FontProperties or dict) – The font properties of the legend’s title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current :rc:`legend.title_fontsize` will be used.

  • title_fontsize (int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`) – The font size of the legend’s title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.

  • alignment ({'center', 'left', 'right'}, default: 'center') – The alignment of the legend title and the box of entries. The entries are aligned as a single block, so that markers always lined up.

  • borderpad (float, default: :rc:`legend.borderpad`) – The fractional whitespace inside the legend border, in font-size units.

  • labelspacing (float, default: :rc:`legend.labelspacing`) – The vertical space between the legend entries, in font-size units.

  • handlelength (float, default: :rc:`legend.handlelength`) – The length of the legend handles, in font-size units.

  • handleheight (float, default: :rc:`legend.handleheight`) – The height of the legend handles, in font-size units.

  • handletextpad (float, default: :rc:`legend.handletextpad`) – The pad between the legend handle and text, in font-size units.

  • borderaxespad (float, default: :rc:`legend.borderaxespad`) – The pad between the Axes and legend border, in font-size units.

  • columnspacing (float, default: :rc:`legend.columnspacing`) – The spacing between columns, in font-size units.

  • handler_map (dict or None) – The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map.

  • draggable (bool, default: False) – Whether the legend can be dragged with the mouse.

Return type:

~matplotlib.legend.Legend

See also

Figure.legend

Notes

Some artists are not supported by this function. See legend_guide for details.

Examples

property lines
locator_params(axis='both', tight=None, **kwargs)

Control behavior of major tick locators.

Because the locator is involved in autoscaling, ~.Axes.autoscale_view is called automatically after the parameters are changed.

Parameters:
  • axis ({'both', 'x', 'y'}, default: 'both') – The axis on which to operate. (For 3D Axes, axis can also be set to ‘z’, and ‘both’ refers to all three axes.)

  • tight (bool or None, optional) – Parameter passed to ~.Axes.autoscale_view. Default is None, for no change.

  • **kwargs – Remaining keyword arguments are passed to directly to the set_params() method of the locator. Supported keywords depend on the type of the locator. See for example ~.ticker.MaxNLocator.set_params for the .ticker.MaxNLocator used by default for linear.

Examples

When plotting small subplots, one might want to reduce the maximum number of ticks and use tight bounds, for example:

ax.locator_params(tight=True, nbins=4)
loglog(*args, **kwargs)[source]

Make a plot with log scaling on both the x- and y-axis.

Call signatures:

loglog([x], y, [fmt], data=None, **kwargs)
loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

This is just a thin wrapper around .plot which additionally changes both the x-axis and the y-axis to log scaling. All the concepts and parameters of plot can be used here as well.

The additional parameters base, subs and nonpositive control the x/y-axis properties. They are just forwarded to .Axes.set_xscale and .Axes.set_yscale. To use different properties on the x-axis and the y-axis, use e.g. ax.set_xscale("log", base=10); ax.set_yscale("log", base=2).

Parameters:
  • base (float, default: 10) – Base of the logarithm.

  • subs (sequence, optional) – The location of the minor ticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See .Axes.set_xscale/.Axes.set_yscale for details.

  • nonpositive ({'mask', 'clip'}, default: 'clip') – Non-positive values can be masked as invalid, or clipped to a very small positive number.

  • **kwargs – All parameters supported by .plot.

Returns:

Objects representing the plotted data.

Return type:

list of .Line2D

magnitude_spectrum(x, *, Fs=None, Fc=None, window=None, pad_to=None, sides=None, scale=None, data=None, **kwargs)[source]

Plot the magnitude spectrum.

Compute the magnitude spectrum of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.

Parameters:
  • x (1-D array or sequence) – Array or sequence containing the data.

  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).

  • scale ({'default', 'linear', 'dB'}) – The scaling of the values in the spec. ‘linear’ is no scaling. ‘dB’ returns the values in dB scale, i.e., the dB amplitude (20 * log10). ‘default’ is ‘linear’.

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

  • spectrum (1-D array) – The values for the magnitude spectrum before scaling (real valued).

  • freqs (1-D array) – The frequencies corresponding to the elements in spectrum.

  • line (~matplotlib.lines.Line2D) – The line created by this function.

See also

psd

Plots the power spectral density.

angle_spectrum

Plots the angles of the corresponding frequencies.

phase_spectrum

Plots the phase (unwrapped angle) of the corresponding frequencies.

specgram

Can plot the magnitude spectrum of segments within the signal in a colormap.

margins(*margins, x=None, y=None, tight=True)

Set or retrieve margins around the data for autoscaling axis limits.

This allows to configure the padding around the data without having to set explicit limits using ~.Axes.set_xlim / ~.Axes.set_ylim.

Autoscaling determines the axis limits by adding margin times the data interval as padding around the data. See the following illustration:

All input parameters must be floats greater than -0.5. Passing both positional and keyword arguments is invalid and will raise a TypeError. If no arguments (positional or otherwise) are provided, the current margins will remain unchanged and simply be returned.

The default margins are :rc:`axes.xmargin` and :rc:`axes.ymargin`.

Parameters:
  • *margins (float, optional) – If a single positional argument is provided, it specifies both margins of the x-axis and y-axis limits. If two positional arguments are provided, they will be interpreted as xmargin, ymargin. If setting the margin on a single axis is desired, use the keyword arguments described below.

  • x (float, optional) – Specific margin values for the x-axis and y-axis, respectively. These cannot be used with positional arguments, but can be used individually to alter on e.g., only the y-axis.

  • y (float, optional) – Specific margin values for the x-axis and y-axis, respectively. These cannot be used with positional arguments, but can be used individually to alter on e.g., only the y-axis.

  • tight (bool or None, default: True) – The tight parameter is passed to ~.axes.Axes.autoscale_view, which is executed after a margin is changed; the default here is True, on the assumption that when margins are specified, no additional padding to match tick marks is usually desired. Setting tight to None preserves the previous setting.

Returns:

xmargin, ymargin

Return type:

float

Notes

If a previously used Axes method such as pcolor() has set ~.Axes.use_sticky_edges to True, only the limits not set by the “sticky artists” will be modified. To force all margins to be set, set ~.Axes.use_sticky_edges to False before calling margins().

matshow(Z, **kwargs)[source]

Plot the values of a 2D matrix or array as color-coded image.

The matrix will be shown the way it would be printed, with the first row at the top. Row and column numbering is zero-based.

Parameters:
  • Z ((M, N) array-like) – The matrix to be displayed.

  • **kwargs (~matplotlib.axes.Axes.imshow arguments)

Return type:

~matplotlib.image.AxesImage

See also

imshow

More general function to plot data on a 2D regular raster.

Notes

This is just a convenience function wrapping .imshow to set useful defaults for displaying a matrix. In particular:

  • Set origin='upper'.

  • Set interpolation='nearest'.

  • Set aspect='equal'.

  • Ticks are placed to the left and above.

  • Ticks are formatted to show integer indices.

minorticks_off()

Remove minor ticks from the Axes.

minorticks_on()

Display minor ticks on the Axes.

Displaying minor ticks may reduce performance; you may turn them off using minorticks_off() if drawing speed is a problem.

property mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

name = 'rectilinear'
property patches
pchanged()

Call all of the registered callbacks.

This function is triggered internally when a property is changed.

pcolor(*args, shading=None, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, colorizer=None, data=None, **kwargs)[source]

Create a pseudocolor plot with a non-regular rectangular grid.

Call signature:

pcolor([X, Y,] C, /, **kwargs)

X and Y can be used to specify the corners of the quadrilaterals.

The arguments X, Y, C are positional-only.

Hint

pcolor() can be very slow for large arrays. In most cases you should use the similar but much faster ~.Axes.pcolormesh instead. See Differences between pcolor() and pcolormesh() for a discussion of the differences.

Parameters:
  • C (2D array-like) – The color-mapped values. Color-mapping is controlled by cmap, norm, vmin, and vmax.

  • X (array-like, optional) –

    The coordinates of the corners of quadrilaterals of a pcolormesh:

    (X[i+1, j], Y[i+1, j])       (X[i+1, j+1], Y[i+1, j+1])
                          ●╶───╴●
                          │     │
                          ●╶───╴●
        (X[i, j], Y[i, j])       (X[i, j+1], Y[i, j+1])
    

    Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.

    If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.

    If shading='nearest', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). The color C[i, j] will be centered on (X[i, j], Y[i, j]).

    If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.

  • Y (array-like, optional) –

    The coordinates of the corners of quadrilaterals of a pcolormesh:

    (X[i+1, j], Y[i+1, j])       (X[i+1, j+1], Y[i+1, j+1])
                          ●╶───╴●
                          │     │
                          ●╶───╴●
        (X[i, j], Y[i, j])       (X[i, j+1], Y[i, j+1])
    

    Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.

    If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.

    If shading='nearest', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). The color C[i, j] will be centered on (X[i, j], Y[i, j]).

    If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.

  • shading ({'flat', 'nearest', 'auto'}, default: :rc:`pcolor.shading`) –

    The fill style for the quadrilateral. Possible values:

    • ’flat’: A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by C[i, j]. The dimensions of X and Y should be one greater than those of C; if they are the same as C, then a deprecation warning is raised, and the last row and column of C are dropped.

    • ’nearest’: Each grid point will have a color centered on it, extending halfway between the adjacent grid centers. The dimensions of X and Y must be the same as C.

    • ’auto’: Choose ‘flat’ if dimensions of X and Y are one larger than C. Choose ‘nearest’ if dimensions are the same.

    See /gallery/images_contours_and_fields/pcolormesh_grids for more description.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) – The Colormap instance or registered colormap name used to map scalar data to colors.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

  • vmin (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • vmax (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

  • edgecolors ({'none', None, 'face', color, color sequence}, optional) –

    The color of the edges. Defaults to ‘none’. Possible values:

    • ’none’ or ‘’: No edge.

    • None: :rc:`patch.edgecolor` will be used. Note that currently :rc:`patch.force_edgecolor` has to be True for this to work.

    • ’face’: Use the adjacent face color.

    • A color or sequence of colors will set the edge color.

    The singular form edgecolor works as an alias.

  • alpha (float, default: None) – The alpha blending value of the face color, between 0 (transparent) and 1 (opaque). Note: The edgecolor is currently not affected by this.

  • snap (bool, default: False) – Whether to snap the mesh to pixel boundaries.

  • antialiaseds (bool, default: False) – The default antialiaseds is False if the default edgecolors=”none” is used. This eliminates artificial lines at patch boundaries, and works regardless of the value of alpha. If edgecolors is not “none”, then the default antialiaseds is taken from :rc:`patch.antialiased`. Stroking the edges may be preferred if alpha is 1, but will cause artifacts otherwise.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs – Additionally, the following arguments are allowed. They are passed along to the ~matplotlib.collections.PolyQuadMesh constructor:

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Return type:

matplotlib.collections.PolyQuadMesh

See also

pcolormesh

for an explanation of the differences between pcolor and pcolormesh.

imshow

If X and Y are each equidistant, ~.Axes.imshow can be a faster alternative.

Notes

Masked arrays

X, Y and C may be masked arrays. If either C[i, j], or one of the vertices surrounding C[i, j] (X or Y at [i, j], [i+1, j], [i, j+1], [i+1, j+1]) is masked, nothing is plotted.

Grid orientation

The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.

pcolorfast(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, colorizer=None, data=None, **kwargs)[source]

Create a pseudocolor plot with a non-regular rectangular grid.

Call signature:

ax.pcolorfast([X, Y], C, /, **kwargs)

The arguments X, Y, C are positional-only.

This method is similar to ~.Axes.pcolor and ~.Axes.pcolormesh. It’s designed to provide the fastest pcolor-type plotting with the Agg backend. To achieve this, it uses different algorithms internally depending on the complexity of the input grid (regular rectangular, non-regular rectangular or arbitrary quadrilateral).

Warning

This method is experimental. Compared to ~.Axes.pcolor or ~.Axes.pcolormesh it has some limitations:

  • It supports only flat shading (no outlines)

  • It lacks support for log scaling of the axes.

  • It does not have a pyplot wrapper.

Parameters:
  • C (array-like) –

    The image data. Supported array shapes are:

    • (M, N): an image with scalar data. Color-mapping is controlled by cmap, norm, vmin, and vmax.

    • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).

    • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

    The first two dimensions (M, N) define the rows and columns of the image.

    This parameter can only be passed positionally.

  • X (tuple or array-like, default: :py:class:`(0`, :py:class:`N)`, :py:class:`(0`, :py:class:`M)`) –

    X and Y are used to specify the coordinates of the quadrilaterals. There are different ways to do this:

    • Use tuples X=(xmin, xmax) and Y=(ymin, ymax) to define a uniform rectangular grid.

      The tuples define the outer edges of the grid. All individual quadrilaterals will be of the same size. This is the fastest version.

    • Use 1D arrays X, Y to specify a non-uniform rectangular grid.

      In this case X and Y have to be monotonic 1D arrays of length N+1 and M+1, specifying the x and y boundaries of the cells.

      The speed is intermediate. Note: The grid is checked, and if found to be uniform the fast version is used.

    • Use 2D arrays X, Y if you need an arbitrary quadrilateral grid (i.e. if the quadrilaterals are not rectangular).

      In this case X and Y are 2D arrays with shape (M + 1, N + 1), specifying the x and y coordinates of the corners of the colored quadrilaterals.

      This is the most general, but the slowest to render. It may produce faster and more compact output using ps, pdf, and svg backends, however.

    These arguments can only be passed positionally.

  • Y (tuple or array-like, default: :py:class:`(0`, :py:class:`N)`, :py:class:`(0`, :py:class:`M)`) –

    X and Y are used to specify the coordinates of the quadrilaterals. There are different ways to do this:

    • Use tuples X=(xmin, xmax) and Y=(ymin, ymax) to define a uniform rectangular grid.

      The tuples define the outer edges of the grid. All individual quadrilaterals will be of the same size. This is the fastest version.

    • Use 1D arrays X, Y to specify a non-uniform rectangular grid.

      In this case X and Y have to be monotonic 1D arrays of length N+1 and M+1, specifying the x and y boundaries of the cells.

      The speed is intermediate. Note: The grid is checked, and if found to be uniform the fast version is used.

    • Use 2D arrays X, Y if you need an arbitrary quadrilateral grid (i.e. if the quadrilaterals are not rectangular).

      In this case X and Y are 2D arrays with shape (M + 1, N + 1), specifying the x and y coordinates of the corners of the colored quadrilaterals.

      This is the most general, but the slowest to render. It may produce faster and more compact output using ps, pdf, and svg backends, however.

    These arguments can only be passed positionally.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if C is RGB(A).

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if C is RGB(A).

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if C is RGB(A).

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if C is RGB(A).

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –

    The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

    This parameter is ignored if C is RGB(A).

  • alpha (float, default: None) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • snap (bool, default: False) – Whether to snap the mesh to pixel boundaries.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs – Supported additional parameters depend on the type of grid. See return types of image for further description.

Returns:

The return type depends on the type of grid:

  • .AxesImage for a regular rectangular grid.

  • .PcolorImage for a non-regular rectangular grid.

  • .QuadMesh for a non-rectangular grid.

Return type:

.AxesImage or .PcolorImage or .QuadMesh

pcolormesh(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, colorizer=None, shading=None, antialiased=False, data=None, **kwargs)[source]

Create a pseudocolor plot with a non-regular rectangular grid.

Call signature:

pcolormesh([X, Y,] C, /, **kwargs)

X and Y can be used to specify the corners of the quadrilaterals.

The arguments X, Y, C are positional-only.

Hint

~.Axes.pcolormesh is similar to ~.Axes.pcolor. It is much faster and preferred in most cases. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh().

Parameters:
  • C (array-like) –

    The mesh data. Supported array shapes are:

    • (M, N) or M*N: a mesh with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.

    • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).

    • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

    The first two dimensions (M, N) define the rows and columns of the mesh data.

  • X (array-like, optional) –

    The coordinates of the corners of quadrilaterals of a pcolormesh:

    (X[i+1, j], Y[i+1, j])       (X[i+1, j+1], Y[i+1, j+1])
                          ●╶───╴●
                          │     │
                          ●╶───╴●
        (X[i, j], Y[i, j])       (X[i, j+1], Y[i, j+1])
    

    Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.

    If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.

    If shading='nearest' or 'gouraud', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). For 'nearest' the color C[i, j] is centered on (X[i, j], Y[i, j]). For 'gouraud', a smooth interpolation is carried out between the quadrilateral corners.

    If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.

  • Y (array-like, optional) –

    The coordinates of the corners of quadrilaterals of a pcolormesh:

    (X[i+1, j], Y[i+1, j])       (X[i+1, j+1], Y[i+1, j+1])
                          ●╶───╴●
                          │     │
                          ●╶───╴●
        (X[i, j], Y[i, j])       (X[i, j+1], Y[i, j+1])
    

    Note that the column index corresponds to the x-coordinate, and the row index corresponds to y. For details, see the Notes section below.

    If shading='flat' the dimensions of X and Y should be one greater than those of C, and the quadrilateral is colored due to the value at C[i, j]. If X, Y and C have equal dimensions, a warning will be raised and the last row and column of C will be ignored.

    If shading='nearest' or 'gouraud', the dimensions of X and Y should be the same as those of C (if not, a ValueError will be raised). For 'nearest' the color C[i, j] is centered on (X[i, j], Y[i, j]). For 'gouraud', a smooth interpolation is carried out between the quadrilateral corners.

    If X and/or Y are 1-D arrays or column vectors they will be expanded as needed into the appropriate 2D arrays, making a rectangular grid.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) – The Colormap instance or registered colormap name used to map scalar data to colors.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

  • vmin (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • vmax (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

  • edgecolors ({'none', None, 'face', color, color sequence}, optional) –

    The color of the edges. Defaults to ‘none’. Possible values:

    • ’none’ or ‘’: No edge.

    • None: :rc:`patch.edgecolor` will be used. Note that currently :rc:`patch.force_edgecolor` has to be True for this to work.

    • ’face’: Use the adjacent face color.

    • A color or sequence of colors will set the edge color.

    The singular form edgecolor works as an alias.

  • alpha (float, default: None) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • shading ({'flat', 'nearest', 'gouraud', 'auto'}, optional) –

    The fill style for the quadrilateral; defaults to :rc:`pcolor.shading`. Possible values:

    • ’flat’: A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by C[i, j]. The dimensions of X and Y should be one greater than those of C; if they are the same as C, then a deprecation warning is raised, and the last row and column of C are dropped.

    • ’nearest’: Each grid point will have a color centered on it, extending halfway between the adjacent grid centers. The dimensions of X and Y must be the same as C.

    • ’gouraud’: Each quad will be Gouraud shaded: The color of the corners (i’, j’) are given by C[i', j']. The color values of the area in between is interpolated from the corner values. The dimensions of X and Y must be the same as C. When Gouraud shading is used, edgecolors is ignored.

    • ’auto’: Choose ‘flat’ if dimensions of X and Y are one larger than C. Choose ‘nearest’ if dimensions are the same.

    See /gallery/images_contours_and_fields/pcolormesh_grids for more description.

  • snap (bool, default: False) – Whether to snap the mesh to pixel boundaries.

  • rasterized (bool, optional) – Rasterize the pcolormesh when drawing vector graphics. This can speed up rendering and produce smaller files for large data sets. See also /gallery/misc/rasterization_demo.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs – Additionally, the following arguments are allowed. They are passed along to the ~matplotlib.collections.QuadMesh constructor:

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased or aa or antialiaseds: bool or list of bools array: array-like capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clim: (vmin: float, vmax: float) clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .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: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float

Return type:

matplotlib.collections.QuadMesh

See also

pcolor

An alternative implementation with slightly different features. For a detailed discussion on the differences see Differences between pcolor() and pcolormesh().

imshow

If X and Y are each equidistant, ~.Axes.imshow can be a faster alternative.

Notes

Masked arrays

C may be a masked array. If C[i, j] is masked, the corresponding quadrilateral will be transparent. Masking of X and Y is not supported. Use ~.Axes.pcolor if you need this functionality.

Grid orientation

The grid orientation follows the standard matrix convention: An array C with shape (nrows, ncolumns) is plotted with the column number as X and the row number as Y.

Differences between pcolor() and pcolormesh()

Both methods are used to create a pseudocolor plot of a 2D array using quadrilaterals.

The main difference lies in the created object and internal data handling: While ~.Axes.pcolor returns a .PolyQuadMesh, ~.Axes.pcolormesh returns a .QuadMesh. The latter is more specialized for the given purpose and thus is faster. It should almost always be preferred.

There is also a slight difference in the handling of masked arrays. Both ~.Axes.pcolor and ~.Axes.pcolormesh support masked arrays for C. However, only ~.Axes.pcolor supports masked arrays for X and Y. The reason lies in the internal handling of the masked values. ~.Axes.pcolor leaves out the respective polygons from the PolyQuadMesh. ~.Axes.pcolormesh sets the facecolor of the masked elements to transparent. You can see the difference when using edgecolors. While all edges are drawn irrespective of masking in a QuadMesh, the edge between two adjacent masked quadrilaterals in ~.Axes.pcolor is not drawn as the corresponding polygons do not exist in the PolyQuadMesh. Because PolyQuadMesh draws each individual polygon, it also supports applying hatches and linestyles to the collection.

Another difference is the support of Gouraud shading in ~.Axes.pcolormesh, which is not available with ~.Axes.pcolor.

phase_spectrum(x, *, Fs=None, Fc=None, window=None, pad_to=None, sides=None, data=None, **kwargs)[source]

Plot the phase spectrum.

Compute the phase spectrum (unwrapped angle spectrum) of x. Data is padded to a length of pad_to and the windowing function window is applied to the signal.

Parameters:
  • x (1-D array or sequence) – Array or sequence containing the data

  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to the length of the input signal (i.e. no padding).

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

  • spectrum (1-D array) – The values for the phase spectrum in radians (real valued).

  • freqs (1-D array) – The frequencies corresponding to the elements in spectrum.

  • line (~matplotlib.lines.Line2D) – The line created by this function.

See also

magnitude_spectrum

Plots the magnitudes of the corresponding frequencies.

angle_spectrum

Plots the wrapped version of this function.

specgram

Can plot the phase spectrum of segments within the signal in a colormap.

pick(mouseevent)

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

Artist.set_picker, Artist.get_picker, Artist.pickable

pickable()

Return whether the artist is pickable.

See also

Artist.set_picker, Artist.get_picker, Artist.pick

pie(x, *, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, normalize=True, hatch=None, data=None)[source]

Plot a pie chart.

Make a pie chart of array x. The fractional area of each wedge is given by x/sum(x).

The wedges are plotted counterclockwise, by default starting from the x-axis.

Parameters:
  • x (1D array-like) – The wedge sizes.

  • explode (array-like, default: None) – If not None, is a len(x) array which specifies the fraction of the radius with which to offset each wedge.

  • labels (list, default: None) – A sequence of strings providing the labels for each wedge

  • colors (:mpltype:`color` or list of :mpltype:`color`, default: None) – A sequence of colors through which the pie chart will cycle. If None, will use the colors in the currently active cycle.

  • hatch (str or list, default: None) –

    Hatching pattern applied to all pie wedges or sequence of patterns through which the chart will cycle. For a list of valid patterns, see /gallery/shapes_and_collections/hatch_style_reference.

    Added in version 3.7.

  • autopct (None or str or callable, default: None) – If not None, autopct is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If autopct is a format string, the label will be fmt % pct. If autopct is a function, then it will be called.

  • pctdistance (float, default: 0.6) – The relative distance along the radius at which the text generated by autopct is drawn. To draw the text outside the pie, set pctdistance > 1. This parameter is ignored if autopct is None.

  • labeldistance (float or None, default: 1.1) – The relative distance along the radius at which the labels are drawn. To draw the labels inside the pie, set labeldistance < 1. If set to None, labels are not drawn but are still stored for use in .legend.

  • shadow (bool or dict, default: False) –

    If bool, whether to draw a shadow beneath the pie. If dict, draw a shadow passing the properties in the dict to .Shadow.

    Added in version 3.8: shadow can be a dict.

  • startangle (float, default: 0 degrees) – The angle by which the start of the pie is rotated, counterclockwise from the x-axis.

  • radius (float, default: 1) – The radius of the pie.

  • counterclock (bool, default: True) – Specify fractions direction, clockwise or counterclockwise.

  • wedgeprops (dict, default: None) – Dict of arguments passed to each .patches.Wedge of the pie. For example, wedgeprops = {'linewidth': 3} sets the width of the wedge border lines equal to 3. By default, clip_on=False. When there is a conflict between these properties and other keywords, properties passed to wedgeprops take precedence.

  • textprops (dict, default: None) – Dict of arguments to pass to the text objects.

  • center ((float, float), default: (0, 0)) – The coordinates of the center of the chart.

  • frame (bool, default: False) – Plot Axes frame with the chart if true.

  • rotatelabels (bool, default: False) – Rotate each label to the angle of the corresponding slice if true.

  • normalize (bool, default: True) – When True, always make a full pie by normalizing x so that sum(x) == 1. False makes a partial pie if sum(x) <= 1 and raises a ValueError for sum(x) > 1.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, explode, labels, colors

Returns:

  • patches (list) – A sequence of matplotlib.patches.Wedge instances

  • texts (list) – A list of the label .Text instances.

  • autotexts (list) – A list of .Text instances for the numeric labels. This will only be returned if the parameter autopct is not None.

Notes

The pie chart will probably look best if the figure and Axes are square, or the Axes aspect is equal. This method sets the aspect ratio of the axis to “equal”. The Axes aspect ratio can be controlled with .Axes.set_aspect.

plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]

Plot y versus x as lines and/or markers.

Call signatures:

plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

The coordinates of the points or line nodes are given by x, y.

The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It’s a shortcut string notation described in the Notes section below.

>>> plot(x, y)        # plot x and y using default line style and color
>>> plot(x, y, 'bo')  # plot x and y using blue circle markers
>>> plot(y)           # plot y using x as index array 0..N-1
>>> plot(y, 'r+')     # ditto, but with red plusses

You can use .Line2D properties as keyword arguments for more control on the appearance. Line properties and fmt can be mixed. The following two calls yield identical results:

>>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
...      linewidth=2, markersize=12)

When conflicting with fmt, keyword arguments take precedence.

Plotting labelled data

There’s a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index obj['y']). Instead of giving the data in x and y, you can provide the object in the data parameter and just give the labels for x and y:

>>> plot('xlabel', 'ylabel', data=obj)

All indexable objects are supported. This could e.g. be a dict, a pandas.DataFrame or a structured numpy array.

Plotting multiple sets of data

There are various ways to plot multiple sets of data.

  • The most straight forward way is just to call plot multiple times. Example:

    >>> plot(x1, y1, 'bo')
    >>> plot(x2, y2, 'go')
    
  • If x and/or y are 2D arrays, a separate data set will be drawn for every column. If both x and y are 2D, they must have the same shape. If only one of them is 2D with shape (N, m) the other must have length N and will be used for every data set m.

    Example:

    >>> x = [1, 2, 3]
    >>> y = np.array([[1, 2], [3, 4], [5, 6]])
    >>> plot(x, y)
    

    is equivalent to:

    >>> for col in range(y.shape[1]):
    ...     plot(x, y[:, col])
    
  • The third way is to specify multiple sets of [x], y, [fmt] groups:

    >>> plot(x1, y1, 'g^', x2, y2, 'g-')
    

    In this case, any additional keyword argument applies to all datasets. Also, this syntax cannot be combined with the data parameter.

By default, each line is assigned a different style specified by a ‘style cycle’. The fmt and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using :rc:`axes.prop_cycle`.

Parameters:
  • x (array-like or float) –

    The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

    These arguments cannot be passed as keywords.

  • y (array-like or float) –

    The horizontal / vertical coordinates of the data points. x values are optional and default to range(len(y)).

    Commonly, these parameters are 1D arrays.

    They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets).

    These arguments cannot be passed as keywords.

  • fmt (str, optional) –

    A format string, e.g. ‘ro’ for red circles. See the Notes section for a full description of the format strings.

    Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments.

    This argument cannot be passed as keyword.

  • data (indexable object, optional) –

    An object with labelled data. If given, provide the label names to plot in x and y.

    Note

    Technically there’s a slight ambiguity in calls where the second label is a valid fmt. plot('n', 'o', data=obj) could be plt(x, y) or plt(y, fmt). In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string plot('n', 'o', '', data=obj).

  • scalex (bool, default: True) – These parameters determine if the view limits are adapted to the data limits. The values are passed on to ~.axes.Axes.autoscale_view.

  • scaley (bool, default: True) – These parameters determine if the view limits are adapted to the data limits. The values are passed on to ~.axes.Axes.autoscale_view.

  • **kwargs (~matplotlib.lines.Line2D properties, optional) –

    kwargs are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:

    >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
    >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
    

    If you specify multiple lines with one plot call, the kwargs apply to all those lines. In case the label object is iterable, each element is used as labels for each set of data.

    Here is a list of available .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

A list of lines representing the plotted data.

Return type:

list of .Line2D

See also

scatter

XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart).

Notes

Format Strings

A format string consists of a part for color, marker and line:

fmt = '[marker][line][color]'

Each of them is optional. If not provided, the value from the style cycle is used. Exception: If line is given, but no marker, the data will be a line without markers.

Other combinations such as [color][marker][line] are also supported, but note that their parsing may be ambiguous.

Markers

character

description

'.'

point marker

','

pixel marker

'o'

circle marker

'v'

triangle_down marker

'^'

triangle_up marker

'<'

triangle_left marker

'>'

triangle_right marker

'1'

tri_down marker

'2'

tri_up marker

'3'

tri_left marker

'4'

tri_right marker

'8'

octagon marker

's'

square marker

'p'

pentagon marker

'P'

plus (filled) marker

'*'

star marker

'h'

hexagon1 marker

'H'

hexagon2 marker

'+'

plus marker

'x'

x marker

'X'

x (filled) marker

'D'

diamond marker

'd'

thin_diamond marker

'|'

vline marker

'_'

hline marker

Line Styles

character

description

'-'

solid line style

'--'

dashed line style

'-.'

dash-dot line style

':'

dotted line style

Example format strings:

'b'    # blue markers with default shape
'or'   # red circles
'-g'   # green solid line
'--'   # dashed line with default color
'^k:'  # black triangle_up markers connected by a dotted line

Colors

The supported color abbreviations are the single letter codes

character

color

'b'

blue

'g'

green

'r'

red

'c'

cyan

'm'

magenta

'y'

yellow

'k'

black

'w'

white

and the 'CN' colors that index into the default property cycle.

If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names ('green') or hex strings ('#008000').

plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, *, data=None, **kwargs)[source]

[Deprecated] Plot coercing the axis to treat floats as dates.

Deprecated since version 3.9: This method exists for historic reasons and will be removed in version 3.11.

  • datetime-like data should directly be plotted using ~.Axes.plot.

  • If you need to plot plain numeric data as date-format or need to set a timezone, call ax.xaxis.axis_date / ax.yaxis.axis_date before ~.Axes.plot. See .Axis.axis_date.

Similar to .plot, this plots y vs. x as lines or markers. However, the axis labels are formatted as dates depending on xdate and ydate. Note that .plot will work with datetime and numpy.datetime64 objects without resorting to this method.

Parameters:
  • x (array-like) – The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates.

  • y (array-like) – The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates.

  • fmt (str, optional) – The plot format string. For details, see the corresponding parameter in .plot.

  • tz (timezone string or datetime.tzinfo, default: :rc:`timezone`) – The time zone to use in labeling dates.

  • xdate (bool, default: True) – If True, the x-axis will be interpreted as Matplotlib dates.

  • ydate (bool, default: False) – If True, the y-axis will be interpreted as Matplotlib dates.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

Objects representing the plotted data.

Return type:

list of .Line2D

See also

matplotlib.dates

Helper functions on dates.

matplotlib.dates.date2num

Convert dates to num.

matplotlib.dates.num2date

Convert num to dates.

matplotlib.dates.drange

Create an equally spaced sequence of dates.

Notes

If you are using custom date tickers and formatters, it may be necessary to set the formatters/locators after the call to .plot_date. .plot_date will set the default tick locator to .AutoDateLocator (if the tick locator is not already set to a .DateLocator instance) and the default tick formatter to .AutoDateFormatter (if the tick formatter is not already set to a .DateFormatter instance).

Deprecated since version 3.9: Use plot instead.

properties()

Return a dictionary of all the properties of the artist.

psd(x, *, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, data=None, **kwargs)[source]

Plot the power spectral density.

The power spectral density \(P_{xx}\) by Welch’s average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The \(|\mathrm{fft}(i)|^2\) of each segment \(i\) are averaged to compute \(P_{xx}\), with a scaling to correct for power loss due to windowing.

If len(x) < NFFT, it will be zero padded to NFFT.

Parameters:
  • x (1-D array or sequence) – Array or sequence containing the data

  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT

  • NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.

  • detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.

  • scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.

  • noverlap (int, default: 0 (no overlap)) – The number of points of overlap between segments.

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • return_line (bool, default: False) – Whether to include the line object plotted in the returned values.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x

  • **kwargs

    Keyword arguments control the .Line2D properties:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

  • Pxx (1-D array) – The values for the power spectrum \(P_{xx}\) before scaling (real valued).

  • freqs (1-D array) – The frequencies corresponding to the elements in Pxx.

  • line (~matplotlib.lines.Line2D) – The line created by this function. Only returned if return_line is True.

See also

specgram

Differs in the default overlap; in not returning the mean of the segment periodograms; in returning the times of the segments; and in plotting a colormap instead of a line.

magnitude_spectrum

Plots the magnitude spectrum.

csd

Plots the spectral density between two signals.

Notes

For plotting, the power is plotted as \(10\log_{10}(P_{xx})\) for decibels, though Pxx itself is returned.

References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)

quiver(*args, data=None, **kwargs)[source]

Plot a 2D field of arrows.

Call signature:

quiver([X, Y], U, V, [C], /, **kwargs)

X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color. The arguments X, Y, U, V, C are positional-only.

Arrow length

The default settings auto-scales the length of the arrows to a reasonable size. To change this behavior see the scale and scale_units parameters.

Arrow shape

The arrow shape is determined by width, headwidth, headlength and headaxislength. See the notes below.

Arrow styling

Each arrow is internally represented by a filled polygon with a default edge linewidth of 0. As a result, an arrow is rather a filled area, not a line with a head, and .PolyCollection properties like linewidth, edgecolor, facecolor, etc. act accordingly.

Parameters:
  • X (1D or 2D array-like, optional) –

    The x and y coordinates of the arrow locations.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • Y (1D or 2D array-like, optional) –

    The x and y coordinates of the arrow locations.

    If not given, they will be generated as a uniform integer meshgrid based on the dimensions of U and V.

    If X and Y are 1D but U, V are 2D, X, Y are expanded to 2D using X, Y = np.meshgrid(X, Y). In this case len(X) and len(Y) must match the column and row dimensions of U and V.

  • U (1D or 2D array-like) –

    The x and y direction components of the arrow vectors. The interpretation of these components (in data or in screen space) depends on angles.

    U and V must have the same number of elements, matching the number of arrow locations in X, Y. U and V may be masked. Locations masked in any of U, V, and C will not be drawn.

  • V (1D or 2D array-like) –

    The x and y direction components of the arrow vectors. The interpretation of these components (in data or in screen space) depends on angles.

    U and V must have the same number of elements, matching the number of arrow locations in X, Y. U and V may be masked. Locations masked in any of U, V, and C will not be drawn.

  • C (1D or 2D array-like, optional) –

    Numeric data that defines the arrow colors by colormapping via norm and cmap.

    This does not support explicit colors. If you want to set colors directly, use color instead. The size of C must match the number of arrow locations.

  • angles ({'uv', 'xy'} or array-like, default: 'uv') –

    Method for determining the angle of the arrows.

    • ’uv’: Arrow directions are based on display coordinates; i.e. a 45° angle will always show up as diagonal on the screen, irrespective of figure or Axes aspect ratio or Axes data ranges. This is useful when the arrows represent a quantity whose direction is not tied to the x and y data coordinates.

      If U == V the orientation of the arrow on the plot is 45 degrees counter-clockwise from the horizontal axis (positive to the right).

    • ’xy’: Arrow direction in data coordinates, i.e. the arrows point from (x, y) to (x+u, y+v). This is ideal for vector fields or gradient plots where the arrows should directly represent movements or gradients in the x and y directions.

    • Arbitrary angles may be specified explicitly as an array of values in degrees, counter-clockwise from the horizontal axis.

      In this case U, V is only used to determine the length of the arrows.

      For example, angles=[30, 60, 90] will orient the arrows at 30, 60, and 90 degrees respectively, regardless of the U and V components.

    Note: inverting a data axis will correspondingly invert the arrows only with angles='xy'.

  • pivot ({'tail', 'mid', 'middle', 'tip'}, default: 'tail') –

    The part of the arrow that is anchored to the X, Y grid. The arrow rotates about this point.

    ’mid’ is a synonym for ‘middle’.

  • scale (float, optional) –

    Scales the length of the arrow inversely.

    Number of data values represented by one unit of arrow length on the plot. For example, if the data represents velocity in meters per second (m/s), the scale parameter determines how many meters per second correspond to one unit of arrow length relative to the width of the plot. Smaller scale parameter makes the arrow longer.

    By default, an autoscaling algorithm is used to scale the arrow length to a reasonable size, which is based on the average vector length and the number of vectors.

    The arrow length unit is given by the scale_units parameter.

  • scale_units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width') –

    The physical image unit, which is used for rendering the scaled arrow data U, V.

    The rendered arrow length is given by

    length in x direction = $frac{u}{mathrm{scale}} mathrm{scale_unit}$

    length in y direction = $frac{v}{mathrm{scale}} mathrm{scale_unit}$

    For example, (u, v) = (0.5, 0) with scale=10, scale_unit="width" results in a horizontal arrow with a length of 0.5 / 10 * “width”, i.e. 0.05 times the Axes width.

    Supported values are:

    • ’width’ or ‘height’: The arrow length is scaled relative to the width or height

      of the Axes. For example, scale_units='width', scale=1.0, will result in an arrow length of width of the Axes.

    • ’dots’: The arrow length of the arrows is in measured in display dots (pixels).

    • ’inches’: Arrow lengths are scaled based on the DPI (dots per inch) of the figure.

      This ensures that the arrows have a consistent physical size on the figure, in inches, regardless of data values or plot scaling. For example, (u, v) = (1, 0) with scale_units='inches', scale=2 results in a 0.5 inch-long arrow.

    • ’x’ or ‘y’: The arrow length is scaled relative to the x or y axis units.

      For example, (u, v) = (0, 1) with scale_units='x', scale=1 results in a vertical arrow with the length of 1 x-axis unit.

    • ’xy’: Arrow length will be same as ‘x’ or ‘y’ units.

      This is useful for creating vectors in the x-y plane where u and v have the same units as x and y. To plot vectors in the x-y plane with u and v having the same units as x and y, use angles='xy', scale_units='xy', scale=1.

    Note: Setting scale_units without setting scale does not have any effect because the scale units only differ by a constant factor and that is rescaled through autoscaling.

  • units ({'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width') –

    Affects the arrow size (except for the length). In particular, the shaft width is measured in multiples of this unit.

    Supported values are:

    • ’width’, ‘height’: The width or height of the Axes.

    • ’dots’, ‘inches’: Pixels or inches based on the figure dpi.

    • ’x’, ‘y’, ‘xy’: X, Y or \(\sqrt{X^2 + Y^2}\) in data units.

    The following table summarizes how these values affect the visible arrow size under zooming and figure size changes:

    units

    zoom

    figure size change

    ’x’, ‘y’, ‘xy’

    arrow size scales

    ‘width’, ‘height’

    arrow size scales

    ’dots’, ‘inches’

  • width (float, optional) –

    Shaft width in arrow units. All head parameters are relative to width.

    The default depends on choice of units above, and number of vectors; a typical starting value is about 0.005 times the width of the plot.

  • headwidth (float, default: 3) – Head width as multiple of shaft width. See the notes below.

  • headlength (float, default: 5) – Head length as multiple of shaft width. See the notes below.

  • headaxislength (float, default: 4.5) – Head length at shaft intersection as multiple of shaft width. See the notes below.

  • minshaft (float, default: 1) – Length below which arrow scales, in units of head length. Do not set this to less than 1, or small arrows will look terrible!

  • minlength (float, default: 1) – Minimum length as a multiple of shaft width; if an arrow length is less than this, plot a dot (hexagon) of this diameter instead.

  • color (:mpltype:`color` or list :mpltype:`color`, optional) –

    Explicit color(s) for the arrows. If C has been set, color has no effect.

    This is a synonym for the .PolyCollection facecolor parameter.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs (~matplotlib.collections.PolyCollection properties, optional) –

    All other keyword arguments are passed on to .PolyCollection:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: list of array-like picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None verts: list of array-like verts_and_codes: unknown visible: bool zorder: float

Return type:

~matplotlib.quiver.Quiver

See also

Axes.quiverkey

Add a key to a quiver plot.

Notes

Arrow shape

The arrow is drawn as a polygon using the nodes as shown below. The values headwidth, headlength, and headaxislength are in units of width.

_static/quiver_sizes.svg

The defaults give a slightly swept-back arrow. Here are some guidelines how to get other head shapes:

  • To make the head a triangle, make headaxislength the same as headlength.

  • To make the arrow more pointed, reduce headwidth or increase headlength and headaxislength.

  • To make the head smaller relative to the shaft, scale down all the head parameters proportionally.

  • To remove the head completely, set all head parameters to 0.

  • To get a diamond-shaped head, make headaxislength larger than headlength.

  • Warning: For headaxislength < (headlength / headwidth), the “headaxis” nodes (i.e. the ones connecting the head with the shaft) will protrude out of the head in forward direction so that the arrow head looks broken.

quiverkey(Q, X, Y, U, label, **kwargs)[source]

Add a key to a quiver plot.

The positioning of the key depends on X, Y, coordinates, and labelpos. If labelpos is ‘N’ or ‘S’, X, Y give the position of the middle of the key arrow. If labelpos is ‘E’, X, Y positions the head, and if labelpos is ‘W’, X, Y positions the tail; in either of these two cases, X, Y is somewhere in the middle of the arrow+label key object.

Parameters:
  • Q (~matplotlib.quiver.Quiver) – A .Quiver object as returned by a call to ~.Axes.quiver().

  • X (float) – The location of the key.

  • Y (float) – The location of the key.

  • U (float) – The length of the key.

  • label (str) – The key label (e.g., length and units of the key).

  • angle (float, default: 0) – The angle of the key arrow, in degrees anti-clockwise from the horizontal axis.

  • coordinates ({'axes', 'figure', 'data', 'inches'}, default: 'axes') – Coordinate system and units for X, Y: ‘axes’ and ‘figure’ are normalized coordinate systems with (0, 0) in the lower left and (1, 1) in the upper right; ‘data’ are the axes data coordinates (used for the locations of the vectors in the quiver plot itself); ‘inches’ is position in the figure in inches, with (0, 0) at the lower left corner.

  • color (:mpltype:`color`) – Overrides face and edge colors from Q.

  • labelpos ({'N', 'S', 'E', 'W'}) – Position the label above, below, to the right, to the left of the arrow, respectively.

  • labelsep (float, default: 0.1) – Distance in inches between the arrow and the label.

  • labelcolor (:mpltype:`color`, default: :rc:`text.color`) – Label color.

  • fontproperties (dict, optional) – A dictionary with keyword arguments accepted by the ~matplotlib.font_manager.FontProperties initializer: family, style, variant, size, weight.

  • zorder (float) – The zorder of the key. The default is 0.1 above Q.

  • **kwargs – Any additional keyword arguments are used to override vector properties taken from Q.

redraw_in_frame()

Efficiently redraw Axes data, but not axis ticks, labels, etc.

relim(visible_only=False)

Recompute the data limits based on current artists.

At present, .Collection instances are not supported.

Parameters:

visible_only (bool, default: False) – Whether to exclude invisible artists.

remove()

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 ~.axes.Axes.relim to update the Axes limits if desired.

Note: ~.axes.Axes.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)

Remove a callback based on its observer id.

See also

add_callback

reset_position()

Reset the active position to the original position.

This undoes changes to the active position (as defined in .set_position) which may have been performed to satisfy fixed-aspect constraints.

scatter(x, y, s=None, c=None, *, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None, colorizer=None, plotnonfinite=False, data=None, **kwargs)[source]

A scatter plot of y vs. x with varying marker size and/or color.

Parameters:
  • x (float or array-like, shape (n, )) – The data positions.

  • y (float or array-like, shape (n, )) – The data positions.

  • s (float or array-like, shape (n, ), optional) –

    The marker size in points**2 (typographic points are 1/72 in.). Default is rcParams['lines.markersize'] ** 2.

    The linewidth and edgecolor can visually interact with the marker size, and can lead to artifacts if the marker size is smaller than the linewidth.

    If the linewidth is greater than 0 and the edgecolor is anything but ‘none’, then the effective size of the marker will be increased by half the linewidth because the stroke will be centered on the edge of the shape.

    To eliminate the marker edge either set linewidth=0 or edgecolor=’none’.

  • c (array-like or list of :mpltype:`color` or :mpltype:`color`, optional) –

    The marker colors. Possible values:

    • A scalar or sequence of n numbers to be mapped to colors using cmap and norm.

    • A 2D array in which the rows are RGB or RGBA.

    • A sequence of colors of length n.

    • A single color format string.

    Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value-matching will have precedence in case of a size matching with x and y.

    If you wish to specify a single color for all points prefer the color keyword argument.

    Defaults to None. In that case the marker color is determined by the value of color, facecolor or facecolors. In case those are not specified or None, the marker color is determined by the next color of the Axes’ current “shape and fill” color cycle. This cycle defaults to :rc:`axes.prop_cycle`.

  • marker (~.markers.MarkerStyle, default: :rc:`scatter.marker`) – The marker style. marker can be either an instance of the class or the text shorthand for a particular marker. See matplotlib.markers for more information about marker styles.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if c is RGB(A).

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if c is RGB(A).

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if c is RGB(A).

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if c is RGB(A).

  • alpha (float, default: None) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • linewidths (float or array-like, default: :rc:`lines.linewidth`) – The linewidth of the marker edges. Note: The default edgecolors is ‘face’. You may want to change this as well.

  • edgecolors ({'face', 'none', *None*} or :mpltype:`color` or list of :mpltype:`color`, default: :rc:`scatter.edgecolors`) –

    The edge color of the marker. Possible values:

    • ’face’: The edge color will always be the same as the face color.

    • ’none’: No patch boundary will be drawn.

    • A color or sequence of colors.

    For non-filled markers, edgecolors is ignored. Instead, the color is determined like with ‘face’, i.e. from c, colors, or facecolors.

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –

    The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

    This parameter is ignored if c is RGB(A).

  • plotnonfinite (bool, default: False) – Whether to plot points with nonfinite c (i.e. inf, -inf or nan). If True the points are drawn with the bad colormap color (see .Colormap.set_bad).

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y, s, linewidths, edgecolors, c, facecolor, facecolors, color

  • **kwargs (~matplotlib.collections.PathCollection properties) – Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .AbstractPathEffect paths: unknown picker: None or bool or float or callable pickradius: float rasterized: bool sizes: numpy.ndarray or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float

Return type:

~matplotlib.collections.PathCollection

See also

plot

To plot scatter plots when markers are identical in size and color.

Notes

  • The .plot function will be faster for scatterplots where markers don’t vary in size or color.

  • Any or all of x, y, s, and c may be masked arrays, in which case all masks will be combined and only unmasked points will be plotted.

  • Fundamentally, scatter works with 1D arrays; x, y, s, and c may be input as N-D arrays, but within scatter they will be flattened. The exception is c, which will be flattened only if its size matches the size of x and y.

secondary_xaxis(location, functions=None, *, transform=None, **kwargs)[source]

Add a second x-axis to this ~.axes.Axes.

For example if we want to have a second scale for the data plotted on the xaxis.

Warning

This method is experimental as of 3.1, and the API may change.

Parameters:
  • location ({'top', 'bottom', 'left', 'right'} or float) – The position to put the secondary axis. Strings can be ‘top’ or ‘bottom’ for orientation=’x’ and ‘right’ or ‘left’ for orientation=’y’. A float indicates the relative position on the parent Axes to put the new Axes, 0.0 being the bottom (or left) and 1.0 being the top (or right).

  • functions (2-tuple of func, or Transform with an inverse) –

    If a 2-tuple of functions, the user specifies the transform function and its inverse. i.e. functions=(lambda x: 2 / x, lambda x: 2 / x) would be an reciprocal transform with a factor of 2. Both functions must accept numpy arrays as input.

    The user can also directly supply a subclass of .transforms.Transform so long as it has an inverse.

    See /gallery/subplots_axes_and_figures/secondary_axis for examples of making these conversions.

  • transform (.Transform, optional) –

    If specified, location will be placed relative to this transform (in the direction of the axis) rather than the parent’s axis. i.e. a secondary x-axis will use the provided y transform and the x transform of the parent.

    Added in version 3.9.

  • **kwargs (~matplotlib.axes.Axes properties.) – Other miscellaneous Axes parameters.

Returns:

ax

Return type:

axes._secondary_axes.SecondaryAxis

Examples

The main axis shows frequency, and the secondary axis shows period.

To add a secondary axis relative to your data, you can pass a transform to the new axis.

secondary_yaxis(location, functions=None, *, transform=None, **kwargs)[source]

Add a second y-axis to this ~.axes.Axes.

For example if we want to have a second scale for the data plotted on the yaxis.

Warning

This method is experimental as of 3.1, and the API may change.

Parameters:
  • location ({'top', 'bottom', 'left', 'right'} or float) – The position to put the secondary axis. Strings can be ‘top’ or ‘bottom’ for orientation=’x’ and ‘right’ or ‘left’ for orientation=’y’. A float indicates the relative position on the parent Axes to put the new Axes, 0.0 being the bottom (or left) and 1.0 being the top (or right).

  • functions (2-tuple of func, or Transform with an inverse) –

    If a 2-tuple of functions, the user specifies the transform function and its inverse. i.e. functions=(lambda x: 2 / x, lambda x: 2 / x) would be an reciprocal transform with a factor of 2. Both functions must accept numpy arrays as input.

    The user can also directly supply a subclass of .transforms.Transform so long as it has an inverse.

    See /gallery/subplots_axes_and_figures/secondary_axis for examples of making these conversions.

  • transform (.Transform, optional) –

    If specified, location will be placed relative to this transform (in the direction of the axis) rather than the parent’s axis. i.e. a secondary x-axis will use the provided y transform and the x transform of the parent.

    Added in version 3.9.

  • **kwargs (~matplotlib.axes.Axes properties.) – Other miscellaneous Axes parameters.

Returns:

ax

Return type:

axes._secondary_axes.SecondaryAxis

Examples

Add a secondary Axes that converts from radians to degrees

To add a secondary axis relative to your data, you can pass a transform to the new axis.

semilogx(*args, **kwargs)[source]

Make a plot with log scaling on the x-axis.

Call signatures:

semilogx([x], y, [fmt], data=None, **kwargs)
semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

This is just a thin wrapper around .plot which additionally changes the x-axis to log scaling. All the concepts and parameters of plot can be used here as well.

The additional parameters base, subs, and nonpositive control the x-axis properties. They are just forwarded to .Axes.set_xscale.

Parameters:
  • base (float, default: 10) – Base of the x logarithm.

  • subs (array-like, optional) – The location of the minor xticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See .Axes.set_xscale for details.

  • nonpositive ({'mask', 'clip'}, default: 'clip') – Non-positive values in x can be masked as invalid, or clipped to a very small positive number.

  • **kwargs – All parameters supported by .plot.

Returns:

Objects representing the plotted data.

Return type:

list of .Line2D

semilogy(*args, **kwargs)[source]

Make a plot with log scaling on the y-axis.

Call signatures:

semilogy([x], y, [fmt], data=None, **kwargs)
semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

This is just a thin wrapper around .plot which additionally changes the y-axis to log scaling. All the concepts and parameters of plot can be used here as well.

The additional parameters base, subs, and nonpositive control the y-axis properties. They are just forwarded to .Axes.set_yscale.

Parameters:
  • base (float, default: 10) – Base of the y logarithm.

  • subs (array-like, optional) – The location of the minor yticks. If None, reasonable locations are automatically chosen depending on the number of decades in the plot. See .Axes.set_yscale for details.

  • nonpositive ({'mask', 'clip'}, default: 'clip') – Non-positive values in y can be masked as invalid, or clipped to a very small positive number.

  • **kwargs – All parameters supported by .plot.

Returns:

Objects representing the plotted data.

Return type:

list of .Line2D

set(*, adjustable=<UNSET>, agg_filter=<UNSET>, alpha=<UNSET>, anchor=<UNSET>, animated=<UNSET>, aspect=<UNSET>, autoscale_on=<UNSET>, autoscalex_on=<UNSET>, autoscaley_on=<UNSET>, axes_locator=<UNSET>, axisbelow=<UNSET>, box_aspect=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, facecolor=<UNSET>, forward_navigation_events=<UNSET>, frame_on=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, mouseover=<UNSET>, navigate=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, position=<UNSET>, prop_cycle=<UNSET>, rasterization_zorder=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, subplotspec=<UNSET>, title=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, xbound=<UNSET>, xlabel=<UNSET>, xlim=<UNSET>, xmargin=<UNSET>, xscale=<UNSET>, xticklabels=<UNSET>, xticks=<UNSET>, ybound=<UNSET>, ylabel=<UNSET>, ylim=<UNSET>, ymargin=<UNSET>, yscale=<UNSET>, yticklabels=<UNSET>, yticks=<UNSET>, zorder=<UNSET>)

Set multiple properties at once.

Supported properties are

Properties:

adjustable: {‘box’, ‘datalim’} agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None anchor: (float, float) or {‘C’, ‘SW’, ‘S’, ‘SE’, ‘E’, ‘NE’, …} animated: bool aspect: {‘auto’, ‘equal’} or float autoscale_on: bool autoscalex_on: unknown autoscaley_on: unknown axes_locator: Callable[[Axes, Renderer], Bbox] axisbelow: bool or ‘line’ box_aspect: float or None clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None facecolor or fc: :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure forward_navigation_events: bool or “auto” frame_on: bool gid: str in_layout: bool label: object mouseover: bool navigate: bool navigate_mode: unknown path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: [left, bottom, width, height] or ~matplotlib.transforms.Bbox prop_cycle: ~cycler.Cycler rasterization_zorder: float or None rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None subplotspec: unknown title: str transform: ~matplotlib.transforms.Transform url: str visible: bool xbound: (lower: float, upper: float) xlabel: str xlim: (left: float, right: float) xmargin: float greater than -0.5 xscale: unknown xticklabels: unknown xticks: unknown ybound: (lower: float, upper: float) ylabel: str ylim: (bottom: float, top: float) ymargin: float greater than -0.5 yscale: unknown yticklabels: unknown yticks: unknown zorder: float

set_adjustable(adjustable, share=False)

Set how the Axes adjusts to achieve the required aspect ratio.

Parameters:
  • adjustable ({'box', 'datalim'}) – If ‘box’, change the physical dimensions of the Axes. If ‘datalim’, change the x or y data limits. This may ignore explicitly defined axis limits.

  • share (bool, default: False) – If True, apply the settings to all shared Axes.

See also

matplotlib.axes.Axes.set_aspect

For a description of aspect handling.

Notes

Shared Axes (of which twinned Axes are a special case) impose restrictions on how aspect ratios can be imposed. For twinned Axes, use ‘datalim’. For Axes that share both x and y, use ‘box’. Otherwise, either ‘datalim’ or ‘box’ may be used. These limitations are partly a requirement to avoid over-specification, and partly a result of the particular implementation we are currently using, in which the adjustments for aspect ratios are done sequentially and independently on each Axes as it is drawn.

set_agg_filter(filter_func)

Set the agg filter.

Parameters:

filter_func (callable) –

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

set_alpha(alpha)

Set the alpha value used for blending - not supported on all backends.

Parameters:

alpha (float or None) – alpha must be within the 0-1 range, inclusive.

set_anchor(anchor, share=False)

Define the anchor location.

The actual drawing area (active position) of the Axes may be smaller than the Bbox (original position) when a fixed aspect is required. The anchor defines where the drawing area will be located within the available space.

Parameters:
  • anchor ((float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}) –

    Either an (x, y) pair of relative coordinates (0 is left or bottom, 1 is right or top), ‘C’ (center), or a cardinal direction (‘SW’, southwest, is bottom left, etc.). str inputs are shorthands for (x, y) coordinates, as shown in the following diagram:

    ┌─────────────────┬─────────────────┬─────────────────┐
    │ 'NW' (0.0, 1.0) │ 'N' (0.5, 1.0)  │ 'NE' (1.0, 1.0) │
    ├─────────────────┼─────────────────┼─────────────────┤
    │ 'W'  (0.0, 0.5) │ 'C' (0.5, 0.5)  │ 'E'  (1.0, 0.5) │
    ├─────────────────┼─────────────────┼─────────────────┤
    │ 'SW' (0.0, 0.0) │ 'S' (0.5, 0.0)  │ 'SE' (1.0, 0.0) │
    └─────────────────┴─────────────────┴─────────────────┘
    

  • share (bool, default: False) – If True, apply the settings to all shared Axes.

See also

matplotlib.axes.Axes.set_aspect

for a description of aspect handling.

set_animated(b)

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 approach is used to speed up animations using blitting.

See also matplotlib.animation and blitting.

Parameters:

b (bool)

set_aspect(aspect, adjustable=None, anchor=None, share=False)

Set the aspect ratio of the Axes scaling, i.e. y/x-scale.

Parameters:
  • aspect ({'auto', 'equal'} or float) –

    Possible values:

    • ’auto’: fill the position rectangle with data.

    • ’equal’: same as aspect=1, i.e. same scaling for x and y.

    • float: The displayed size of 1 unit in y-data coordinates will be aspect times the displayed size of 1 unit in x-data coordinates; e.g. for aspect=2 a square in data coordinates will be rendered with a height of twice its width.

  • adjustable (None or {'box', 'datalim'}, optional) – If not None, this defines which parameter will be adjusted to meet the required aspect. See .set_adjustable for further details.

  • anchor (None or str or (float, float), optional) –

    If not None, this defines where the Axes will be drawn if there is extra space due to aspect constraints. The most common way to specify the anchor are abbreviations of cardinal directions:

    value

    description

    ’C’

    centered

    ’SW’

    lower left corner

    ’S’

    middle of bottom edge

    ’SE’

    lower right corner

    etc.

    See ~.Axes.set_anchor for further details.

  • share (bool, default: False) – If True, apply the settings to all shared Axes.

See also

matplotlib.axes.Axes.set_adjustable

Set how the Axes adjusts to achieve the required aspect ratio.

matplotlib.axes.Axes.set_anchor

Set the position in case of extra space.

set_autoscale_on(b)

Set whether autoscaling is applied to each axis on the next draw or call to .Axes.autoscale_view.

Parameters:

b (bool)

set_autoscalex_on(b)

Set whether the xaxis is autoscaled when drawing or by .Axes.autoscale_view.

If b is None, then the value is not changed.

Parameters:

b (bool)

set_autoscaley_on(b)

Set whether the yaxis is autoscaled when drawing or by .Axes.autoscale_view.

If b is None, then the value is not changed.

Parameters:

b (bool)

set_axes_locator(locator)

Set the Axes locator.

Parameters:

locator (Callable[[Axes, Renderer], Bbox])

set_axis_off()

Hide all visual components of the x- and y-axis.

This sets a flag to suppress drawing of all axis decorations, i.e. axis labels, axis spines, and the axis tick component (tick markers, tick labels, and grid lines). Individual visibility settings of these components are ignored as long as set_axis_off() is in effect.

set_axis_on()

Do not hide all visual components of the x- and y-axis.

This reverts the effect of a prior .set_axis_off() call. Whether the individual axis decorations are drawn is controlled by their respective visibility settings.

This is on by default.

set_axisbelow(b)

Set whether axis ticks and gridlines are above or below most artists.

This controls the zorder of the ticks and gridlines. For more information on the zorder see /gallery/misc/zorder_demo.

Parameters:

b (bool or 'line') –

Possible values:

  • True (zorder = 0.5): Ticks and gridlines are below patches and lines, though still above images.

  • ’line’ (zorder = 1.5): Ticks and gridlines are above patches (e.g. rectangles, with default zorder = 1) but still below lines and markers (with their default zorder = 2).

  • False (zorder = 2.5): Ticks and gridlines are above patches and lines / markers.

Notes

For more control, call the ~.Artist.set_zorder method of each axis.

See also

get_axisbelow

set_box_aspect(aspect=None)

Set the Axes box aspect, i.e. the ratio of height to width.

This defines the aspect of the Axes in figure space and is not to be confused with the data aspect (see ~.Axes.set_aspect).

Parameters:

aspect (float or None) –

Changes the physical dimensions of the Axes, such that the ratio of the Axes height to the Axes width in physical units is equal to aspect. Defining a box aspect will change the adjustable property to ‘datalim’ (see ~.Axes.set_adjustable).

None will disable a fixed box aspect so that height and width of the Axes are chosen independently.

See also

matplotlib.axes.Axes.set_aspect

for a description of aspect handling.

set_clip_box(clipbox)

Set the artist’s clip .Bbox.

Parameters:

clipbox (~matplotlib.transforms.BboxBase or None) – Will typically be created from a .TransformedBbox. For instance, TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes) is the default clipping for an artist added to an Axes.

set_clip_on(b)

Set whether the artist uses clipping.

When False, artists will be visible outside the Axes which can lead to unexpected results.

Parameters:

b (bool)

set_clip_path(path, transform=None)

Set the artist’s clip path.

Parameters:
  • path (~matplotlib.patches.Patch 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.

  • transform (~matplotlib.transforms.Transform, 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 ~.Artist.set), a tuple (path, transform) is also accepted as a single positional parameter.

set_facecolor(color)

Set the facecolor of the Axes.

Parameters:

color (:mpltype:`color`)

set_fc(color)

Alias for set_facecolor.

set_figure(fig)

Set the .Figure or .SubFigure instance the artist belongs to.

Parameters:

fig (~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure)

set_forward_navigation_events(forward)

Set how pan/zoom events are forwarded to Axes below this one.

Parameters:

forward (bool or "auto") –

Possible values:

  • True: Forward events to other axes with lower or equal zorder.

  • False: Events are only executed on this axes.

  • ”auto”: Default behaviour (True for axes with an invisible patch and False otherwise)

See also

matplotlib.axes.Axes.set_navigate

set_frame_on(b)

Set whether the Axes rectangle patch is drawn.

Parameters:

b (bool)

set_gid(gid)

Set the (group) id for the artist.

Parameters:

gid (str)

set_in_layout(in_layout)

Set if artist is to be included in layout calculations, E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

Parameters:

in_layout (bool)

set_label(s)

Set a label that will be displayed in the legend.

Parameters:

s (object) – s will be converted to a string by calling str.

set_mouseover(mouseover)

Set whether this artist is queried for custom context information when the mouse cursor moves over it.

Parameters:

mouseover (bool)

See also

get_cursor_data, ToolCursorPosition, NavigationToolbar2

set_navigate(b)

Set whether the Axes responds to navigation toolbar commands.

Parameters:

b (bool)

See also

matplotlib.axes.Axes.set_forward_navigation_events

set_navigate_mode(b)

Set the navigation toolbar button status.

Warning

This is not a user-API function.

set_path_effects(path_effects)

Set the path effects.

Parameters:

path_effects (list of .AbstractPathEffect)

set_picker(picker)

Define the picking behavior of the artist.

Parameters:

picker (None 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_position(pos, which='both')

Set the Axes position.

Axes have two position attributes. The ‘original’ position is the position allocated for the Axes. The ‘active’ position is the position the Axes is actually drawn at. These positions are usually the same unless a fixed aspect is set to the Axes. See .Axes.set_aspect for details.

Parameters:
  • pos ([left, bottom, width, height] or ~matplotlib.transforms.Bbox) – The new position of the Axes in .Figure coordinates.

  • which ({'both', 'active', 'original'}, default: 'both') – Determines which position variables to change.

See also

matplotlib.transforms.Bbox.from_bounds, matplotlib.transforms.Bbox.from_extents

set_prop_cycle(*args, **kwargs)

Set the property cycle of the Axes.

The property cycle controls the style properties such as color, marker and linestyle of future plot commands. The style properties of data already added to the Axes are not modified.

Call signatures:

set_prop_cycle(cycler)
set_prop_cycle(label=values, label2=values2, ...)
set_prop_cycle(label, values)

Form 1 sets given ~cycler.Cycler object.

Form 2 creates a ~cycler.Cycler which cycles over one or more properties simultaneously and set it as the property cycle of the Axes. If multiple properties are given, their value lists must have the same length. This is just a shortcut for explicitly creating a cycler and passing it to the function, i.e. it’s short for set_prop_cycle(cycler(label=values, label2=values2, ...)).

Form 3 creates a ~cycler.Cycler for a single property and set it as the property cycle of the Axes. This form exists for compatibility with the original cycler.cycler interface. Its use is discouraged in favor of the kwarg form, i.e. set_prop_cycle(label=values).

Parameters:
  • cycler (~cycler.Cycler or None) –

    Set the given Cycler. None resets to the cycle defined by the current style.

  • label (str) – The property key. Must be a valid .Artist property. For example, ‘color’ or ‘linestyle’. Aliases are allowed, such as ‘c’ for ‘color’ and ‘lw’ for ‘linewidth’.

  • values (iterable) – Finite-length iterable of the property values. These values are validated and will raise a ValueError if invalid.

See also

matplotlib.rcsetup.cycler

Convenience function for creating validated cyclers for properties.

cycler.cycler

The original function for creating unvalidated cyclers.

Examples

Setting the property cycle for a single property:

>>> ax.set_prop_cycle(color=['red', 'green', 'blue'])

Setting the property cycle for simultaneously cycling over multiple properties (e.g. red circle, green plus, blue cross):

>>> ax.set_prop_cycle(color=['red', 'green', 'blue'],
...                   marker=['o', '+', 'x'])
set_rasterization_zorder(z)

Set the zorder threshold for rasterization for vector graphics output.

All artists with a zorder below the given value will be rasterized if they support rasterization.

This setting is ignored for pixel-based output.

See also /gallery/misc/rasterization_demo.

Parameters:

z (float or None) – The zorder below which artists are rasterized. If None rasterization based on zorder is deactivated.

set_rasterized(rasterized)

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 /gallery/misc/rasterization_demo.

Parameters:

rasterized (bool)

set_sketch_params(scale=None, length=None, randomness=None)

Set the sketch parameters.

Parameters:
  • scale (float, 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.

  • length (float, optional) – The length of the wiggle along the line, in pixels (default 128.0)

  • randomness (float, 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)

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:

snap (bool 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_subplotspec(subplotspec)

Set the .SubplotSpec. associated with the subplot.

set_title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)[source]

Set a title for the Axes.

Set one of the three available Axes titles. The available titles are positioned above the Axes in the center, flush with the left edge, and flush with the right edge.

Parameters:
  • label (str) – Text to use for the title

  • fontdict (dict) –

    Discouraged

    The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking set_title(..., **fontdict).

    A dictionary controlling the appearance of the title text, the default fontdict is:

    {'fontsize': rcParams['axes.titlesize'],
     'fontweight': rcParams['axes.titleweight'],
     'color': rcParams['axes.titlecolor'],
     'verticalalignment': 'baseline',
     'horizontalalignment': loc}
    

  • loc ({'center', 'left', 'right'}, default: :rc:`axes.titlelocation`) – Which title to set.

  • y (float, default: :rc:`axes.titley`) – Vertical Axes location for the title (1.0 is the top). If None (the default) and :rc:`axes.titley` is also None, y is determined automatically to avoid decorators on the Axes.

  • pad (float, default: :rc:`axes.titlepad`) – The offset of the title from the top of the Axes, in points.

  • **kwargs (~matplotlib.text.Text properties) – Other keyword arguments are text properties, see .Text for a list of valid text properties.

Returns:

The matplotlib text instance representing the title

Return type:

.Text

set_transform(t)

Set the artist transform.

Parameters:

t (~matplotlib.transforms.Transform)

set_url(url)

Set the url for the artist.

Parameters:

url (str)

set_visible(b)

Set the artist’s visibility.

Parameters:

b (bool)

set_xbound(lower=None, upper=None)

Set the lower and upper numerical bounds of the x-axis.

This method will honor axis inversion regardless of parameter order. It will not change the autoscaling setting (.get_autoscalex_on()).

Parameters:
  • lower (float or None) –

    The lower and upper bounds. If None, the respective axis bound is not modified.

  • upper (float or None) –

    The lower and upper bounds. If None, the respective axis bound is not modified.

set_xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)

Set the label for the x-axis.

Parameters:
  • xlabel (str) – The label text.

  • labelpad (float, default: :rc:`axes.labelpad`) – Spacing in points from the Axes bounding box including ticks and tick labels. If None, the previous value is left as is.

  • loc ({'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`) – The label position. This is a high-level alternative for passing parameters x and horizontalalignment.

  • **kwargs (~matplotlib.text.Text properties) – .Text properties control the appearance of the label.

See also

text

Documents the properties supported by .Text.

set_xlim(left=None, right=None, *, emit=True, auto=False, xmin=None, xmax=None)

Set the x-axis view limits.

Parameters:
  • left (float, optional) –

    The left xlim in data coordinates. Passing None leaves the limit unchanged.

    The left and right xlims may also be passed as the tuple (left, right) as the first positional argument (or as the left keyword argument).

  • right (float, optional) – The right xlim in data coordinates. Passing None leaves the limit unchanged.

  • emit (bool, default: True) – Whether to notify observers of limit change.

  • auto (bool or None, default: False) – Whether to turn on autoscaling of the x-axis. True turns on, False turns off, None leaves unchanged.

  • xmin (float, optional) – They are equivalent to left and right respectively, and it is an error to pass both xmin and left or xmax and right.

  • xmax (float, optional) – They are equivalent to left and right respectively, and it is an error to pass both xmin and left or xmax and right.

Returns:

left, right – The new x-axis limits in data coordinates.

Return type:

(float, float)

Notes

The left value may be greater than the right value, in which case the x-axis values will decrease from left to right.

Examples

>>> set_xlim(left, right)
>>> set_xlim((left, right))
>>> left, right = set_xlim(left, right)

One limit may be left unchanged.

>>> set_xlim(right=right_lim)

Limits may be passed in reverse order to flip the direction of the x-axis. For example, suppose x represents the number of years before present. The x-axis limits might be set like the following so 5000 years ago is on the left of the plot and the present is on the right.

>>> set_xlim(5000, 0)
set_xmargin(m)

Set padding of X data limits prior to autoscaling.

m times the data interval will be added to each end of that interval before it is used in autoscaling. If m is negative, this will clip the data range instead of expanding it.

For example, if your data is in the range [0, 2], a margin of 0.1 will result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range of [0.2, 1.8].

Parameters:

m (float greater than -0.5)

set_xscale(value, **kwargs)

Set the xaxis’ scale.

Parameters:
  • value (str or .ScaleBase) – The axis scale type to apply. Valid string values are the names of scale classes (“linear”, “log”, “function”,…). These may be the names of any of the built-in scales or of any custom scales registered using matplotlib.scale.register_scale.

  • **kwargs – If value is a string, keywords are passed to the instantiation method of the respective class.

set_xticklabels(labels, *, minor=False, fontdict=None, **kwargs)

[Discouraged] Set the xaxis’ tick labels with list of string labels.

Discouraged

The use of this method is discouraged, because of the dependency on tick positions. In most cases, you’ll want to use Axes.set_[x/y/z]ticks(positions, labels) or Axes.set_xticks instead.

If you are using this method, you should always fix the tick positions before, e.g. by using .Axes.set_xticks or by explicitly setting a ~.ticker.FixedLocator. Otherwise, ticks are free to move and the labels may end up in unexpected positions.

Parameters:
  • labels (sequence of str or of `.Texts`) – Texts for labeling each tick location in the sequence set by .Axes.set_xticks; the number of labels must match the number of locations. The labels are used as is, via a .FixedFormatter (without further formatting).

  • minor (bool) – If True, set minor ticks instead of major ticks.

  • fontdict (dict, optional) –

    Discouraged

    The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking set_ticklabels(..., **fontdict).

    A dictionary controlling the appearance of the ticklabels. The default fontdict is:

    {'fontsize': rcParams['axes.titlesize'],
     'fontweight': rcParams['axes.titleweight'],
     'verticalalignment': 'baseline',
     'horizontalalignment': loc}
    

  • **kwargs

    Text properties.

    Warning

    This only sets the properties of the current ticks, which is only sufficient for static plots.

    Ticks are not guaranteed to be persistent. Various operations can create, delete and modify the Tick instances. There is an imminent risk that these settings can get lost if you work on the figure further (including also panning/zooming on a displayed figure).

    Use .set_tick_params instead if possible.

Returns:

For each tick, includes tick.label1 if it is visible, then tick.label2 if it is visible, in that order.

Return type:

list of .Texts

set_xticks(ticks, labels=None, *, minor=False, **kwargs)

Set the xaxis’ tick locations and optionally tick labels.

If necessary, the view limits of the Axis are expanded so that all given ticks are visible.

Parameters:
  • ticks (1D array-like) –

    Array of tick locations (either floats or in axis units). The axis .Locator is replaced by a ~.ticker.FixedLocator.

    Pass an empty list (set_xticks([])) to remove all ticks.

    Some tick formatters will not label arbitrary tick positions; e.g. log formatters only label decade ticks by default. In such a case you can set a formatter explicitly on the axis using .Axis.set_major_formatter or provide formatted labels yourself.

  • labels (list of str, optional) – Tick labels for each location in ticks; must have the same length as ticks. If set, the labels are used as is, via a .FixedFormatter. If not set, the labels are generated using the axis tick .Formatter.

  • minor (bool, default: False) – If False, set only the major ticks; if True, only the minor ticks.

  • **kwargs.Text properties for the labels. Using these is only allowed if you pass labels. In other cases, please use ~.Axes.tick_params.

Notes

The mandatory expansion of the view limits is an intentional design choice to prevent the surprise of a non-visible tick. If you need other limits, you should set the limits explicitly after setting the ticks.

set_ybound(lower=None, upper=None)

Set the lower and upper numerical bounds of the y-axis.

This method will honor axis inversion regardless of parameter order. It will not change the autoscaling setting (.get_autoscaley_on()).

Parameters:
  • lower (float or None) –

    The lower and upper bounds. If None, the respective axis bound

    is not modified.

  • upper (float or None) –

    The lower and upper bounds. If None, the respective axis bound

    is not modified.

set_ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)

Set the label for the y-axis.

Parameters:
  • ylabel (str) – The label text.

  • labelpad (float, default: :rc:`axes.labelpad`) – Spacing in points from the Axes bounding box including ticks and tick labels. If None, the previous value is left as is.

  • loc ({'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`) – The label position. This is a high-level alternative for passing parameters y and horizontalalignment.

  • **kwargs (~matplotlib.text.Text properties) – .Text properties control the appearance of the label.

See also

text

Documents the properties supported by .Text.

set_ylim(bottom=None, top=None, *, emit=True, auto=False, ymin=None, ymax=None)

Set the y-axis view limits.

Parameters:
  • bottom (float, optional) –

    The bottom ylim in data coordinates. Passing None leaves the limit unchanged.

    The bottom and top ylims may also be passed as the tuple (bottom, top) as the first positional argument (or as the bottom keyword argument).

  • top (float, optional) – The top ylim in data coordinates. Passing None leaves the limit unchanged.

  • emit (bool, default: True) – Whether to notify observers of limit change.

  • auto (bool or None, default: False) – Whether to turn on autoscaling of the y-axis. True turns on, False turns off, None leaves unchanged.

  • ymin (float, optional) – They are equivalent to bottom and top respectively, and it is an error to pass both ymin and bottom or ymax and top.

  • ymax (float, optional) – They are equivalent to bottom and top respectively, and it is an error to pass both ymin and bottom or ymax and top.

Returns:

bottom, top – The new y-axis limits in data coordinates.

Return type:

(float, float)

Notes

The bottom value may be greater than the top value, in which case the y-axis values will decrease from bottom to top.

Examples

>>> set_ylim(bottom, top)
>>> set_ylim((bottom, top))
>>> bottom, top = set_ylim(bottom, top)

One limit may be left unchanged.

>>> set_ylim(top=top_lim)

Limits may be passed in reverse order to flip the direction of the y-axis. For example, suppose y represents depth of the ocean in m. The y-axis limits might be set like the following so 5000 m depth is at the bottom of the plot and the surface, 0 m, is at the top.

>>> set_ylim(5000, 0)
set_ymargin(m)

Set padding of Y data limits prior to autoscaling.

m times the data interval will be added to each end of that interval before it is used in autoscaling. If m is negative, this will clip the data range instead of expanding it.

For example, if your data is in the range [0, 2], a margin of 0.1 will result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range of [0.2, 1.8].

Parameters:

m (float greater than -0.5)

set_yscale(value, **kwargs)

Set the yaxis’ scale.

Parameters:
  • value (str or .ScaleBase) – The axis scale type to apply. Valid string values are the names of scale classes (“linear”, “log”, “function”,…). These may be the names of any of the built-in scales or of any custom scales registered using matplotlib.scale.register_scale.

  • **kwargs – If value is a string, keywords are passed to the instantiation method of the respective class.

set_yticklabels(labels, *, minor=False, fontdict=None, **kwargs)

[Discouraged] Set the yaxis’ tick labels with list of string labels.

Discouraged

The use of this method is discouraged, because of the dependency on tick positions. In most cases, you’ll want to use Axes.set_[x/y/z]ticks(positions, labels) or Axes.set_yticks instead.

If you are using this method, you should always fix the tick positions before, e.g. by using .Axes.set_yticks or by explicitly setting a ~.ticker.FixedLocator. Otherwise, ticks are free to move and the labels may end up in unexpected positions.

Parameters:
  • labels (sequence of str or of `.Texts`) – Texts for labeling each tick location in the sequence set by .Axes.set_yticks; the number of labels must match the number of locations. The labels are used as is, via a .FixedFormatter (without further formatting).

  • minor (bool) – If True, set minor ticks instead of major ticks.

  • fontdict (dict, optional) –

    Discouraged

    The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking set_ticklabels(..., **fontdict).

    A dictionary controlling the appearance of the ticklabels. The default fontdict is:

    {'fontsize': rcParams['axes.titlesize'],
     'fontweight': rcParams['axes.titleweight'],
     'verticalalignment': 'baseline',
     'horizontalalignment': loc}
    

  • **kwargs

    Text properties.

    Warning

    This only sets the properties of the current ticks, which is only sufficient for static plots.

    Ticks are not guaranteed to be persistent. Various operations can create, delete and modify the Tick instances. There is an imminent risk that these settings can get lost if you work on the figure further (including also panning/zooming on a displayed figure).

    Use .set_tick_params instead if possible.

Returns:

For each tick, includes tick.label1 if it is visible, then tick.label2 if it is visible, in that order.

Return type:

list of .Texts

set_yticks(ticks, labels=None, *, minor=False, **kwargs)

Set the yaxis’ tick locations and optionally tick labels.

If necessary, the view limits of the Axis are expanded so that all given ticks are visible.

Parameters:
  • ticks (1D array-like) –

    Array of tick locations (either floats or in axis units). The axis .Locator is replaced by a ~.ticker.FixedLocator.

    Pass an empty list (set_yticks([])) to remove all ticks.

    Some tick formatters will not label arbitrary tick positions; e.g. log formatters only label decade ticks by default. In such a case you can set a formatter explicitly on the axis using .Axis.set_major_formatter or provide formatted labels yourself.

  • labels (list of str, optional) – Tick labels for each location in ticks; must have the same length as ticks. If set, the labels are used as is, via a .FixedFormatter. If not set, the labels are generated using the axis tick .Formatter.

  • minor (bool, default: False) – If False, set only the major ticks; if True, only the minor ticks.

  • **kwargs.Text properties for the labels. Using these is only allowed if you pass labels. In other cases, please use ~.Axes.tick_params.

Notes

The mandatory expansion of the view limits is an intentional design choice to prevent the surprise of a non-visible tick. If you need other limits, you should set the limits explicitly after setting the ticks.

set_zorder(level)

Set the zorder for the artist. Artists with lower zorder values are drawn first.

Parameters:

level (float)

sharex(other)

Share the x-axis with other.

This is equivalent to passing sharex=other when constructing the Axes, and cannot be used if the x-axis is already being shared with another Axes. Note that it is not possible to unshare axes.

sharey(other)

Share the y-axis with other.

This is equivalent to passing sharey=other when constructing the Axes, and cannot be used if the y-axis is already being shared with another Axes. Note that it is not possible to unshare axes.

specgram(x, *, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, data=None, **kwargs)[source]

Plot a spectrogram.

Compute and plot a spectrogram of data in x. Data are split into NFFT length segments and the spectrum of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap. The spectrogram is plotted as a colormap (using imshow).

Parameters:
  • x (1-D array or sequence) – Array or sequence containing the data.

  • Fs (float, default: 2) – The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit.

  • window (callable or ndarray, default: .window_hanning) – A function or a vector of length NFFT. To create window vectors see .window_hanning, .window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.

  • sides ({'default', 'onesided', 'twosided'}, optional) – Which sides of the spectrum to return. ‘default’ is one-sided for real data and two-sided for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.

  • pad_to (int, optional) – The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to ~numpy.fft.fft. The default is None, which sets pad_to equal to NFFT

  • NFFT (int, default: 256) – The number of data points used in each block for the FFT. A power 2 is most efficient. This should NOT be used to get zero padding, or the scaling of the result will be incorrect; use pad_to for this instead.

  • detrend ({'none', 'mean', 'linear'} or callable, default: 'none') – The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib it is a function. The mlab module defines .detrend_none, .detrend_mean, and .detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls .detrend_none. ‘mean’ calls .detrend_mean. ‘linear’ calls .detrend_linear.

  • scale_by_freq (bool, default: True) – Whether the resulting density values should be scaled by the scaling frequency, which gives density in units of 1/Hz. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.

  • mode ({'default', 'psd', 'magnitude', 'angle', 'phase'}) – What sort of spectrum to use. Default is ‘psd’, which takes the power spectral density. ‘magnitude’ returns the magnitude spectrum. ‘angle’ returns the phase spectrum without unwrapping. ‘phase’ returns the phase spectrum with unwrapping.

  • noverlap (int, default: 128) – The number of points of overlap between blocks.

  • scale ({'default', 'linear', 'dB'}) – The scaling of the values in the spec. ‘linear’ is no scaling. ‘dB’ returns the values in dB scale. When mode is ‘psd’, this is dB power (10 * log10). Otherwise, this is dB amplitude (20 * log10). ‘default’ is ‘dB’ if mode is ‘psd’ or ‘magnitude’ and ‘linear’ otherwise. This must be ‘linear’ if mode is ‘angle’ or ‘phase’.

  • Fc (int, default: 0) – The center frequency of x, which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.

  • cmap (.Colormap, default: :rc:`image.cmap`)

  • xextent (*None* or (xmin, xmax)) – The image extent along the x-axis. The default sets xmin to the left border of the first bin (spectrum column) and xmax to the right border of the last bin. Note that for noverlap>0 the width of the bins is smaller than those of the segments.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x

  • vmin (float, optional) – vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the data.

  • vmax (float, optional) – vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the data.

  • **kwargs – Additional keyword arguments are passed on to ~.axes.Axes.imshow which makes the specgram image. The origin keyword argument is not supported.

Returns:

  • spectrum (2D array) – Columns are the periodograms of successive segments.

  • freqs (1-D array) – The frequencies corresponding to the rows in spectrum.

  • t (1-D array) – The times corresponding to midpoints of segments (i.e., the columns in spectrum).

  • im (.AxesImage) – The image created by imshow containing the spectrogram.

See also

psd

Differs in the default overlap; in returning the mean of the segment periodograms; in not returning times; and in generating a line plot instead of colormap.

magnitude_spectrum

A single spectrum, similar to having a single segment when mode is ‘magnitude’. Plots a line instead of a colormap.

angle_spectrum

A single spectrum, similar to having a single segment when mode is ‘angle’. Plots a line instead of a colormap.

phase_spectrum

A single spectrum, similar to having a single segment when mode is ‘phase’. Plots a line instead of a colormap.

Notes

The parameters detrend and scale_by_freq do only apply when mode is set to ‘psd’.

spines: mspines.Spines

The .Spines container for the Axes’ spines, i.e. the lines denoting the data area boundaries.

spy(Z, *, precision=0, marker=None, markersize=None, aspect='equal', origin='upper', **kwargs)[source]

Plot the sparsity pattern of a 2D array.

This visualizes the non-zero values of the array.

Two plotting styles are available: image and marker. Both are available for full arrays, but only the marker style works for scipy.sparse.spmatrix instances.

Image style

If marker and markersize are None, ~.Axes.imshow is used. Any extra remaining keyword arguments are passed to this method.

Marker style

If Z is a scipy.sparse.spmatrix or marker or markersize are None, a .Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to ~.Axes.plot.

Parameters:
  • Z ((M, N) array-like) – The array to be plotted.

  • precision (float or 'present', default: 0) –

    If precision is 0, any non-zero value will be plotted. Otherwise, values of \(|Z| > precision\) will be plotted.

    For scipy.sparse.spmatrix instances, you can also pass ‘present’. In this case any value present in the array will be plotted, even if it is identically zero.

  • aspect ({'equal', 'auto', None} or float, default: 'equal') –

    The aspect ratio of the Axes. This parameter is particularly relevant for images since it determines whether data pixels are square.

    This parameter is a shortcut for explicitly calling .Axes.set_aspect. See there for further details.

    • ’equal’: Ensures an aspect ratio of 1. Pixels will be square.

    • ’auto’: The Axes is kept fixed and the aspect is adjusted so that the data fit in the Axes. In general, this will result in non-square pixels.

    • None: Use :rc:`image.aspect`.

  • origin ({'upper', 'lower'}, default: :rc:`image.origin`) – Place the [0, 0] index of the array in the upper left or lower left corner of the Axes. The convention ‘upper’ is typically used for matrices and images.

  • **kwargs

    The supported additional parameters depend on the plotting style.

    For the image style, you can pass the following additional parameters of ~.Axes.imshow:

    • cmap

    • alpha

    • url

    • any .Artist properties (passed on to the .AxesImage)

    For the marker style, you can pass any .Line2D property except for linestyle:

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

Returns:

The return type depends on the plotting style (see above).

Return type:

~matplotlib.image.AxesImage or .Line2D

stackplot(x, *args, labels=(), colors=None, hatch=None, baseline='zero', data=None, **kwargs)

Draw a stacked area plot or a streamgraph.

Parameters:
  • x ((N,) array-like)

  • y ((M, N) array-like) –

    The data can be either stacked or unstacked. Each of the following calls is legal:

    stackplot(x, y)  # where y has shape (M, N) e.g. y = [y1, y2, y3, y4]
    stackplot(x, y1, y2, y3, y4)  # where y1, y2, y3, y4 have length N
    

  • baseline ({'zero', 'sym', 'wiggle', 'weighted_wiggle'}) –

    Method used to calculate the baseline:

    • 'zero': Constant zero baseline, i.e. a simple stacked plot.

    • 'sym': Symmetric around zero and is sometimes called ‘ThemeRiver’.

    • 'wiggle': Minimizes the sum of the squared slopes.

    • 'weighted_wiggle': Does the same but weights to account for size of each layer. It is also called ‘Streamgraph’-layout. More details can be found at http://leebyron.com/streamgraph/.

  • labels (list of str, optional) – A sequence of labels to assign to each data series. If unspecified, then no labels will be applied to artists.

  • colors (list of :mpltype:`color`, optional) –

    A sequence of colors to be cycled through and used to color the stacked areas. The sequence need not be exactly the same length as the number of provided y, in which case the colors will repeat from the beginning.

    If not specified, the colors from the Axes property cycle will be used.

  • hatch (list of str, default: None) –

    A sequence of hatching styles. See /gallery/shapes_and_collections/hatch_style_reference. The sequence will be cycled through for filling the stacked areas from bottom to top. It need not be exactly the same length as the number of provided y, in which case the styles will repeat from the beginning.

    Added in version 3.9: Support for list input

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs – All other keyword arguments are passed to .Axes.fill_between.

Returns:

A list of .PolyCollection instances, one for each element in the stacked area plot.

Return type:

list of .PolyCollection

stairs(values, edges=None, *, orientation='vertical', baseline=0, fill=False, data=None, **kwargs)[source]

Draw a stepwise constant function as a line or a filled plot.

edges define the x-axis positions of the steps. values the function values between these steps. Depending on fill, the function is drawn either as a continuous line with vertical segments at the edges, or as a filled area.

Parameters:
  • values (array-like) – The step heights.

  • edges (array-like) – The step positions, with len(edges) == len(vals) + 1, between which the curve takes on vals values.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') – The direction of the steps. Vertical means that values are along the y-axis, and edges are along the x-axis.

  • baseline (float, array-like or None, default: 0) –

    The bottom value of the bounding edges or when fill=True, position of lower edge. If fill is True or an array is passed to baseline, a closed path is drawn.

    If None, then drawn as an unclosed Path.

  • fill (bool, default: False) –

    Whether the area under the step curve should be filled.

    Passing both fill=True` and ``baseline=None will likely result in undesired filling: the first and last points will be connected with a straight line and the fill will be between this line and the stairs.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

  • **kwargs~matplotlib.patches.StepPatch properties

Returns:

StepPatch

Return type:

~matplotlib.patches.StepPatch

property stale

Whether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.

start_pan(x, y, button)

Called when a pan operation has started.

Parameters:
  • x (float) – The mouse coordinates in display coords.

  • y (float) – The mouse coordinates in display coords.

  • button (.MouseButton) – The pressed mouse button.

Notes

This is intended to be overridden by new projection types.

stem(*args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, orientation='vertical', data=None)[source]

Create a stem plot.

A stem plot draws lines perpendicular to a baseline at each location locs from the baseline to heads, and places a marker there. For vertical stem plots (the default), the locs are x positions, and the heads are y values. For horizontal stem plots, the locs are y positions, and the heads are x values.

Call signature:

stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None)

The locs-positions are optional. linefmt may be provided as positional, but all other formats must be provided as keyword arguments.

Parameters:
  • locs (array-like, default: (0, 1, ..., len(heads) - 1)) – For vertical stem plots, the x-positions of the stems. For horizontal stem plots, the y-positions of the stems.

  • heads (array-like) – For vertical stem plots, the y-values of the stem heads. For horizontal stem plots, the x-values of the stem heads.

  • linefmt (str, optional) –

    A string defining the color and/or linestyle of the vertical lines:

    Character

    Line Style

    '-'

    solid line

    '--'

    dashed line

    '-.'

    dash-dot line

    ':'

    dotted line

    Default: ‘C0-’, i.e. solid line with the first color of the color cycle.

    Note: Markers specified through this parameter (e.g. ‘x’) will be silently ignored. Instead, markers should be specified using markerfmt.

  • markerfmt (str, optional) – A string defining the color and/or shape of the markers at the stem heads. If the marker is not given, use the marker ‘o’, i.e. filled circles. If the color is not given, use the color from linefmt.

  • basefmt (str, default: 'C3-' ('C2-' in classic mode)) – A format string defining the properties of the baseline.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') – The orientation of the stems.

  • bottom (float, default: 0) – The y/x-position of the baseline (depending on orientation).

  • label (str, optional) – The label to use for the stems in legends.

  • data (indexable object, optional) – If given, all parameters also accept a string s, which is interpreted as data[s] if s is a key in data.

Returns:

The container may be treated like a tuple (markerline, stemlines, baseline)

Return type:

.StemContainer

Notes

See also

The MATLAB function stem which inspired this method.

step(x, y, *args, where='pre', data=None, **kwargs)[source]

Make a step plot.

Call signatures:

step(x, y, [fmt], *, data=None, where='pre', **kwargs)
step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)

This is just a thin wrapper around .plot which changes some formatting options. Most of the concepts and parameters of plot can be used here as well.

Note

This method uses a standard plot with a step drawstyle: The x values are the reference positions and steps extend left/right/both directions depending on where.

For the common case where you know the values and edges of the steps, use ~.Axes.stairs instead.

Parameters:
  • x (array-like) – 1D sequence of x positions. It is assumed, but not checked, that it is uniformly increasing.

  • y (array-like) – 1D sequence of y levels.

  • fmt (str, optional) –

    A format string, e.g. ‘g’ for a green line. See .plot for a more detailed description.

    Note: While full format strings are accepted, it is recommended to only specify the color. Line styles are currently ignored (use the keyword argument linestyle instead). Markers are accepted and plotted on the given positions, however, this is a rarely needed feature for step plots.

  • where ({'pre', 'post', 'mid'}, default: 'pre') –

    Define where the steps should be placed:

    • ’pre’: The y value is continued constantly to the left from every x position, i.e. the interval (x[i-1], x[i]] has the value y[i].

    • ’post’: The y value is continued constantly to the right from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i].

    • ’mid’: Steps occur half-way between the x positions.

  • data (indexable object, optional) – An object with labelled data. If given, provide the label names to plot in x and y.

  • **kwargs – Additional parameters are the same as those for .plot.

Returns:

Objects representing the plotted data.

Return type:

list of .Line2D

property sticky_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)
streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction='both', broken_streamlines=True, *, data=None)

Draw streamlines of a vector flow.

Parameters:
  • x (1D/2D arrays) – Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of x must be equal and all columns of y must be equal; i.e., they must be as if generated by np.meshgrid(x_1d, y_1d).

  • y (1D/2D arrays) – Evenly spaced strictly increasing arrays to make a grid. If 2D, all rows of x must be equal and all columns of y must be equal; i.e., they must be as if generated by np.meshgrid(x_1d, y_1d).

  • u (2D arrays) – x and y-velocities. The number of rows and columns must match the length of y and x, respectively.

  • v (2D arrays) – x and y-velocities. The number of rows and columns must match the length of y and x, respectively.

  • density (float or (float, float)) – Controls the closeness of streamlines. When density = 1, the domain is divided into a 30x30 grid. density linearly scales this grid. Each cell in the grid can have, at most, one traversing streamline. For different densities in each direction, use a tuple (density_x, density_y).

  • linewidth (float or 2D array) – The width of the streamlines. With a 2D array the line width can be varied across the grid. The array must have the same shape as u and v.

  • color (:mpltype:`color` or 2D array) – The streamline color. If given an array, its values are converted to colors using cmap and norm. The array must have the same shape as u and v.

  • cmap – Data normalization and colormapping parameters for color; only used if color is an array of floats. See ~.Axes.imshow for a detailed description.

  • norm – Data normalization and colormapping parameters for color; only used if color is an array of floats. See ~.Axes.imshow for a detailed description.

  • arrowsize (float) – Scaling factor for the arrow size.

  • arrowstyle (str) – Arrow style specification. See ~matplotlib.patches.FancyArrowPatch.

  • minlength (float) – Minimum length of streamline in axes coordinates.

  • start_points ((N, 2) array) – Coordinates of starting points for the streamlines in data coordinates (the same coordinates as the x and y arrays).

  • zorder (float) – The zorder of the streamlines and arrows. Artists with lower zorder values are drawn first.

  • maxlength (float) – Maximum length of streamline in axes coordinates.

  • integration_direction ({'forward', 'backward', 'both'}, default: 'both') – Integrate the streamline in forward, backward or both directions.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y, u, v, start_points

  • broken_streamlines (boolean, default: True) – If False, forces streamlines to continue until they leave the plot domain. If True, they may be terminated if they come too close to another streamline.

Returns:

Container object with attributes

  • lines: .LineCollection of streamlines

  • arrows: .PatchCollection containing .FancyArrowPatch objects representing the arrows half-way along streamlines.

This container will probably change in the future to allow changes to the colormap, alpha, etc. for both lines and arrows, but these changes should be backward compatible.

Return type:

StreamplotSet

table(cellText=None, cellColours=None, cellLoc='right', colWidths=None, rowLabels=None, rowColours=None, rowLoc='left', colLabels=None, colColours=None, colLoc='center', loc='bottom', bbox=None, edges='closed', **kwargs)

Add a table to an ~.axes.Axes.

At least one of cellText or cellColours must be specified. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values per row. Each row must have the same number of elements.

The table can optionally have row and column headers, which are configured using rowLabels, rowColours, rowLoc and colLabels, colColours, colLoc respectively.

For finer grained control over tables, use the .Table class and add it to the Axes with .Axes.add_table.

Parameters:
  • cellText (2D list of str or pandas.DataFrame, optional) –

    The texts to place into the table cells.

    Note: Line breaks in the strings are currently not accounted for and will result in the text exceeding the cell boundaries.

  • cellColours (2D list of :mpltype:`color`, optional) – The background colors of the cells.

  • cellLoc ({'right', 'center', 'left'}) – The alignment of the text within the cells.

  • colWidths (list of float, optional) – The column widths in units of the axes. If not given, all columns will have a width of 1 / ncols.

  • rowLabels (list of str, optional) – The text of the row header cells.

  • rowColours (list of :mpltype:`color`, optional) – The colors of the row header cells.

  • rowLoc ({'left', 'center', 'right'}) – The text alignment of the row header cells.

  • colLabels (list of str, optional) – The text of the column header cells.

  • colColours (list of :mpltype:`color`, optional) – The colors of the column header cells.

  • colLoc ({'center', 'left', 'right'}) – The text alignment of the column header cells.

  • loc (str, default: 'bottom') – The position of the cell with respect to ax. This must be one of the ~.Table.codes.

  • bbox (.Bbox or [xmin, ymin, width, height], optional) – A bounding box to draw the table into. If this is not None, this overrides loc.

  • edges ({'closed', 'open', 'horizontal', 'vertical'} or substring of 'BRTL') – The cell edges to be drawn with a line. See also ~.Cell.visible_edges.

  • **kwargs.Table properties.

  • Properties – agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fontsize: float gid: str in_layout: bool label: object mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float

Returns:

The created table.

Return type:

~matplotlib.table.Table

property tables
text(x, y, s, fontdict=None, **kwargs)[source]

Add text to the Axes.

Add the text s to the Axes at location x, y in data coordinates, with a default horizontalalignment on the left and verticalalignment at the baseline. See /gallery/text_labels_and_annotations/text_alignment.

Parameters:
  • x (float) – The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • y (float) – The position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.

  • s (str) – The text.

  • fontdict (dict, default: None) –

    Discouraged

    The use of fontdict is discouraged. Parameters should be passed as individual keyword arguments or using dictionary-unpacking text(..., **fontdict).

    A dictionary to override the default text properties. If fontdict is None, the defaults are determined by .rcParams.

  • **kwargs (~matplotlib.text.Text properties.) –

    Other miscellaneous text parameters.

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased: bool backgroundcolor: :mpltype:`color` bbox: dict with properties for .patches.FancyBboxPatch clip_box: unknown clip_on: unknown clip_path: unknown color or c: :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fontfamily or family or fontname: {FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’} fontproperties or font or font_properties: .font_manager.FontProperties or str or pathlib.Path fontsize or size: float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’} fontstretch or stretch: {a numeric value in range 0-1000, ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’} fontstyle or style: {‘normal’, ‘italic’, ‘oblique’} fontvariant or variant: {‘normal’, ‘small-caps’} fontweight or weight: {a numeric value in range 0-1000, ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’} gid: str horizontalalignment or ha: {‘left’, ‘center’, ‘right’} in_layout: bool label: object linespacing: float (multiple of font size) math_fontfamily: str mouseover: bool multialignment or ma: {‘left’, ‘right’, ‘center’} parse_math: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: (float, float) rasterized: bool rotation: float or {‘vertical’, ‘horizontal’} rotation_mode: {None, ‘default’, ‘anchor’} sketch_params: (scale: float, length: float, randomness: float) snap: bool or None text: object transform: ~matplotlib.transforms.Transform transform_rotates_text: bool url: str usetex: bool, default: :rc:`text.usetex` verticalalignment or va: {‘baseline’, ‘bottom’, ‘center’, ‘center_baseline’, ‘top’} visible: bool wrap: bool x: float y: float zorder: float

Returns:

The created .Text instance.

Return type:

.Text

Examples

Individual keyword arguments can be used to override any given parameter:

>>> text(x, y, s, fontsize=12)

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords ((0, 0) is lower-left and (1, 1) is upper-right). The example below places text in the center of the Axes:

>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
...      verticalalignment='center', transform=ax.transAxes)

You can put a rectangular box around the text instance (e.g., to set a background color) by using the keyword bbox. bbox is a dictionary of ~matplotlib.patches.Rectangle properties. For example:

>>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
property texts
tick_params(axis='both', **kwargs)

Change the appearance of ticks, tick labels, and gridlines.

Tick properties that are not explicitly set using the keyword arguments remain unchanged unless reset is True. For the current style settings, see .Axis.get_tick_params.

Parameters:
  • axis ({'x', 'y', 'both'}, default: 'both') – The axis to which the parameters are applied.

  • which ({'major', 'minor', 'both'}, default: 'major') – The group of ticks to which the parameters are applied.

  • reset (bool, default: False) – Whether to reset the ticks to defaults before updating them.

  • direction ({'in', 'out', 'inout'}) – Puts ticks inside the Axes, outside the Axes, or both.

  • length (float) – Tick length in points.

  • width (float) – Tick width in points.

  • color (:mpltype:`color`) – Tick color.

  • pad (float) – Distance in points between tick and label.

  • labelsize (float or str) – Tick label font size in points or as a string (e.g., ‘large’).

  • labelcolor (:mpltype:`color`) – Tick label color.

  • labelfontfamily (str) – Tick label font.

  • colors (:mpltype:`color`) – Tick color and label color.

  • zorder (float) – Tick and label zorder.

  • bottom (bool) – Whether to draw the respective ticks.

  • top (bool) – Whether to draw the respective ticks.

  • left (bool) – Whether to draw the respective ticks.

  • right (bool) – Whether to draw the respective ticks.

  • labelbottom (bool) – Whether to draw the respective tick labels.

  • labeltop (bool) – Whether to draw the respective tick labels.

  • labelleft (bool) – Whether to draw the respective tick labels.

  • labelright (bool) – Whether to draw the respective tick labels.

  • labelrotation (float) – Tick label rotation

  • grid_color (:mpltype:`color`) – Gridline color.

  • grid_alpha (float) – Transparency of gridlines: 0 (transparent) to 1 (opaque).

  • grid_linewidth (float) – Width of gridlines in points.

  • grid_linestyle (str) – Any valid .Line2D line style spec.

Examples

ax.tick_params(direction='out', length=6, width=2, colors='r',
               grid_color='r', grid_alpha=0.5)

This will make all major ticks be red, pointing out of the box, and with dimensions 6 points by 2 points. Tick labels will also be red. Gridlines will be red and translucent.

ticklabel_format(*, axis='both', style=None, scilimits=None, useOffset=None, useLocale=None, useMathText=None)

Configure the .ScalarFormatter used by default for linear Axes.

If a parameter is not set, the corresponding property of the formatter is left unchanged.

Parameters:
  • axis ({'x', 'y', 'both'}, default: 'both') – The axis to configure. Only major ticks are affected.

  • style ({'sci', 'scientific', 'plain'}) – Whether to use scientific notation. The formatter default is to use scientific notation. ‘sci’ is equivalent to ‘scientific’.

  • scilimits (pair of ints (m, n)) – Scientific notation is used only for numbers outside the range 10m to 10n (and only if the formatter is configured to use scientific notation at all). Use (0, 0) to include all numbers. Use (m, m) where m != 0 to fix the order of magnitude to 10m. The formatter default is :rc:`axes.formatter.limits`.

  • useOffset (bool or float) – If True, the offset is calculated as needed. If False, no offset is used. If a numeric value, it sets the offset. The formatter default is :rc:`axes.formatter.useoffset`.

  • useLocale (bool) – Whether to format the number using the current locale or using the C (English) locale. This affects e.g. the decimal separator. The formatter default is :rc:`axes.formatter.use_locale`.

  • useMathText (bool) – Render the offset and scientific notation in mathtext. The formatter default is :rc:`axes.formatter.use_mathtext`.

Raises:

AttributeError – If the current formatter is not a .ScalarFormatter.

tricontour(*args, **kwargs)

Draw contour lines on an unstructured triangular grid.

Call signatures:

tricontour(triangulation, z, [levels], ...)
tricontour(x, y, z, [levels], *, [triangles=triangles], [mask=mask], ...)

The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. See .Triangulation for an explanation of these parameters. If neither of triangulation or triangles are given, the triangulation is calculated on the fly.

It is possible to pass triangles positionally, i.e. tricontour(x, y, triangles, z, ...). However, this is discouraged. For more clarity, pass triangles via keyword argument.

Parameters:
  • triangulation (.Triangulation, optional) – An already created triangular grid.

  • x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • z (array-like) –

    The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.

    Note

    All values in z must be finite. Hence, nan and inf values must either be removed or ~.Triangulation.set_mask be used.

  • levels (int or array-like, optional) –

    Determines the number and positions of the contour lines / regions.

    If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between between minimum and maximum numeric values of Z.

    If array-like, draw contour lines at the specified levels. The values must be in increasing order.

  • colors (:mpltype:`color` or list of :mpltype:`color`, optional) –

    The colors of the levels, i.e., the contour lines.

    The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it is repeated.

    As a shortcut, single color strings may be used in place of one-element lists, i.e. 'red' instead of ['red'] to color all levels with the same color. This shortcut does only work for color strings, not for other ways of specifying colors.

    By default (value None), the colormap specified by cmap will be used.

  • alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if colors is set.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if colors is set.

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • origin ({*None*, 'upper', 'lower', 'image'}, default: None) –

    Determines the orientation and exact position of z by specifying the position of z[0, 0]. This is only relevant, if X, Y are not given.

    • None: z[0, 0] is at X=0, Y=0 in the lower left corner.

    • ’lower’: z[0, 0] is at X=0.5, Y=0.5 in the lower left corner.

    • ’upper’: z[0, 0] is at X=N+0.5, Y=0.5 in the upper left corner.

    • ’image’: Use the value from :rc:`image.origin`.

  • extent ((x0, x1, y0, y1), optional) –

    If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of z[0, 0], and (x1, y1) is the position of z[-1, -1].

    This argument is ignored if X and Y are specified in the call to contour.

  • locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.

  • extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –

    Determines the tricontour-coloring of values that are outside the levels range.

    If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.

    Values below min(levels) and above max(levels) are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.

    Note

    An existing .TriContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call to .ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .TriContourSet because it internally calls .ContourSet.changed().

  • xunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • yunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from :rc:`lines.antialiased`.

  • linewidths (float or array-like, default: :rc:`contour.linewidth`) –

    The line width of the contour lines.

    If a number, all levels will be plotted with this linewidth.

    If a sequence, the levels in ascending order will be plotted with the linewidths in the order specified.

    If None, this falls back to :rc:`lines.linewidth`.

  • linestyles ({*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional) –

    If linestyles is None, the default is ‘solid’ unless the lines are monochrome. In that case, negative contours will take their linestyle from :rc:`contour.negative_linestyle` setting.

    linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary.

Return type:

~matplotlib.tri.TriContourSet

tricontourf(*args, **kwargs)

Draw contour regions on an unstructured triangular grid.

Call signatures:

tricontourf(triangulation, z, [levels], ...)
tricontourf(x, y, z, [levels], *, [triangles=triangles], [mask=mask], ...)

The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. See .Triangulation for an explanation of these parameters. If neither of triangulation or triangles are given, the triangulation is calculated on the fly.

It is possible to pass triangles positionally, i.e. tricontourf(x, y, triangles, z, ...). However, this is discouraged. For more clarity, pass triangles via keyword argument.

Parameters:
  • triangulation (.Triangulation, optional) – An already created triangular grid.

  • x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • z (array-like) –

    The height values over which the contour is drawn. Color-mapping is controlled by cmap, norm, vmin, and vmax.

    Note

    All values in z must be finite. Hence, nan and inf values must either be removed or ~.Triangulation.set_mask be used.

  • levels (int or array-like, optional) –

    Determines the number and positions of the contour lines / regions.

    If an int n, use ~matplotlib.ticker.MaxNLocator, which tries to automatically choose no more than n+1 “nice” contour levels between between minimum and maximum numeric values of Z.

    If array-like, draw contour lines at the specified levels. The values must be in increasing order.

  • colors (:mpltype:`color` or list of :mpltype:`color`, optional) –

    The colors of the levels, i.e., the contour regions.

    The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it is repeated.

    As a shortcut, single color strings may be used in place of one-element lists, i.e. 'red' instead of ['red'] to color all levels with the same color. This shortcut does only work for color strings, not for other ways of specifying colors.

    By default (value None), the colormap specified by cmap will be used.

  • alpha (float, default: 1) – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if colors is set.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if colors is set.

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    If vmin or vmax are not given, the default color scaling is based on levels.

    This parameter is ignored if colors is set.

  • origin ({*None*, 'upper', 'lower', 'image'}, default: None) –

    Determines the orientation and exact position of z by specifying the position of z[0, 0]. This is only relevant, if X, Y are not given.

    • None: z[0, 0] is at X=0, Y=0 in the lower left corner.

    • ’lower’: z[0, 0] is at X=0.5, Y=0.5 in the lower left corner.

    • ’upper’: z[0, 0] is at X=N+0.5, Y=0.5 in the upper left corner.

    • ’image’: Use the value from :rc:`image.origin`.

  • extent ((x0, x1, y0, y1), optional) –

    If origin is not None, then extent is interpreted as in .imshow: it gives the outer pixel boundaries. In this case, the position of z[0, 0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of z[0, 0], and (x1, y1) is the position of z[-1, -1].

    This argument is ignored if X and Y are specified in the call to contour.

  • locator (ticker.Locator subclass, optional) – The locator is used to determine the contour levels if they are not given explicitly via levels. Defaults to ~.ticker.MaxNLocator.

  • extend ({'neither', 'both', 'min', 'max'}, default: 'neither') –

    Determines the tricontourf-coloring of values that are outside the levels range.

    If ‘neither’, values outside the levels range are not colored. If ‘min’, ‘max’ or ‘both’, color the values below, above or below and above the levels range.

    Values below min(levels) and above max(levels) are mapped to the under/over values of the .Colormap. Note that most colormaps do not have dedicated colors for these by default, so that the over and under values are the edge values of the colormap. You may want to set these values explicitly using .Colormap.set_under and .Colormap.set_over.

    Note

    An existing .TriContourSet does not get notified if properties of its colormap are changed. Therefore, an explicit call to .ContourSet.changed() is needed after modifying the colormap. The explicit call can be left out, if a colorbar is assigned to the .TriContourSet because it internally calls .ContourSet.changed().

  • xunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • yunits (registered units, optional) – Override axis units by specifying an instance of a matplotlib.units.ConversionInterface.

  • antialiased (bool, optional) – Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from :rc:`lines.antialiased`.

  • hatches (list[str], optional) – A list of crosshatch patterns to use on the filled areas. If None, no hatching will be added to the contour.

Return type:

~matplotlib.tri.TriContourSet

Notes

.tricontourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is:

z1 < Z <= z2

except for the lowest interval, which is closed on both sides (i.e. it includes the lowest value).

tripcolor(*args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', facecolors=None, **kwargs)

Create a pseudocolor plot of an unstructured triangular grid.

Call signatures:

tripcolor(triangulation, c, *, ...)
tripcolor(x, y, c, *, [triangles=triangles], [mask=mask], ...)

The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. See .Triangulation for an explanation of these parameters.

It is possible to pass the triangles positionally, i.e. tripcolor(x, y, triangles, c, ...). However, this is discouraged. For more clarity, pass triangles via keyword argument.

If neither of triangulation or triangles are given, the triangulation is calculated on the fly. In this case, it does not make sense to provide colors at the triangle faces via c or facecolors because there are multiple possible triangulations for a group of points and you don’t know which triangles will be constructed.

Parameters:
  • triangulation (.Triangulation) – An already created triangular grid.

  • x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • c (array-like) – The color values, either for the points or for the triangles. Which one is automatically inferred from the length of c, i.e. does it match the number of points or the number of triangles. If there are the same number of points and triangles in the triangulation it is assumed that color values are defined at points; to force the use of color values at triangles use the keyword argument facecolors=c instead of just c. This parameter is position-only.

  • facecolors (array-like, optional) – Can be used alternatively to c to specify colors at the triangle faces. This parameter takes precedence over c.

  • shading ({'flat', 'gouraud'}, default: 'flat') – If ‘flat’ and the color values c are defined at points, the color values used for each triangle are from the mean c of the triangle’s three points. If shading is ‘gouraud’ then color values must be defined at points.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) – The Colormap instance or registered colormap name used to map scalar data to colors.

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

  • vmin (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • vmax (float, optional) – When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) – The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

  • **kwargs (~matplotlib.collections.Collection properties) – Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: array-like or float or None animated: bool antialiased 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: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None cmap: .Colormap or str or None color: :mpltype:`color` or list of RGBA tuples edgecolor or ec or edgecolors: :mpltype:`color` or list of :mpltype:`color` or ‘face’ facecolor or facecolors or fc: :mpltype:`color` or list of :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown 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 mouseover: bool norm: .Normalize or str or None offset_transform or transOffset: .Transform offsets: (N, 2) or (2,) array-like path_effects: list of .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: ~matplotlib.transforms.Transform url: str urls: list of str or None visible: bool zorder: float

Returns:

The result depends on shading: For shading='flat' the result is a .PolyCollection, for shading='gouraud' the result is a .TriMesh.

Return type:

~matplotlib.collections.PolyCollection or ~matplotlib.collections.TriMesh

triplot(*args, **kwargs)

Draw an unstructured triangular grid as lines and/or markers.

Call signatures:

triplot(triangulation, ...)
triplot(x, y, [triangles], *, [mask=mask], ...)

The triangular grid can be specified either by passing a .Triangulation object as the first parameter, or by passing the points x, y and optionally the triangles and a mask. If neither of triangulation or triangles are given, the triangulation is calculated on the fly.

Parameters:
  • triangulation (.Triangulation) – An already created triangular grid.

  • x – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • y – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • triangles – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • mask – Parameters defining the triangular grid. See .Triangulation. This is mutually exclusive with specifying triangulation.

  • other_parameters – All other args and kwargs are forwarded to ~.Axes.plot.

Returns:

  • lines (~matplotlib.lines.Line2D) – The drawn triangles edges.

  • markers (~matplotlib.lines.Line2D) – The drawn marker nodes.

twinx()

Create a twin Axes sharing the xaxis.

Create a new Axes with an invisible x-axis and an independent y-axis positioned opposite to the original one (i.e. at right). The x-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both y-axes align, see ~matplotlib.ticker.LinearLocator.

Returns:

The newly created Axes instance

Return type:

Axes

Notes

For those who are ‘picking’ artists while using twinx, pick events are only called for the artists in the top-most Axes.

twiny()

Create a twin Axes sharing the yaxis.

Create a new Axes with an invisible y-axis and an independent x-axis positioned opposite to the original one (i.e. at top). The y-axis autoscale setting will be inherited from the original Axes. To ensure that the tick marks of both x-axes align, see ~matplotlib.ticker.LinearLocator.

Returns:

The newly created Axes instance

Return type:

Axes

Notes

For those who are ‘picking’ artists while using twiny, pick events are only called for the artists in the top-most Axes.

update(props)

Update this artist’s properties from the dict props.

Parameters:

props (dict)

update_datalim(xys, updatex=True, updatey=True)

Extend the ~.Axes.dataLim Bbox to include the given points.

If no data is set currently, the Bbox will ignore its limits and set the bound to be the bounds of the xydata (xys). Otherwise, it will compute the bounds of the union of its current data and the data in xys.

Parameters:
  • xys (2D array-like) – The points to include in the data limits Bbox. This can be either a list of (x, y) tuples or a (N, 2) array.

  • updatex (bool, default: True) – Whether to update the x/y limits.

  • updatey (bool, default: True) – Whether to update the x/y limits.

update_from(other)

Copy properties from other to self.

property use_sticky_edges

When autoscaling, whether to obey all .Artist.sticky_edges.

Default is True.

Setting this to False ensures that the specified margins will be applied, even if the plot includes an image, for example, which would otherwise force a view limit to coincide with its data limit.

The changing this property does not change the plot until autoscale or autoscale_view is called.

property viewLim

The view limits as .Bbox in data coordinates.

violin(vpstats, positions=None, *, vert=None, orientation='vertical', widths=0.5, showmeans=False, showextrema=True, showmedians=False, side='both')[source]

Draw a violin plot from pre-computed statistics.

Draw a violin plot for each column of vpstats. Each filled area extends to represent the entire data range, with optional lines at the mean, the median, the minimum, the maximum, and the quantiles values.

Parameters:
  • vpstats (list of dicts) –

    A list of dictionaries containing stats for each violin plot. Required keys are:

    • coords: A list of scalars containing the coordinates that the violin’s kernel density estimate were evaluated at.

    • vals: A list of scalars containing the values of the kernel density estimate at each of the coordinates given in coords.

    • mean: The mean value for this violin’s dataset.

    • median: The median value for this violin’s dataset.

    • min: The minimum value for this violin’s dataset.

    • max: The maximum value for this violin’s dataset.

    Optional keys are:

    • quantiles: A list of scalars containing the quantile values for this violin’s dataset.

  • positions (array-like, default: [1, 2, ..., n]) – The positions of the violins; i.e. coordinates on the x-axis for vertical violins (or y-axis for horizontal violins).

  • vert (bool, optional) –

    Deprecated since version 3.10: Use orientation instead.

    If this is given during the deprecation period, it overrides the orientation parameter.

    If True, plots the violins vertically. If False, plots the violins horizontally.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') –

    If ‘horizontal’, plots the violins horizontally. Otherwise, plots the violins vertically.

    Added in version 3.10.

  • widths (float or array-like, default: 0.5) – The maximum width of each violin in units of the positions axis. The default is 0.5, which is half available space when using default positions.

  • showmeans (bool, default: False) – Whether to show the mean with a line.

  • showextrema (bool, default: True) – Whether to show extrema with a line.

  • showmedians (bool, default: False) – Whether to show the median with a line.

  • side ({'both', 'low', 'high'}, default: 'both') – ‘both’ plots standard violins. ‘low’/’high’ only plots the side below/above the positions value.

Returns:

A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys:

  • bodies: A list of the ~.collections.PolyCollection instances containing the filled area of each violin.

  • cmeans: A ~.collections.LineCollection instance that marks the mean values of each of the violin’s distribution.

  • cmins: A ~.collections.LineCollection instance that marks the bottom of each violin’s distribution.

  • cmaxes: A ~.collections.LineCollection instance that marks the top of each violin’s distribution.

  • cbars: A ~.collections.LineCollection instance that marks the centers of each violin’s distribution.

  • cmedians: A ~.collections.LineCollection instance that marks the median values of each of the violin’s distribution.

  • cquantiles: A ~.collections.LineCollection instance created to identify the quantiles values of each of the violin’s distribution.

Return type:

dict

See also

violinplot

Draw a violin plot from data instead of pre-computed statistics.

violinplot(dataset, positions=None, *, vert=None, orientation='vertical', widths=0.5, showmeans=False, showextrema=True, showmedians=False, quantiles=None, points=100, bw_method=None, side='both', data=None)[source]

Make a violin plot.

Make a violin plot for each column of dataset or each vector in sequence dataset. Each filled area extends to represent the entire data range, with optional lines at the mean, the median, the minimum, the maximum, and user-specified quantiles.

Parameters:
  • dataset (Array or a sequence of vectors.) – The input data.

  • positions (array-like, default: [1, 2, ..., n]) – The positions of the violins; i.e. coordinates on the x-axis for vertical violins (or y-axis for horizontal violins).

  • vert (bool, optional) –

    Deprecated since version 3.10: Use orientation instead.

    If this is given during the deprecation period, it overrides the orientation parameter.

    If True, plots the violins vertically. If False, plots the violins horizontally.

  • orientation ({'vertical', 'horizontal'}, default: 'vertical') –

    If ‘horizontal’, plots the violins horizontally. Otherwise, plots the violins vertically.

    Added in version 3.10.

  • widths (float or array-like, default: 0.5) – The maximum width of each violin in units of the positions axis. The default is 0.5, which is half the available space when using default positions.

  • showmeans (bool, default: False) – Whether to show the mean with a line.

  • showextrema (bool, default: True) – Whether to show extrema with a line.

  • showmedians (bool, default: False) – Whether to show the median with a line.

  • quantiles (array-like, default: None) – If not None, set a list of floats in interval [0, 1] for each violin, which stands for the quantiles that will be rendered for that violin.

  • points (int, default: 100) – The number of points to evaluate each of the gaussian kernel density estimations at.

  • bw_method ({'scott', 'silverman'} or float or callable, default: 'scott') – The method used to calculate the estimator bandwidth. If a float, this will be used directly as kde.factor. If a callable, it should take a matplotlib.mlab.GaussianKDE instance as its only parameter and return a float.

  • side ({'both', 'low', 'high'}, default: 'both') – ‘both’ plots standard violins. ‘low’/’high’ only plots the side below/above the positions value.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    dataset

Returns:

A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys:

  • bodies: A list of the ~.collections.PolyCollection instances containing the filled area of each violin.

  • cmeans: A ~.collections.LineCollection instance that marks the mean values of each of the violin’s distribution.

  • cmins: A ~.collections.LineCollection instance that marks the bottom of each violin’s distribution.

  • cmaxes: A ~.collections.LineCollection instance that marks the top of each violin’s distribution.

  • cbars: A ~.collections.LineCollection instance that marks the centers of each violin’s distribution.

  • cmedians: A ~.collections.LineCollection instance that marks the median values of each of the violin’s distribution.

  • cquantiles: A ~.collections.LineCollection instance created to identify the quantile values of each of the violin’s distribution.

Return type:

dict

See also

Axes.violin

Draw a violin from pre-computed statistics.

boxplot

Draw a box and whisker plot.

vlines(x, ymin, ymax, colors=None, linestyles='solid', *, label='', data=None, **kwargs)[source]

Plot vertical lines at each x from ymin to ymax.

Parameters:
  • x (float or array-like) – x-indexes where to plot the lines.

  • ymin (float or array-like) – Respective beginning and end of each line. If scalars are provided, all lines will have the same length.

  • ymax (float or array-like) – Respective beginning and end of each line. If scalars are provided, all lines will have the same length.

  • colors (:mpltype:`color` or list of color, default: :rc:`lines.color`)

  • linestyles ({'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid')

  • label (str, default: '')

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, ymin, ymax, colors

  • **kwargs (~matplotlib.collections.LineCollection properties.)

Return type:

~matplotlib.collections.LineCollection

See also

hlines

horizontal lines

axvline

vertical line across the Axes

xaxis: maxis.XAxis

The .XAxis instance.

Common axis-related configuration can be achieved through high-level wrapper methods on Axes; e.g. ax.set_xticks <.Axes.set_xticks> is a shortcut for ax.xaxis.set_ticks <.Axis.set_ticks>. The xaxis attribute gives direct direct access to the underlying ~.axis.Axis if you need more control.

See also

  • Axis wrapper methods on Axes

  • Axis API

xaxis_date(tz=None)

Set up axis ticks and labels to treat data along the xaxis as dates.

Parameters:

tz (str or datetime.tzinfo, default: :rc:`timezone`) – The timezone used to create date labels.

xaxis_inverted()

Return whether the xaxis is oriented in the “inverse” direction.

The “normal” direction is increasing to the right for the x-axis and to the top for the y-axis; the “inverse” direction is increasing to the left for the x-axis and to the bottom for the y-axis.

xcorr(x, y, *, normed=True, detrend=<function detrend_none>, usevlines=True, maxlags=10, data=None, **kwargs)[source]

Plot the cross correlation between x and y.

The correlation with lag k is defined as \(\sum_n x[n+k] \cdot y^*[n]\), where \(y^*\) is the complex conjugate of \(y\).

Parameters:
  • x (array-like of length n) – Neither x nor y are run through Matplotlib’s unit conversion, so these should be unit-less arrays.

  • y (array-like of length n) – Neither x nor y are run through Matplotlib’s unit conversion, so these should be unit-less arrays.

  • detrend (callable, default: .mlab.detrend_none (no detrending)) –

    A detrending function applied to x and y. It must have the signature

    detrend(x: np.ndarray) -> np.ndarray
    

  • normed (bool, default: True) – If True, input vectors are normalised to unit length.

  • usevlines (bool, default: True) –

    Determines the plot style.

    If True, vertical lines are plotted from 0 to the xcorr value using .Axes.vlines. Additionally, a horizontal line is plotted at y=0 using .Axes.axhline.

    If False, markers are plotted at the xcorr values using .Axes.plot.

  • maxlags (int, default: 10) – Number of lags to show. If None, will return all 2 * len(x) - 1 lags.

  • linestyle (~matplotlib.lines.Line2D property, optional) – The linestyle for plotting the data points. Only used if usevlines is False.

  • marker (str, default: 'o') – The marker for plotting the data points. Only used if usevlines is False.

  • data (indexable object, optional) –

    If given, the following parameters also accept a string s, which is interpreted as data[s] if s is a key in data:

    x, y

  • **kwargs – Additional parameters are passed to .Axes.vlines and .Axes.axhline if usevlines is True; otherwise they are passed to .Axes.plot.

Returns:

  • lags (array (length ``2*maxlags+1`)`) – The lag vector.

  • c (array  (length ``2*maxlags+1`)`) – The auto correlation vector.

  • line (.LineCollection or .Line2D) – .Artist added to the Axes of the correlation:

    • .LineCollection if usevlines is True.

    • .Line2D if usevlines is False.

  • b (~matplotlib.lines.Line2D or None) – Horizontal line at 0 if usevlines is True None usevlines is False.

Notes

The cross correlation is performed with numpy.correlate with mode = "full".

yaxis: maxis.YAxis

The .YAxis instance.

Common axis-related configuration can be achieved through high-level wrapper methods on Axes; e.g. ax.set_yticks <.Axes.set_yticks> is a shortcut for ax.yaxis.set_ticks <.Axis.set_ticks>. The yaxis attribute gives direct access to the underlying ~.axis.Axis if you need more control.

See also

  • Axis wrapper methods on Axes

  • Axis API

yaxis_date(tz=None)

Set up axis ticks and labels to treat data along the yaxis as dates.

Parameters:

tz (str or datetime.tzinfo, default: :rc:`timezone`) – The timezone used to create date labels.

yaxis_inverted()

Return whether the yaxis is oriented in the “inverse” direction.

The “normal” direction is increasing to the right for the x-axis and to the top for the y-axis; the “inverse” direction is increasing to the left for the x-axis and to the bottom for the y-axis.

zorder = 0
class pyorps.utils.plotting.Figure(figsize=None, dpi=None, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, layout=None, **kwargs)[source]

Bases: FigureBase

The top level container for all the plot elements.

See matplotlib.figure for an index of class methods.

patch

The .Rectangle instance representing the figure background patch.

suppressComposite

For multiple images, the figure will make composite images depending on the renderer option_image_nocomposite function. If suppressComposite is a boolean, this will override the renderer.

__init__(figsize=None, dpi=None, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, layout=None, **kwargs)[source]
Parameters:
  • figsize (2-tuple of floats, default: :rc:`figure.figsize`) – Figure dimension (width, height) in inches.

  • dpi (float, default: :rc:`figure.dpi`) – Dots per inch.

  • facecolor (default: :rc:`figure.facecolor`) – The figure patch facecolor.

  • edgecolor (default: :rc:`figure.edgecolor`) – The figure patch edge color.

  • linewidth (float) – The linewidth of the frame (i.e. the edge linewidth of the figure patch).

  • frameon (bool, default: :rc:`figure.frameon`) – If False, suppress drawing the figure background patch.

  • subplotpars (~matplotlib.gridspec.SubplotParams) – Subplot parameters. If not given, the default subplot parameters :rc:`figure.subplot.*` are used.

  • tight_layout (bool or dict, default: :rc:`figure.autolayout`) –

    Whether to use the tight layout mechanism. See .set_tight_layout.

    Discouraged

    The use of this parameter is discouraged. Please use layout='tight' instead for the common case of tight_layout=True and use .set_tight_layout otherwise.

  • constrained_layout (bool, default: :rc:`figure.constrained_layout.use`) –

    This is equal to layout='constrained'.

    Discouraged

    The use of this parameter is discouraged. Please use layout='constrained' instead.

  • layout ({'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}, default: None) –

    The layout mechanism for positioning of plot elements to avoid overlapping Axes decorations (labels, ticks, etc). Note that layout managers can have significant performance penalties.

    • ’constrained’: The constrained layout solver adjusts Axes sizes to avoid overlapping Axes decorations. Can handle complex plot layouts and colorbars, and is thus recommended.

      See constrainedlayout_guide for examples.

    • ’compressed’: uses the same algorithm as ‘constrained’, but removes extra space between fixed-aspect-ratio Axes. Best for simple grids of Axes.

    • ’tight’: Use the tight layout mechanism. This is a relatively simple algorithm that adjusts the subplot parameters so that decorations do not overlap.

      See tight_layout_guide for examples.

    • ’none’: Do not use a layout engine.

    • A .LayoutEngine instance. Builtin layout classes are .ConstrainedLayoutEngine and .TightLayoutEngine, more easily accessible by ‘constrained’ and ‘tight’. Passing an instance allows third parties to provide their own layout engine.

    If not given, fall back to using the parameters tight_layout and constrained_layout, including their config defaults :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.

  • **kwargs (.Figure properties, optional) – Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool canvas: FigureCanvas clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None constrained_layout: unknown constrained_layout_pads: unknown dpi: float edgecolor: :mpltype:`color` facecolor: :mpltype:`color` figheight: float figure: unknown figwidth: float frameon: bool gid: str in_layout: bool label: object layout_engine: {‘constrained’, ‘compressed’, ‘tight’, ‘none’, .LayoutEngine, None} linewidth: number mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool size_inches: (float, float) or float sketch_params: (scale: float, length: float, randomness: float) snap: bool or None tight_layout: unknown transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float

add_artist(artist, clip=False)

Add an .Artist to the figure.

Usually artists are added to ~.axes.Axes objects using .Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead.

Parameters:
  • artist (~matplotlib.artist.Artist) – The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transSubfigure.

  • clip (bool, default: False) – Whether the added artist should be clipped by the figure patch.

Returns:

The added artist.

Return type:

~matplotlib.artist.Artist

add_axes(*args, **kwargs)

Add an ~.axes.Axes to the figure.

Call signatures:

add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters:
  • rect (tuple (left, bottom, width, height)) – The dimensions (left, bottom, width, height) of the new ~.axes.Axes. All quantities are in fractions of figure width and height.

  • projection ({None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional) – The projection type of the ~.axes.Axes. str is the name of a custom projection, see ~matplotlib.projections. The default None results in a ‘rectilinear’ projection.

  • polar (bool, default: False) – If True, equivalent to projection=’polar’.

  • axes_class (subclass type of ~.axes.Axes, optional) – The .axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist_users-guide-index for examples.

  • sharex (~matplotlib.axes.Axes, optional) – Share the x or y ~matplotlib.axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes.

  • sharey (~matplotlib.axes.Axes, optional) – Share the x or y ~matplotlib.axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes.

  • label (str) – A label for the returned Axes.

  • **kwargs

    This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class ~.axes.Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class.

    Properties: adjustable: {‘box’, ‘datalim’} agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None anchor: (float, float) or {‘C’, ‘SW’, ‘S’, ‘SE’, ‘E’, ‘NE’, …} animated: bool aspect: {‘auto’, ‘equal’} or float autoscale_on: bool autoscalex_on: unknown autoscaley_on: unknown axes_locator: Callable[[Axes, Renderer], Bbox] axisbelow: bool or ‘line’ box_aspect: float or None clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None facecolor or fc: :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure forward_navigation_events: bool or “auto” frame_on: bool gid: str in_layout: bool label: object mouseover: bool navigate: bool navigate_mode: unknown path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: [left, bottom, width, height] or ~matplotlib.transforms.Bbox prop_cycle: ~cycler.Cycler rasterization_zorder: float or None rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None subplotspec: unknown title: str transform: ~matplotlib.transforms.Transform url: str visible: bool xbound: (lower: float, upper: float) xlabel: str xlim: (left: float, right: float) xmargin: float greater than -0.5 xscale: unknown xticklabels: unknown xticks: unknown ybound: (lower: float, upper: float) ylabel: str ylim: (bottom: float, top: float) ymargin: float greater than -0.5 yscale: unknown yticklabels: unknown yticks: unknown zorder: float

Returns:

The returned Axes class depends on the projection used. It is ~.axes.Axes if rectilinear projection is used and .projections.polar.PolarAxes if polar projection is used.

Return type:

~.axes.Axes, or a subclass of ~.axes.Axes

Notes

In rare circumstances, .add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure’s list of Axes.

See also

Figure.add_subplot, pyplot.subplot, pyplot.axes, Figure.subplots, pyplot.subplots

Examples

Some simple examples:

rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
add_axobserver(func)[source]

Whenever the Axes state change, func(self) will be called.

add_callback(func)

Add a callback function that will be called whenever one of the .Artist’s properties changes.

Parameters:

func (callable) –

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:

The observer id associated with the callback. This id can be used for removing the callback with .remove_callback later.

Return type:

int

See also

remove_callback

add_gridspec(nrows=1, ncols=1, **kwargs)

Low-level API for creating a .GridSpec that has this figure as a parent.

This is a low-level API, allowing you to create a gridspec and subsequently add subplots based on the gridspec. Most users do not need that freedom and should use the higher-level methods ~.Figure.subplots or ~.Figure.subplot_mosaic.

Parameters:
  • nrows (int, default: 1) – Number of rows in grid.

  • ncols (int, default: 1) – Number of columns in grid.

  • **kwargs – Keyword arguments are passed to .GridSpec.

Return type:

.GridSpec

See also

matplotlib.pyplot.subplots

Examples

Adding a subplot that spans two rows:

fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
add_subfigure(subplotspec, **kwargs)

Add a .SubFigure to the figure as part of a subplot arrangement.

Parameters:
  • subplotspec (.gridspec.SubplotSpec) – Defines the region in a parent gridspec where the subfigure will be placed.

  • **kwargs – Are passed to the .SubFigure object.

Return type:

.SubFigure

add_subplot(*args, **kwargs)

Add an ~.axes.Axes to the figure as part of a subplot arrangement.

Call signatures:

add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters:
  • *args (int, (int, int, *index*), or .SubplotSpec, default: (1, 1, 1)) –

    The position of the subplot described by one of

    • Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure.

    • A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots.

    • A .SubplotSpec.

    In rare circumstances, .add_subplot may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure’s list of Axes.

  • projection ({None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional) – The projection type of the subplot (~.axes.Axes). str is the name of a custom projection, see ~matplotlib.projections. The default None results in a ‘rectilinear’ projection.

  • polar (bool, default: False) – If True, equivalent to projection=’polar’.

  • axes_class (subclass type of ~.axes.Axes, optional) – The .axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist_users-guide-index for examples.

  • sharex (~matplotlib.axes.Axes, optional) – Share the x or y ~matplotlib.axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes.

  • sharey (~matplotlib.axes.Axes, optional) – Share the x or y ~matplotlib.axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes.

  • label (str) – A label for the returned Axes.

  • **kwargs

    This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class ~.axes.Axes can be found in the following table but there might also be other keyword arguments if another projection is used.

    Properties: adjustable: {‘box’, ‘datalim’} agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None anchor: (float, float) or {‘C’, ‘SW’, ‘S’, ‘SE’, ‘E’, ‘NE’, …} animated: bool aspect: {‘auto’, ‘equal’} or float autoscale_on: bool autoscalex_on: unknown autoscaley_on: unknown axes_locator: Callable[[Axes, Renderer], Bbox] axisbelow: bool or ‘line’ box_aspect: float or None clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None facecolor or fc: :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure forward_navigation_events: bool or “auto” frame_on: bool gid: str in_layout: bool label: object mouseover: bool navigate: bool navigate_mode: unknown path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: [left, bottom, width, height] or ~matplotlib.transforms.Bbox prop_cycle: ~cycler.Cycler rasterization_zorder: float or None rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None subplotspec: unknown title: str transform: ~matplotlib.transforms.Transform url: str visible: bool xbound: (lower: float, upper: float) xlabel: str xlim: (left: float, right: float) xmargin: float greater than -0.5 xscale: unknown xticklabels: unknown xticks: unknown ybound: (lower: float, upper: float) ylabel: str ylim: (bottom: float, top: float) ymargin: float greater than -0.5 yscale: unknown yticklabels: unknown yticks: unknown zorder: float

Returns:

The Axes of the subplot. The returned Axes can actually be an instance of a subclass, such as .projections.polar.PolarAxes for polar projections.

Return type:

~.axes.Axes

See also

Figure.add_axes, pyplot.subplot, pyplot.axes, Figure.subplots, pyplot.subplots

Examples

fig = plt.figure()

fig.add_subplot(231)
ax1 = fig.add_subplot(2, 3, 1)  # equivalent but more general

fig.add_subplot(232, frameon=False)  # subplot with no frame
fig.add_subplot(233, projection='polar')  # polar subplot
fig.add_subplot(234, sharex=ax1)  # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red")  # red subplot

ax1.remove()  # delete ax1 from the figure
fig.add_subplot(ax1)  # add ax1 back to the figure
align_labels(axs=None)

Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set).

Alignment persists for draw events after this is called.

Parameters:

axs (list of ~matplotlib.axes.Axes) – Optional list (or ~numpy.ndarray) of ~matplotlib.axes.Axes to align the labels. Default is to align all Axes on the figure.

See also

matplotlib.figure.Figure.align_xlabels, matplotlib.figure.Figure.align_ylabels, matplotlib.figure.Figure.align_titles

Notes

This assumes that all Axes in axs are from the same .GridSpec, so that their .SubplotSpec positions correspond to figure positions.

align_titles(axs=None)

Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set).

Alignment persists for draw events after this is called.

Parameters:

axs (list of ~matplotlib.axes.Axes) – Optional list of (or ndarray) ~matplotlib.axes.Axes to align the titles. Default is to align all Axes on the figure.

See also

matplotlib.figure.Figure.align_xlabels, matplotlib.figure.Figure.align_ylabels, matplotlib.figure.Figure.align_labels

Notes

This assumes that all Axes in axs are from the same .GridSpec, so that their .SubplotSpec positions correspond to figure positions.

Examples

Example with titles:

fig, axs = plt.subplots(1, 2)
axs[0].set_aspect('equal')
axs[0].set_title('Title 0')
axs[1].set_title('Title 1')
fig.align_titles()
align_xlabels(axs=None)

Align the xlabels of subplots in the same subplot row if label alignment is being done automatically (i.e. the label position is not manually set).

Alignment persists for draw events after this is called.

If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row.

Parameters:

axs (list of ~matplotlib.axes.Axes) – Optional list of (or ~numpy.ndarray) ~matplotlib.axes.Axes to align the xlabels. Default is to align all Axes on the figure.

See also

matplotlib.figure.Figure.align_ylabels, matplotlib.figure.Figure.align_titles, matplotlib.figure.Figure.align_labels

Notes

This assumes that all Axes in axs are from the same .GridSpec, so that their .SubplotSpec positions correspond to figure positions.

Examples

Example with rotated xtick labels:

fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
    tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
align_ylabels(axs=None)

Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).

Alignment persists for draw events after this is called.

If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column.

Parameters:

axs (list of ~matplotlib.axes.Axes) – Optional list (or ~numpy.ndarray) of ~matplotlib.axes.Axes to align the ylabels. Default is to align all Axes on the figure.

See also

matplotlib.figure.Figure.align_xlabels, matplotlib.figure.Figure.align_titles, matplotlib.figure.Figure.align_labels

Notes

This assumes that all Axes in axs are from the same .GridSpec, so that their .SubplotSpec positions correspond to figure positions.

Examples

Example with large yticks labels:

fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')

Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.

Parameters:
  • bottom (float, default: 0.2) – The bottom of the subplots for subplots_adjust.

  • rotation (float, default: 30 degrees) – The rotation angle of the xtick labels in degrees.

  • ha ({'left', 'center', 'right'}, default: 'right') – The horizontal alignment of the xticklabels.

  • which ({'major', 'minor', 'both'}, default: 'major') – Selects which ticklabels to rotate.

property axes

List of Axes in the Figure. You can access and modify the Axes in the Figure through this list.

Do not modify the list itself. Instead, use ~Figure.add_axes, ~.Figure.add_subplot or ~.Figure.delaxes to add or remove an Axes.

Note: The .Figure.axes property and ~.Figure.get_axes method are equivalent.

clear(keep_observers=False)[source]

Clear the figure.

Parameters:

keep_observers (bool, default: False) – Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.

clf(keep_observers=False)

[Discouraged] Alias for the clear() method.

Discouraged

The use of clf() is discouraged. Use clear() instead.

Parameters:

keep_observers (bool, default: False) – Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.

colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kwargs)

Add a colorbar to a plot.

Parameters:
  • mappable

    The matplotlib.cm.ScalarMappable (i.e., .AxesImage, .ContourSet, etc.) described by this colorbar. This argument is mandatory for the .Figure.colorbar method but optional for the .pyplot.colorbar function, which sets the default to the current image.

    Note that one can create a .ScalarMappable “on-the-fly” to generate colorbars not attached to a previously drawn artist, e.g.

    fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
    

  • cax (~matplotlib.axes.Axes, optional) – Axes into which the colorbar will be drawn. If None, then a new Axes is created and the space for it will be stolen from the Axes(s) specified in ax.

  • ax (~matplotlib.axes.Axes or iterable or numpy.ndarray of Axes, optional) –

    The one or more parent Axes from which space for a new colorbar Axes will be stolen. This parameter is only used if cax is not set.

    Defaults to the Axes that contains the mappable used to create the colorbar.

  • use_gridspec (bool, optional) – If cax is None, a new cax is created as an instance of Axes. If ax is positioned with a subplotspec and use_gridspec is True, then cax is also positioned with a subplotspec.

  • location (None or {'left', 'right', 'top', 'bottom'}) – The location, relative to the parent Axes, where the colorbar Axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to ‘right’ if orientation is unset.

  • orientation (None or {'vertical', 'horizontal'}) – The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception.

  • fraction (float, default: 0.15) – Fraction of original Axes to use for colorbar.

  • shrink (float, default: 1.0) – Fraction by which to multiply the size of the colorbar.

  • aspect (float, default: 20) – Ratio of long to short dimensions.

  • pad (float, default: 0.05 if vertical, 0.15 if horizontal) – Fraction of original Axes between colorbar and new image Axes.

  • anchor ((float, float), optional) – The anchor point of the colorbar Axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.

  • panchor ((float, float), or *False*, optional) – The anchor point of the colorbar parent Axes. If False, the parent axes’ anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.

  • extend ({'neither', 'both', 'min', 'max'}) – Make pointed end(s) for out-of-range values (unless ‘neither’). These are set for a given colormap using the colormap set_under and set_over methods.

  • extendfrac ({*None*, 'auto', length, lengths}) –

    If set to None, both the minimum and maximum triangular colorbar extensions will have a length of 5% of the interior colorbar length (this is the default setting).

    If set to ‘auto’, makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to ‘uniform’) or the same lengths as the respective adjacent interior boxes (when spacing is set to ‘proportional’).

    If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.

  • extendrect (bool) – If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.

  • ticks (None or list of ticks or Locator) – If None, ticks are determined automatically from the input.

  • format (None or str or Formatter) – If None, ~.ticker.ScalarFormatter is used. Format strings, e.g., "%4.2e" or "{x:.2e}", are supported. An alternative ~.ticker.Formatter may be given instead.

  • drawedges (bool) – Whether to draw lines at color boundaries.

  • label (str) – The label on the colorbar’s long axis.

  • boundaries (None or a sequence) – If unset, the colormap will be displayed on a 0-1 scale. If sequences, values must have a length 1 less than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. The size of each region is determined by the spacing parameter. Normally only useful for indexed colors (i.e. norm=NoNorm()) or other unusual circumstances.

  • values (None or a sequence) – If unset, the colormap will be displayed on a 0-1 scale. If sequences, values must have a length 1 less than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. The size of each region is determined by the spacing parameter. Normally only useful for indexed colors (i.e. norm=NoNorm()) or other unusual circumstances.

  • spacing ({'uniform', 'proportional'}) – For discrete colorbars (.BoundaryNorm or contours), ‘uniform’ gives each color the same space; ‘proportional’ makes the space proportional to the data interval.

Returns:

colorbar

Return type:

~matplotlib.colorbar.Colorbar

Notes

If mappable is a ~.contour.ContourSet, its extend kwarg is included automatically.

The shrink kwarg provides a simple way to scale the colorbar with respect to the Axes. Note that if cax is specified, it determines the size of the colorbar, and shrink and aspect are ignored.

For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the Axes properties kwargs.

It is known that some vector graphics viewers (svg and pdf) render white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:

cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()

However, this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).

contains(mouseevent)

Test whether the mouse event occurred on the figure.

Returns:

bool, {}

convert_xunits(x)

Convert x using the unit type of the xaxis.

If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.

convert_yunits(y)

Convert y using the unit type of the yaxis.

If the artist is not contained in an Axes or if the yaxis does not have units, y itself is returned.

delaxes(ax)

Remove the ~.axes.Axes ax from the figure; update the current Axes.

property dpi

The resolution in dots per inch.

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:

renderer (~matplotlib.backend_bases.RendererBase subclass.)

Notes

This method is overridden in the Artist subclasses.

draw_artist(a)[source]

Draw .Artist a only.

draw_without_rendering()[source]

Draw the figure with no output. Useful to get the final size of artists that require a draw before their size is known (e.g. text).

figimage(X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, *, colorizer=None, **kwargs)[source]

Add a non-resampled image to the figure.

The image is attached to the lower or upper left corner depending on origin.

Parameters:
  • X

    The image data. This is an array of one of the following shapes:

    • (M, N): an image with scalar data. Color-mapping is controlled by cmap, norm, vmin, and vmax.

    • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).

    • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

  • xo (int) – The x/y image offset in pixels.

  • yo (int) – The x/y image offset in pixels.

  • alpha (None or float) – The alpha blending value.

  • cmap (str or ~matplotlib.colors.Colormap, default: :rc:`image.cmap`) –

    The Colormap instance or registered colormap name used to map scalar data to colors.

    This parameter is ignored if X is RGB(A).

  • norm (str or ~matplotlib.colors.Normalize, optional) –

    The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

    If given, this can be one of the following:

    • An instance of .Normalize or one of its subclasses (see colormapnorms).

    • A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a list of available scales, call matplotlib.scale.get_scale_names(). In that case, a suitable .Normalize subclass is dynamically generated and instantiated.

    This parameter is ignored if X is RGB(A).

  • vmin (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if X is RGB(A).

  • vmax (float, optional) –

    When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

    This parameter is ignored if X is RGB(A).

  • origin ({'upper', 'lower'}, default: :rc:`image.origin`) – Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the Axes.

  • resize (bool) – If True, resize the figure to match the given image size.

  • colorizer (~matplotlib.colorizer.Colorizer or None, default: None) –

    The Colorizer object used to map color to data. If None, a Colorizer object is created from a norm and cmap.

    This parameter is ignored if X is RGB(A).

  • **kwargs – Additional kwargs are .Artist kwargs passed on to .FigureImage.

Return type:

matplotlib.image.FigureImage

Notes

figimage complements the Axes image (~matplotlib.axes.Axes.imshow) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define an ~matplotlib.axes.Axes with extent [0, 0, 1, 1].

Examples

f = plt.figure()
nx = int(f.get_figwidth() * f.dpi)
ny = int(f.get_figheight() * f.dpi)
data = np.random.random((ny, nx))
f.figimage(data)
plt.show()
property figure

The root Figure. To get the parent of a SubFigure, use the get_figure method.

findobj(match=None, include_self=True)

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_self (bool) – Include self in the list to be checked for a match.

Return type:

list of .Artist

format_cursor_data(data)

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

property frameon

Return the figure’s background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().

gca()

Get the current Axes.

If there is currently no Axes on this Figure, a new one is created using .Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether .pyplot.get_fignums() is empty.)

get_agg_filter()

Return filter function to be used for agg filter.

get_alpha()

Return the alpha value used for blending - not supported on all backends.

get_animated()

Return whether the artist is animated.

get_axes()

List of Axes in the Figure. You can access and modify the Axes in the Figure through this list.

Do not modify the list itself. Instead, use ~Figure.add_axes, ~.Figure.add_subplot or ~.Figure.delaxes to add or remove an Axes.

Note: The .Figure.axes property and ~.Figure.get_axes method are equivalent.

get_children()

Get a list of artists contained in the figure.

get_clip_box()

Return the clipbox.

get_clip_on()

Return whether the artist uses clipping.

get_clip_path()

Return the clip path.

get_constrained_layout()[source]

Return whether constrained layout is being used.

See constrainedlayout_guide.

get_constrained_layout_pads(relative=False)[source]

[Deprecated] Get padding for constrained_layout.

Returns a list of w_pad, h_pad in inches and wspace and hspace as fractions of the subplot. All values are None if constrained_layout is not used.

See constrainedlayout_guide.

Parameters:

relative (bool) – If True, then convert from inches to figure relative.

Notes

Deprecated since version 3.6: Use fig.get_layout_engine().get() instead.

get_cursor_data(event)

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:

event (~matplotlib.backend_bases.MouseEvent)

get_default_bbox_extra_artists()

Return a list of Artists typically used in .Figure.get_tightbbox.

get_dpi()[source]

Return the resolution in dots per inch as a float.

get_edgecolor()

Get the edge color of the Figure rectangle.

get_facecolor()

Get the face color of the Figure rectangle.

get_figheight()[source]

Return the figure height in inches.

get_figure(root=None)

Return the .Figure or .SubFigure instance the (Sub)Figure belongs to.

Parameters:

root (bool, default True) –

If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.

Deprecated since version 3.10: From version 3.12 root will default to False.

get_figwidth()[source]

Return the figure width in inches.

get_frameon()

Return the figure’s background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().

get_gid()

Return the group id.

get_in_layout()

Return boolean flag, True if artist is included in layout calculations.

E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

get_label()

Return the label used for this artist in the legend.

get_layout_engine()[source]
get_linewidth()

Get the line width of the Figure rectangle.

get_mouseover()

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

get_path_effects()
get_picker()

Return the picking behavior of the artist.

The possible values are described in .Artist.set_picker.

See also

Artist.set_picker, Artist.pickable, Artist.pick

get_rasterized()

Return whether the artist is to be rasterized.

get_size_inches()[source]

Return the current size of the figure in inches.

Returns:

The size (width, height) of the figure in inches.

Return type:

ndarray

See also

matplotlib.figure.Figure.set_size_inches, matplotlib.figure.Figure.get_figwidth, matplotlib.figure.Figure.get_figheight

Notes

The size in pixels can be obtained by multiplying with Figure.dpi.

get_sketch_params()

Return the sketch parameters for the artist.

Returns:

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.

Return type:

tuple or None

get_snap()

Return the snap setting.

See .set_snap for details.

get_suptitle()

Return the suptitle as string or an empty string if not set.

get_supxlabel()

Return the supxlabel as string or an empty string if not set.

get_supylabel()

Return the supylabel as string or an empty string if not set.

get_tight_layout()[source]

Return whether .Figure.tight_layout is called when drawing.

get_tightbbox(renderer=None, *, bbox_extra_artists=None)

Return a (tight) bounding box of the figure in inches.

Note that .FigureBase differs from all other artists, which return their .Bbox in pixels.

Artists that have artist.set_in_layout(False) are not included in the bbox.

Parameters:
  • renderer (.RendererBase subclass) – Renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())

  • bbox_extra_artists (list of .Artist or None) – List of artists to include in the tight bounding box. If None (default), then all artist children of each Axes are included in the tight bounding box.

Returns:

containing the bounding box (in figure inches).

Return type:

.BboxBase

get_transform()

Return the .Transform instance used by this artist.

get_transformed_clip_path_and_affine()

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

get_url()

Return the url.

get_visible()

Return the visibility.

get_window_extent(renderer=None)

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()

Return the artist’s zorder.

ginput(n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE)[source]

Blocking call to interact with a figure.

Wait until the user clicks n times on the figure, and return the coordinates of each click in a list.

There are three possible interactions:

  • Add a point.

  • Remove the most recently added point.

  • Stop the interaction and return the points added so far.

The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop.

Parameters:
  • n (int, default: 1) – Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.

  • timeout (float, default: 30 seconds) – Number of seconds to wait before timing out. If zero or negative will never time out.

  • show_clicks (bool, default: True) – If True, show a red cross at the location of each click.

  • mouse_add (.MouseButton or None, default: .MouseButton.LEFT) – Mouse button used to add points.

  • mouse_pop (.MouseButton or None, default: .MouseButton.RIGHT) – Mouse button used to remove the most recently added point.

  • mouse_stop (.MouseButton or None, default: .MouseButton.MIDDLE) – Mouse button used to stop input.

Returns:

A list of the clicked (x, y) coordinates.

Return type:

list of tuples

Notes

The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right-clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.

have_units()

Return whether units are set on any axis.

is_transform_set()

Return whether the Artist has an explicitly set transform.

This is True after .set_transform has been called.

legend(*args, **kwargs)

Place a legend on the figure.

Call signatures:

legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)

The call signatures correspond to the following different ways to use this method:

1. Automatic detection of elements to be shown in the legend

The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.

In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist:

ax.plot([1, 2, 3], label='Inline label')
fig.legend()

or:

line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
fig.legend()

Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling .Figure.legend without any arguments and without setting the labels manually will result in no legend being drawn.

2. Explicitly listing the artists and labels in the legend

For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:

fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])

3. Explicitly listing the artists in the legend

This is similar to 2, but the labels are taken from the artists’ label properties. Example:

line1, = ax1.plot([1, 2, 3], label='label1')
line2, = ax2.plot([1, 2, 3], label='label2')
fig.legend(handles=[line1, line2])

4. Labeling existing plot elements

Discouraged

This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.

To make a legend for all artists on all Axes, call this function with an iterable of strings, one for each legend item. For example:

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 3, 5], color='blue')
ax2.plot([2, 4, 6], color='red')
fig.legend(['the blues', 'the reds'])
Parameters:
  • handles (list of .Artist, optional) –

    A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

    The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.

  • labels (list of str, optional) – A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

  • loc (str or pair of floats, default: 'upper right') –

    The location of the legend.

    The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the figure.

    The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the figure.

    The string 'center' places the legend at the center of the figure.

    The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in figure coordinates (in which case bbox_to_anchor will be ignored).

    For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each “string” location can also be given as a numeric value:

    Location String

    Location Code

    ’best’ (Axes only)

    0

    ’upper right’

    1

    ’upper left’

    2

    ’lower left’

    3

    ’lower right’

    4

    ’right’

    5

    ’center left’

    6

    ’center right’

    7

    ’lower center’

    8

    ’upper center’

    9

    ’center’

    10

    If a figure is using the constrained layout manager, the string codes of the loc keyword argument can get better layout behaviour using the prefix ‘outside’. There is ambiguity at the corners, so ‘outside upper right’ will make space for the legend above the rest of the axes in the layout, and ‘outside right upper’ will make space on the right side of the layout. In addition to the values of loc listed above, we have ‘outside right upper’, ‘outside right lower’, ‘outside left upper’, and ‘outside left lower’. See legend_guide for more details.

  • bbox_to_anchor (.BboxBase, 2-tuple, or 4-tuple of floats) –

    Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to .Axes.legend) or figure.bbox (if figure.legend). This argument allows arbitrary placement of the legend.

    Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called.

    If a 4-tuple or .BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the Axes (or figure):

    loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
    

    A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend’s upper right-hand corner in the center of the Axes (or figure) the following keywords can be used:

    loc='upper right', bbox_to_anchor=(0.5, 0.5)
    

  • ncols (int, default: 1) –

    The number of columns that the legend has.

    For backward compatibility, the spelling ncol is also supported but it is discouraged. If both are given, ncols takes precedence.

  • prop (None or ~matplotlib.font_manager.FontProperties or dict) – The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

  • fontsize (int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}) – The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.

  • labelcolor (str or list, default: :rc:`legend.labelcolor`) –

    The color of the text in the legend. Either a valid color string (for example, ‘red’), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using ‘linecolor’, ‘markerfacecolor’ (or ‘mfc’), or ‘markeredgecolor’ (or ‘mec’).

    Labelcolor can be set globally using :rc:`legend.labelcolor`. If None, use :rc:`text.color`.

  • numpoints (int, default: :rc:`legend.numpoints`) – The number of marker points in the legend when creating a legend entry for a .Line2D (line).

  • scatterpoints (int, default: :rc:`legend.scatterpoints`) – The number of marker points in the legend when creating a legend entry for a .PathCollection (scatter plot).

  • scatteryoffsets (iterable of floats, default: :py:class:`[0.375`, ``0.5, 0.3125]``) – The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].

  • markerscale (float, default: :rc:`legend.markerscale`) – The relative size of legend markers compared to the originally drawn ones.

  • markerfirst (bool, default: True) – If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.

  • reverse (bool, default: False) –

    If True, the legend labels are displayed in reverse order from the input. If False, the legend labels are displayed in the same order as the input.

    Added in version 3.7.

  • frameon (bool, default: :rc:`legend.frameon`) – Whether the legend should be drawn on a patch (frame).

  • fancybox (bool, default: :rc:`legend.fancybox`) – Whether round edges should be enabled around the .FancyBboxPatch which makes up the legend’s background.

  • shadow (None, bool or dict, default: :rc:`legend.shadow`) – Whether to draw a shadow behind the legend. The shadow can be configured using .Patch keywords. Customization via :rc:`legend.shadow` is currently not supported.

  • framealpha (float, default: :rc:`legend.framealpha`) – The alpha transparency of the legend’s background. If shadow is activated and framealpha is None, the default value is ignored.

  • facecolor ("inherit" or color, default: :rc:`legend.facecolor`) – The legend’s background color. If "inherit", use :rc:`axes.facecolor`.

  • edgecolor ("inherit" or color, default: :rc:`legend.edgecolor`) – The legend’s background patch edge color. If "inherit", use :rc:`axes.edgecolor`.

  • mode ({"expand", None}) – If mode is set to "expand" the legend will be horizontally expanded to fill the Axes area (or bbox_to_anchor if defines the legend’s size).

  • bbox_transform (None or ~matplotlib.transforms.Transform) – The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’ transAxes transform will be used.

  • title (str or None) – The legend’s title. Default is no title (None).

  • title_fontproperties (None or ~matplotlib.font_manager.FontProperties or dict) – The font properties of the legend’s title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current :rc:`legend.title_fontsize` will be used.

  • title_fontsize (int or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`) – The font size of the legend’s title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.

  • alignment ({'center', 'left', 'right'}, default: 'center') – The alignment of the legend title and the box of entries. The entries are aligned as a single block, so that markers always lined up.

  • borderpad (float, default: :rc:`legend.borderpad`) – The fractional whitespace inside the legend border, in font-size units.

  • labelspacing (float, default: :rc:`legend.labelspacing`) – The vertical space between the legend entries, in font-size units.

  • handlelength (float, default: :rc:`legend.handlelength`) – The length of the legend handles, in font-size units.

  • handleheight (float, default: :rc:`legend.handleheight`) – The height of the legend handles, in font-size units.

  • handletextpad (float, default: :rc:`legend.handletextpad`) – The pad between the legend handle and text, in font-size units.

  • borderaxespad (float, default: :rc:`legend.borderaxespad`) – The pad between the Axes and legend border, in font-size units.

  • columnspacing (float, default: :rc:`legend.columnspacing`) – The spacing between columns, in font-size units.

  • handler_map (dict or None) – The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map.

  • draggable (bool, default: False) – Whether the legend can be dragged with the mouse.

Return type:

~matplotlib.legend.Legend

See also

Axes.legend

Notes

Some artists are not supported by this function. See legend_guide for details.

property mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

property number

The figure id, used to identify figures in .pyplot.

pchanged()

Call all of the registered callbacks.

This function is triggered internally when a property is changed.

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

Artist.set_picker, Artist.get_picker, Artist.pickable

pickable()

Return whether the artist is pickable.

See also

Artist.set_picker, Artist.get_picker, Artist.pick

properties()

Return a dictionary of all the properties of the artist.

remove()

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 ~.axes.Axes.relim to update the Axes limits if desired.

Note: ~.axes.Axes.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)

Remove a callback based on its observer id.

See also

add_callback

savefig(fname, *, transparent=None, **kwargs)[source]

Save the current figure as an image or vector graphic to a file.

Call signature:

savefig(fname, *, transparent=None, dpi='figure', format=None,
        metadata=None, bbox_inches=None, pad_inches=0.1,
        facecolor='auto', edgecolor='auto', backend=None,
        **kwargs
       )

The available output formats depend on the backend being used.

Parameters:
  • fname (str or path-like or binary file-like) –

    A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages.

    If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.

    If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with :rc:`savefig.format` and the appropriate extension is appended to fname.

  • transparent (bool, default: :rc:`savefig.transparent`) –

    If True, the Axes patches will all be transparent; the Figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs.

    If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used).

    The transparency of these patches will be restored to their original values upon exit of this function.

    This is useful, for example, for displaying a plot on top of a colored background on a web page.

  • dpi (float or 'figure', default: :rc:`savefig.dpi`) – The resolution in dots per inch. If ‘figure’, use the figure’s dpi value.

  • format (str) – The file format, e.g. ‘png’, ‘pdf’, ‘svg’, … The behavior when this is unset is documented under fname.

  • metadata (dict, optional) –

    Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:

    • ’png’ with Agg backend: See the parameter metadata of ~.FigureCanvasAgg.print_png.

    • ’pdf’ with pdf backend: See the parameter metadata of ~.backend_pdf.PdfPages.

    • ’svg’ with svg backend: See the parameter metadata of ~.FigureCanvasSVG.print_svg.

    • ’eps’ and ‘ps’ with PS backend: Only ‘Creator’ is supported.

    Not supported for ‘pgf’, ‘raw’, and ‘rgba’ as those formats do not support embedding metadata. Does not currently support ‘jpg’, ‘tiff’, or ‘webp’, but may include embedding EXIF metadata in the future.

  • bbox_inches (str or .Bbox, default: :rc:`savefig.bbox`) – Bounding box in inches: only the given portion of the figure is saved. If ‘tight’, try to figure out the tight bbox of the figure.

  • pad_inches (float or 'layout', default: :rc:`savefig.pad_inches`) – Amount of padding in inches around the figure when bbox_inches is ‘tight’. If ‘layout’ use the padding from the constrained or compressed layout engine; ignored if one of those engines is not in use.

  • facecolor (:mpltype:`color` or 'auto', default: :rc:`savefig.facecolor`) – The facecolor of the figure. If ‘auto’, use the current figure facecolor.

  • edgecolor (:mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor`) – The edgecolor of the figure. If ‘auto’, use the current figure edgecolor.

  • backend (str, optional) – Use a non-default backend to render the file, e.g. to render a png file with the “cairo” backend rather than the default “agg”, or a pdf file with the “pgf” backend rather than the default “pdf”. Note that the default backend is normally sufficient. See the-builtin-backends for a list of valid backends for each file format. Custom backends can be referenced as “module://…”.

  • orientation ({'landscape', 'portrait'}) – Currently only supported by the postscript backend.

  • papertype (str) – One of ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through ‘a10’, ‘b0’ through ‘b10’. Only supported for postscript output.

  • bbox_extra_artists (list of ~matplotlib.artist.Artist, optional) – A list of extra artists that will be considered when the tight bbox is calculated.

  • pil_kwargs (dict, optional) – Additional keyword arguments that are passed to PIL.Image.Image.save when saving the figure.

sca(a)

Set the current Axes to be a and return a.

set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, canvas=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, constrained_layout=<UNSET>, constrained_layout_pads=<UNSET>, dpi=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, figheight=<UNSET>, figwidth=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, layout_engine=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, size_inches=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, tight_layout=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool canvas: FigureCanvas clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None constrained_layout: unknown constrained_layout_pads: unknown dpi: float edgecolor: :mpltype:`color` facecolor: :mpltype:`color` figheight: float figure: unknown figwidth: float frameon: bool gid: str in_layout: bool label: object layout_engine: {‘constrained’, ‘compressed’, ‘tight’, ‘none’, .LayoutEngine, None} linewidth: number mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool size_inches: (float, float) or float sketch_params: (scale: float, length: float, randomness: float) snap: bool or None tight_layout: unknown transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float

set_agg_filter(filter_func)

Set the agg filter.

Parameters:

filter_func (callable) –

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

set_alpha(alpha)

Set the alpha value used for blending - not supported on all backends.

Parameters:

alpha (float or None) – alpha must be within the 0-1 range, inclusive.

set_animated(b)

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 approach is used to speed up animations using blitting.

See also matplotlib.animation and blitting.

Parameters:

b (bool)

set_canvas(canvas)[source]

Set the canvas that contains the figure

Parameters:

canvas (FigureCanvas)

set_clip_box(clipbox)

Set the artist’s clip .Bbox.

Parameters:

clipbox (~matplotlib.transforms.BboxBase or None) – Will typically be created from a .TransformedBbox. For instance, TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes) is the default clipping for an artist added to an Axes.

set_clip_on(b)

Set whether the artist uses clipping.

When False, artists will be visible outside the Axes which can lead to unexpected results.

Parameters:

b (bool)

set_clip_path(path, transform=None)

Set the artist’s clip path.

Parameters:
  • path (~matplotlib.patches.Patch 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.

  • transform (~matplotlib.transforms.Transform, 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 ~.Artist.set), a tuple (path, transform) is also accepted as a single positional parameter.

set_constrained_layout(constrained)[source]

[Deprecated] Set whether constrained_layout is used upon drawing.

If None, :rc:`figure.constrained_layout.use` value will be used.

When providing a dict containing the keys w_pad, h_pad the default constrained_layout paddings will be overridden. These pads are in inches and default to 3.0/72.0. w_pad is the width padding and h_pad is the height padding.

Parameters:

constrained (bool or dict or None)

Notes

Deprecated since version 3.6: Use set_layout_engine(‘constrained’) instead.

set_constrained_layout_pads(**kwargs)[source]

[Deprecated] Set padding for constrained_layout.

Tip: The parameters can be passed from a dictionary by using fig.set_constrained_layout(**pad_dict).

See constrainedlayout_guide.

Parameters:

Notes

Deprecated since version 3.6: Use figure.get_layout_engine().set() instead.

set_dpi(val)[source]

Set the resolution of the figure in dots-per-inch.

Parameters:

val (float)

set_edgecolor(color)

Set the edge color of the Figure rectangle.

Parameters:

color (:mpltype:`color`)

set_facecolor(color)

Set the face color of the Figure rectangle.

Parameters:

color (:mpltype:`color`)

set_figheight(val, forward=True)[source]

Set the height of the figure in inches.

Parameters:
  • val (float)

  • forward (bool) – See set_size_inches.

See also

matplotlib.figure.Figure.set_figwidth, matplotlib.figure.Figure.set_size_inches

set_figure(fig)

Deprecated since version 3.10: Currently this method will raise an exception if fig is anything other than the root .Figure this (Sub)Figure is on. In future it will always raise an exception.

set_figwidth(val, forward=True)[source]

Set the width of the figure in inches.

Parameters:
  • val (float)

  • forward (bool) – See set_size_inches.

See also

matplotlib.figure.Figure.set_figheight, matplotlib.figure.Figure.set_size_inches

set_frameon(b)

Set the figure’s background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible().

Parameters:

b (bool)

set_gid(gid)

Set the (group) id for the artist.

Parameters:

gid (str)

set_in_layout(in_layout)

Set if artist is to be included in layout calculations, E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

Parameters:

in_layout (bool)

set_label(s)

Set a label that will be displayed in the legend.

Parameters:

s (object) – s will be converted to a string by calling str.

set_layout_engine(layout=None, **kwargs)[source]

Set the layout engine for this figure.

Parameters:
  • layout ({'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}) –

    • ‘constrained’ will use ~.ConstrainedLayoutEngine

    • ’compressed’ will also use ~.ConstrainedLayoutEngine, but with a correction that attempts to make a good layout for fixed-aspect ratio Axes.

    • ’tight’ uses ~.TightLayoutEngine

    • ’none’ removes layout engine.

    If a .LayoutEngine instance, that instance will be used.

    If None, the behavior is controlled by :rc:`figure.autolayout` (which if True behaves as if ‘tight’ was passed) and :rc:`figure.constrained_layout.use` (which if True behaves as if ‘constrained’ was passed). If both are True, :rc:`figure.autolayout` takes priority.

    Users and libraries can define their own layout engines and pass the instance directly as well.

  • **kwargs – The keyword arguments are passed to the layout engine to set things like padding and margin sizes. Only used if layout is a string.

set_linewidth(linewidth)

Set the line width of the Figure rectangle.

Parameters:

linewidth (number)

set_mouseover(mouseover)

Set whether this artist is queried for custom context information when the mouse cursor moves over it.

Parameters:

mouseover (bool)

See also

get_cursor_data, ToolCursorPosition, NavigationToolbar2

set_path_effects(path_effects)

Set the path effects.

Parameters:

path_effects (list of .AbstractPathEffect)

set_picker(picker)

Define the picking behavior of the artist.

Parameters:

picker (None 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_rasterized(rasterized)

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 /gallery/misc/rasterization_demo.

Parameters:

rasterized (bool)

set_size_inches(w, h=None, forward=True)[source]

Set the figure size in inches.

Call signatures:

fig.set_size_inches(w, h)  # OR
fig.set_size_inches((w, h))
Parameters:
  • w ((float, float) or float) – Width and height in inches (if height not specified as a separate argument) or width.

  • h (float) – Height in inches.

  • forward (bool, default: True) – If True, the canvas size is automatically updated, e.g., you can resize the figure window from the shell.

See also

matplotlib.figure.Figure.get_size_inches, matplotlib.figure.Figure.set_figwidth, matplotlib.figure.Figure.set_figheight

Notes

To transform from pixels to inches divide by Figure.dpi.

set_sketch_params(scale=None, length=None, randomness=None)

Set the sketch parameters.

Parameters:
  • scale (float, 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.

  • length (float, optional) – The length of the wiggle along the line, in pixels (default 128.0)

  • randomness (float, 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)

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:

snap (bool 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_tight_layout(tight)[source]

[Deprecated] Set whether and how .Figure.tight_layout is called when drawing.

Parameters:

tight (bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None) – If a bool, sets whether to call .Figure.tight_layout upon drawing. If None, use :rc:`figure.autolayout` instead. If a dict, pass it as kwargs to .Figure.tight_layout, overriding the default paddings.

Notes

Deprecated since version 3.6: Use set_layout_engine instead.

set_transform(t)

Set the artist transform.

Parameters:

t (~matplotlib.transforms.Transform)

set_url(url)

Set the url for the artist.

Parameters:

url (str)

set_visible(b)

Set the artist’s visibility.

Parameters:

b (bool)

set_zorder(level)

Set the zorder for the artist. Artists with lower zorder values are drawn first.

Parameters:

level (float)

show(warn=True)[source]

If using a GUI backend with pyplot, display the figure window.

If the figure was not created using ~.pyplot.figure, it will lack a ~.backend_bases.FigureManagerBase, and this method will raise an AttributeError.

Warning

This does not manage an GUI event loop. Consequently, the figure may only be shown briefly or not shown at all if you or your environment are not managing an event loop.

Use cases for .Figure.show include running this from a GUI application (where there is persistently an event loop running) or from a shell, like IPython, that install an input hook to allow the interactive shell to accept input while the figure is also being shown and interactive. Some, but not all, GUI toolkits will register an input hook on import. See cp_integration for more details.

If you’re in a shell without input hook integration or executing a python script, you should use matplotlib.pyplot.show with block=True instead, which takes care of starting and running the event loop for you.

Parameters:

warn (bool, default: True) – If True and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend.

property stale

Whether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.

property sticky_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)
subfigures(nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs)

Add a set of subfigures to this figure or subfigure.

A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See /gallery/subplots_axes_and_figures/subfigures.

Changed in version 3.10: subfigures are now added in row-major order.

Parameters:
  • nrows (int, default: 1) – Number of rows/columns of the subfigure grid.

  • ncols (int, default: 1) – Number of rows/columns of the subfigure grid.

  • squeeze (bool, default: True) – If True, extra dimensions are squeezed out from the returned array of subfigures.

  • wspace (float, default: None) – The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from rcParams if using constrained layout (see ~.ConstrainedLayoutEngine), or zero if not using a layout engine.

  • hspace (float, default: None) – The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from rcParams if using constrained layout (see ~.ConstrainedLayoutEngine), or zero if not using a layout engine.

  • width_ratios (array-like of length *ncols*, optional) – Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width.

  • height_ratios (array-like of length *nrows*, optional) – Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height.

subplot_mosaic(mosaic, *, sharex=False, sharey=False, width_ratios=None, height_ratios=None, empty_sentinel='.', subplot_kw=None, per_subplot_kw=None, gridspec_kw=None)

Build a layout of Axes based on ASCII art or nested lists.

This is a helper function to build complex GridSpec layouts visually.

See mosaic for an example and full API documentation

Parameters:
  • mosaic (list of list of {hashable or nested} or str) –

    A visual layout of how you want your Axes to be arranged labeled as strings. For example

    x = [['A panel', 'A panel', 'edge'],
         ['C panel', '.',       'edge']]
    

    produces 4 Axes:

    • ’A panel’ which is 1 row high and spans the first two columns

    • ’edge’ which is 2 rows high and is on the right edge

    • ’C panel’ which in 1 row and 1 column wide in the bottom left

    • a blank space 1 row and 1 column wide in the bottom center

    Any of the entries in the layout can be a list of lists of the same form to create nested layouts.

    If input is a str, then it can either be a multi-line string of the form

    '''
    AAE
    C.E
    '''
    

    where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ;:

    'AB;CC'
    

    The string notation allows only single character Axes labels and does not support nesting but is very terse.

    The Axes identifiers may be str or a non-iterable hashable object (e.g. tuple s may not be used).

  • sharex (bool, default: False) – If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot’s x- or y-axis will be independent.

  • sharey (bool, default: False) – If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot’s x- or y-axis will be independent.

  • width_ratios (array-like of length *ncols*, optional) – Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width. Equivalent to gridspec_kw={'width_ratios': [...]}. In the case of nested layouts, this argument applies only to the outer layout.

  • height_ratios (array-like of length *nrows*, optional) – Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height. Equivalent to gridspec_kw={'height_ratios': [...]}. In the case of nested layouts, this argument applies only to the outer layout.

  • subplot_kw (dict, optional) – Dictionary with keywords passed to the .Figure.add_subplot call used to create each subplot. These values may be overridden by values in per_subplot_kw.

  • per_subplot_kw (dict, optional) –

    A dictionary mapping the Axes identifiers or tuples of identifiers to a dictionary of keyword arguments to be passed to the .Figure.add_subplot call used to create each subplot. The values in these dictionaries have precedence over the values in subplot_kw.

    If mosaic is a string, and thus all keys are single characters, it is possible to use a single string instead of a tuple as keys; i.e. "AB" is equivalent to ("A", "B").

    Added in version 3.7.

  • gridspec_kw (dict, optional) – Dictionary with keywords passed to the .GridSpec constructor used to create the grid the subplots are placed on. In the case of nested layouts, this argument applies only to the outer layout. For more complex layouts, users should use .Figure.subfigures to create the nesting.

  • empty_sentinel (object, optional) – Entry in the layout to mean “leave this space empty”. Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel.

Returns:

A dictionary mapping the labels to the Axes objects. The order of the Axes is left-to-right and top-to-bottom of their position in the total layout.

Return type:

dict[label, Axes]

subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None)

Add a set of subplots to this figure.

This utility wrapper makes it convenient to create common layouts of subplots in a single call.

Parameters:
  • nrows (int, default: 1) – Number of rows/columns of the subplot grid.

  • ncols (int, default: 1) – Number of rows/columns of the subplot grid.

  • sharex (bool or {'none', 'all', 'row', 'col'}, default: False) –

    Controls sharing of x-axis (sharex) or y-axis (sharey):

    • True or ‘all’: x- or y-axis will be shared among all subplots.

    • False or ‘none’: each subplot x- or y-axis will be independent.

    • ’row’: each subplot row will share an x- or y-axis.

    • ’col’: each subplot column will share an x- or y-axis.

    When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots’ ticklabels on, use ~matplotlib.axes.Axes.tick_params.

    When subplots have a shared axis that has units, calling .Axis.set_units will update each axis with the new units.

    Note that it is not possible to unshare axes.

  • sharey (bool or {'none', 'all', 'row', 'col'}, default: False) –

    Controls sharing of x-axis (sharex) or y-axis (sharey):

    • True or ‘all’: x- or y-axis will be shared among all subplots.

    • False or ‘none’: each subplot x- or y-axis will be independent.

    • ’row’: each subplot row will share an x- or y-axis.

    • ’col’: each subplot column will share an x- or y-axis.

    When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots’ ticklabels on, use ~matplotlib.axes.Axes.tick_params.

    When subplots have a shared axis that has units, calling .Axis.set_units will update each axis with the new units.

    Note that it is not possible to unshare axes.

  • squeeze (bool, default: True) –

    • If True, extra dimensions are squeezed out from the returned array of Axes:

      • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.

      • for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.

      • for NxM, subplots with N>1 and M>1 are returned as a 2D array.

    • If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

  • width_ratios (array-like of length *ncols*, optional) – Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width. Equivalent to gridspec_kw={'width_ratios': [...]}.

  • height_ratios (array-like of length *nrows*, optional) – Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height. Equivalent to gridspec_kw={'height_ratios': [...]}.

  • subplot_kw (dict, optional) – Dict with keywords passed to the .Figure.add_subplot call used to create each subplot.

  • gridspec_kw (dict, optional) – Dict with keywords passed to the ~matplotlib.gridspec.GridSpec constructor used to create the grid the subplots are placed on.

Returns:

Either a single ~matplotlib.axes.Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

Return type:

~.axes.Axes or array of Axes

See also

pyplot.subplots, Figure.add_subplot, pyplot.subplot

Examples

# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create a figure
fig = plt.figure()

# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)

# Share an X-axis with each column of subplots
fig.subplots(2, 2, sharex='col')

# Share a Y-axis with each row of subplots
fig.subplots(2, 2, sharey='row')

# Share both X- and Y-axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

Adjust the subplot layout parameters.

Unset parameters are left unmodified; initial values are given by :rc:`figure.subplot.[name]`.

Parameters:
  • left (float, optional) – The position of the left edge of the subplots, as a fraction of the figure width.

  • right (float, optional) – The position of the right edge of the subplots, as a fraction of the figure width.

  • bottom (float, optional) – The position of the bottom edge of the subplots, as a fraction of the figure height.

  • top (float, optional) – The position of the top edge of the subplots, as a fraction of the figure height.

  • wspace (float, optional) – The width of the padding between subplots, as a fraction of the average Axes width.

  • hspace (float, optional) – The height of the padding between subplots, as a fraction of the average Axes height.

suptitle(t, **kwargs)

Add a centered super title to the figure.

Parameters:
  • t (str) – The super title text.

  • x (float, default: 0.5) – The x location of the text in figure coordinates.

  • y (float, default: 0.98) – The y location of the text in figure coordinates.

  • horizontalalignment ({'center', 'left', 'right'}, default: center) – The horizontal alignment of the text relative to (x, y).

  • ha ({'center', 'left', 'right'}, default: center) – The horizontal alignment of the text relative to (x, y).

  • verticalalignment ({'top', 'center', 'bottom', 'baseline'}, default: top) – The vertical alignment of the text relative to (x, y).

  • va ({'top', 'center', 'bottom', 'baseline'}, default: top) – The vertical alignment of the text relative to (x, y).

  • fontsize (default: :rc:`figure.titlesize`) – The font size of the text. See .Text.set_size for possible values.

  • size (default: :rc:`figure.titlesize`) – The font size of the text. See .Text.set_size for possible values.

  • fontweight (default: :rc:`figure.titleweight`) – The font weight of the text. See .Text.set_weight for possible values.

  • weight (default: :rc:`figure.titleweight`) – The font weight of the text. See .Text.set_weight for possible values.

  • fontproperties (None or dict, optional) – A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the .FontProperties defaults. :rc:`figure.titlesize` and :rc:`figure.titleweight` are ignored in this case.

  • **kwargs – Additional kwargs are matplotlib.text.Text properties.

Returns:

The .Text instance of the super title.

Return type:

text

supxlabel(t, **kwargs)

Add a centered super xlabel to the figure.

Parameters:
  • t (str) – The super xlabel text.

  • x (float, default: 0.5) – The x location of the text in figure coordinates.

  • y (float, default: 0.01) – The y location of the text in figure coordinates.

  • horizontalalignment ({'center', 'left', 'right'}, default: center) – The horizontal alignment of the text relative to (x, y).

  • ha ({'center', 'left', 'right'}, default: center) – The horizontal alignment of the text relative to (x, y).

  • verticalalignment ({'top', 'center', 'bottom', 'baseline'}, default: bottom) – The vertical alignment of the text relative to (x, y).

  • va ({'top', 'center', 'bottom', 'baseline'}, default: bottom) – The vertical alignment of the text relative to (x, y).

  • fontsize (default: :rc:`figure.labelsize`) – The font size of the text. See .Text.set_size for possible values.

  • size (default: :rc:`figure.labelsize`) – The font size of the text. See .Text.set_size for possible values.

  • fontweight (default: :rc:`figure.labelweight`) – The font weight of the text. See .Text.set_weight for possible values.

  • weight (default: :rc:`figure.labelweight`) – The font weight of the text. See .Text.set_weight for possible values.

  • fontproperties (None or dict, optional) – A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the .FontProperties defaults. :rc:`figure.labelsize` and :rc:`figure.labelweight` are ignored in this case.

  • **kwargs – Additional kwargs are matplotlib.text.Text properties.

Returns:

The .Text instance of the super xlabel.

Return type:

text

supylabel(t, **kwargs)

Add a centered super ylabel to the figure.

Parameters:
  • t (str) – The super ylabel text.

  • x (float, default: 0.02) – The x location of the text in figure coordinates.

  • y (float, default: 0.5) – The y location of the text in figure coordinates.

  • horizontalalignment ({'center', 'left', 'right'}, default: left) – The horizontal alignment of the text relative to (x, y).

  • ha ({'center', 'left', 'right'}, default: left) – The horizontal alignment of the text relative to (x, y).

  • verticalalignment ({'top', 'center', 'bottom', 'baseline'}, default: center) – The vertical alignment of the text relative to (x, y).

  • va ({'top', 'center', 'bottom', 'baseline'}, default: center) – The vertical alignment of the text relative to (x, y).

  • fontsize (default: :rc:`figure.labelsize`) – The font size of the text. See .Text.set_size for possible values.

  • size (default: :rc:`figure.labelsize`) – The font size of the text. See .Text.set_size for possible values.

  • fontweight (default: :rc:`figure.labelweight`) – The font weight of the text. See .Text.set_weight for possible values.

  • weight (default: :rc:`figure.labelweight`) – The font weight of the text. See .Text.set_weight for possible values.

  • fontproperties (None or dict, optional) – A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the .FontProperties defaults. :rc:`figure.labelsize` and :rc:`figure.labelweight` are ignored in this case.

  • **kwargs – Additional kwargs are matplotlib.text.Text properties.

Returns:

The .Text instance of the super ylabel.

Return type:

text

text(x, y, s, fontdict=None, **kwargs)

Add text to figure.

Parameters:
  • x (float) – The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.

  • y (float) – The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.

  • s (str) – The text string.

  • fontdict (dict, optional) – A dictionary to override the default text properties. If not given, the defaults are determined by :rc:`font.*`. Properties passed as kwargs override the corresponding ones given in fontdict.

  • **kwargs (~matplotlib.text.Text properties) –

    Other miscellaneous text parameters.

    Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased: bool backgroundcolor: :mpltype:`color` bbox: dict with properties for .patches.FancyBboxPatch clip_box: unknown clip_on: unknown clip_path: unknown color or c: :mpltype:`color` figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fontfamily or family or fontname: {FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’} fontproperties or font or font_properties: .font_manager.FontProperties or str or pathlib.Path fontsize or size: float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’} fontstretch or stretch: {a numeric value in range 0-1000, ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’} fontstyle or style: {‘normal’, ‘italic’, ‘oblique’} fontvariant or variant: {‘normal’, ‘small-caps’} fontweight or weight: {a numeric value in range 0-1000, ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’} gid: str horizontalalignment or ha: {‘left’, ‘center’, ‘right’} in_layout: bool label: object linespacing: float (multiple of font size) math_fontfamily: str mouseover: bool multialignment or ma: {‘left’, ‘right’, ‘center’} parse_math: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable position: (float, float) rasterized: bool rotation: float or {‘vertical’, ‘horizontal’} rotation_mode: {None, ‘default’, ‘anchor’} sketch_params: (scale: float, length: float, randomness: float) snap: bool or None text: object transform: ~matplotlib.transforms.Transform transform_rotates_text: bool url: str usetex: bool, default: :rc:`text.usetex` verticalalignment or va: {‘baseline’, ‘bottom’, ‘center’, ‘center_baseline’, ‘top’} visible: bool wrap: bool x: float y: float zorder: float

Return type:

~.text.Text

See also

Axes.text, pyplot.text

tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None)[source]

Adjust the padding between and around subplots.

To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set a.set_in_layout(False) for that artist.

Parameters:
  • pad (float, default: 1.08) – Padding between the figure edge and the edges of subplots, as a fraction of the font size.

  • h_pad (float, default: *pad*) – Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.

  • w_pad (float, default: *pad*) – Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.

  • rect (tuple (left, bottom, right, top), default: (0, 0, 1, 1)) – A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit.

See also

Figure.set_layout_engine, pyplot.tight_layout

update(props)

Update this artist’s properties from the dict props.

Parameters:

props (dict)

update_from(other)

Copy properties from other to self.

waitforbuttonpress(timeout=-1)[source]

Blocking call to interact with the figure.

Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within timeout seconds. Negative values deactivate timeout.

zorder = 0
class pyorps.utils.plotting.Line2D(xdata, ydata, *, linewidth=None, linestyle=None, color=None, gapcolor=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, markerfacecoloralt='none', fillstyle=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, markevery=None, **kwargs)[source]

Bases: Artist

A line - the line can have both a solid linestyle connecting all the vertices, and a marker at each vertex. Additionally, the drawing of the solid line is influenced by the drawstyle, e.g., one can create “stepped” lines in various styles.

__init__(xdata, ydata, *, linewidth=None, linestyle=None, color=None, gapcolor=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, markerfacecoloralt='none', fillstyle=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, markevery=None, **kwargs)[source]

Create a .Line2D instance with x and y data in sequences of xdata, ydata.

Additional keyword arguments are .Line2D properties:

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased or aa: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor or mec: :mpltype:`color` markeredgewidth or mew: float markerfacecolor or mfc: :mpltype:`color` markerfacecoloralt or mfcalt: :mpltype:`color` markersize or ms: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

See set_linestyle() for a description of the line styles, set_marker() for a description of the markers, and set_drawstyle() for a description of the draw styles.

add_callback(func)

Add a callback function that will be called whenever one of the .Artist’s properties changes.

Parameters:

func (callable) –

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:

The observer id associated with the callback. This id can be used for removing the callback with .remove_callback later.

Return type:

int

See also

remove_callback

property axes

The ~.axes.Axes instance the artist resides in, or None.

contains(mouseevent)[source]

Test whether mouseevent occurred on the line.

An event is deemed to have occurred “on” the line if it is less than self.pickradius (default: 5 points) away from it. Use ~.Line2D.get_pickradius or ~.Line2D.set_pickradius to get or set the pick radius.

Parameters:

mouseevent (~matplotlib.backend_bases.MouseEvent)

Returns:

  • contains (bool) – Whether any values are within the radius.

  • details (dict) – A dictionary {'ind': pointlist}, where pointlist is a list of points of the line that are within the pickradius around the event position.

    TODO: sort returned indices by distance

convert_xunits(x)

Convert x using the unit type of the xaxis.

If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.

convert_yunits(y)

Convert y using the unit type of the yaxis.

If the artist is not 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:

renderer (~matplotlib.backend_bases.RendererBase subclass.)

Notes

This method is overridden in the Artist subclasses.

drawStyleKeys = ['default', 'steps-mid', 'steps-pre', 'steps-post', 'steps']
drawStyles = {'default': '_draw_lines', 'steps': '_draw_steps_pre', 'steps-mid': '_draw_steps_mid', 'steps-post': '_draw_steps_post', 'steps-pre': '_draw_steps_pre'}
property figure

The (Sub)Figure that the artist is on. For more control, use the get_figure method.

fillStyles = ('full', 'left', 'right', 'bottom', 'top', 'none')
filled_markers = ('.', 'o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X')
findobj(match=None, include_self=True)

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_self (bool) – Include self in the list to be checked for a match.

Return type:

list of .Artist

format_cursor_data(data)

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_aa()

Alias for get_antialiased.

get_agg_filter()

Return filter function to be used for agg filter.

get_alpha()

Return the alpha value used for blending - not supported on all backends.

get_animated()

Return whether the artist is animated.

get_antialiased()[source]

Return whether antialiased rendering is used.

get_bbox()[source]

Get the bounding box of this line.

get_c()

Alias for get_color.

get_children()

Return a list of the child .Artists of this .Artist.

get_clip_box()

Return the clipbox.

get_clip_on()

Return whether the artist uses clipping.

get_clip_path()

Return the clip path.

get_color()[source]

Return the line color.

See also ~.Line2D.set_color.

get_cursor_data(event)

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:

event (~matplotlib.backend_bases.MouseEvent)

get_dash_capstyle()[source]

Return the .CapStyle for dashed lines.

See also ~.Line2D.set_dash_capstyle.

get_dash_joinstyle()[source]

Return the .JoinStyle for dashed lines.

See also ~.Line2D.set_dash_joinstyle.

get_data(orig=True)[source]

Return the line data as an (xdata, ydata) pair.

If orig is True, return the original data.

get_drawstyle()[source]

Return the drawstyle.

See also ~.Line2D.set_drawstyle.

get_ds()

Alias for get_drawstyle.

get_figure(root=False)

Return the .Figure or .SubFigure instance the artist belongs to.

Parameters:

root (bool, default False) – If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.

get_fillstyle()[source]

Return the marker fill style.

See also ~.Line2D.set_fillstyle.

get_gapcolor()[source]

Return the line gapcolor.

See also ~.Line2D.set_gapcolor.

get_gid()

Return the group id.

get_in_layout()

Return boolean flag, True if artist is included in layout calculations.

E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

get_label()

Return the label used for this artist in the legend.

get_linestyle()[source]

Return the linestyle.

See also ~.Line2D.set_linestyle.

get_linewidth()[source]

Return the linewidth in points.

See also ~.Line2D.set_linewidth.

get_ls()

Alias for get_linestyle.

get_lw()

Alias for get_linewidth.

get_marker()[source]

Return the line marker.

See also ~.Line2D.set_marker.

get_markeredgecolor()[source]

Return the marker edge color.

See also ~.Line2D.set_markeredgecolor.

get_markeredgewidth()[source]

Return the marker edge width in points.

See also ~.Line2D.set_markeredgewidth.

get_markerfacecolor()[source]

Return the marker face color.

See also ~.Line2D.set_markerfacecolor.

get_markerfacecoloralt()[source]

Return the alternate marker face color.

See also ~.Line2D.set_markerfacecoloralt.

get_markersize()[source]

Return the marker size in points.

See also ~.Line2D.set_markersize.

get_markevery()[source]

Return the markevery setting for marker subsampling.

See also ~.Line2D.set_markevery.

get_mec()

Alias for get_markeredgecolor.

get_mew()

Alias for get_markeredgewidth.

get_mfc()

Alias for get_markerfacecolor.

get_mfcalt()

Alias for get_markerfacecoloralt.

get_mouseover()

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

get_ms()

Alias for get_markersize.

get_path()[source]

Return the ~matplotlib.path.Path associated with this line.

get_path_effects()
get_picker()

Return the picking behavior of the artist.

The possible values are described in .Artist.set_picker.

See also

Artist.set_picker, Artist.pickable, Artist.pick

get_pickradius()[source]

Return the pick radius used for containment tests.

See .contains for more details.

get_rasterized()

Return whether the artist is to be rasterized.

get_sketch_params()

Return the sketch parameters for the artist.

Returns:

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.

Return type:

tuple or None

get_snap()

Return the snap setting.

See .set_snap for details.

get_solid_capstyle()[source]

Return the .CapStyle for solid lines.

See also ~.Line2D.set_solid_capstyle.

get_solid_joinstyle()[source]

Return the .JoinStyle for solid lines.

See also ~.Line2D.set_solid_joinstyle.

get_tightbbox(renderer=None)

Like .Artist.get_window_extent, but includes any clipping.

Parameters:

renderer (~matplotlib.backend_bases.RendererBase subclass, optional) – renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())

Returns:

The enclosing bounding box (in figure pixel coordinates). Returns None if clipping results in no intersection.

Return type:

.Bbox or None

get_transform()

Return the .Transform instance used by this artist.

get_transformed_clip_path_and_affine()

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

get_url()

Return the url.

get_visible()

Return the visibility.

get_window_extent(renderer=None)[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_xdata(orig=True)[source]

Return the xdata.

If orig is True, return the original data, else the processed data.

get_xydata()[source]

Return the xy data as a (N, 2) array.

get_ydata(orig=True)[source]

Return the ydata.

If orig is True, return the original data, else the processed data.

get_zorder()

Return the artist’s zorder.

have_units()

Return whether units are set on any axis.

is_dashed()[source]

Return whether line has a dashed linestyle.

A custom linestyle is assumed to be dashed, we do not inspect the onoffseq directly.

See also ~.Line2D.set_linestyle.

is_transform_set()

Return whether the Artist has an explicitly set transform.

This is True after .set_transform has been called.

lineStyles = {'': '_draw_nothing', ' ': '_draw_nothing', '-': '_draw_solid', '--': '_draw_dashed', '-.': '_draw_dash_dot', ':': '_draw_dotted', 'None': '_draw_nothing'}
markers = {' ': 'nothing', '': 'nothing', '*': 'star', '+': 'plus', ',': 'pixel', '.': 'point', '1': 'tri_down', '2': 'tri_up', '3': 'tri_left', '4': 'tri_right', '8': 'octagon', '<': 'triangle_left', '>': 'triangle_right', 'D': 'diamond', 'H': 'hexagon2', 'None': 'nothing', 'P': 'plus_filled', 'X': 'x_filled', '^': 'triangle_up', '_': 'hline', 'd': 'thin_diamond', 'h': 'hexagon1', 'none': 'nothing', 'o': 'circle', 'p': 'pentagon', 's': 'square', 'v': 'triangle_down', 'x': 'x', '|': 'vline', 0: 'tickleft', 1: 'tickright', 10: 'caretupbase', 11: 'caretdownbase', 2: 'tickup', 3: 'tickdown', 4: 'caretleft', 5: 'caretright', 6: 'caretup', 7: 'caretdown', 8: 'caretleftbase', 9: 'caretrightbase'}
property mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

pchanged()

Call all of the registered callbacks.

This function is triggered internally when a property is changed.

pick(mouseevent)

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

Artist.set_picker, Artist.get_picker, Artist.pickable

pickable()

Return whether the artist is pickable.

See also

Artist.set_picker, Artist.get_picker, Artist.pick

property pickradius

Return the pick radius used for containment tests.

See .contains for more details.

properties()

Return a dictionary of all the properties of the artist.

recache(always=False)[source]
recache_always()[source]
remove()

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 ~.axes.Axes.relim to update the Axes limits if desired.

Note: ~.axes.Axes.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)

Remove a callback based on its observer id.

See also

add_callback

set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, dash_capstyle=<UNSET>, dash_joinstyle=<UNSET>, dashes=<UNSET>, data=<UNSET>, drawstyle=<UNSET>, fillstyle=<UNSET>, gapcolor=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, marker=<UNSET>, markeredgecolor=<UNSET>, markeredgewidth=<UNSET>, markerfacecolor=<UNSET>, markerfacecoloralt=<UNSET>, markersize=<UNSET>, markevery=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, pickradius=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, solid_capstyle=<UNSET>, solid_joinstyle=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, xdata=<UNSET>, ydata=<UNSET>, zorder=<UNSET>)

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool antialiased: bool clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` dash_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} dash_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle: {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’ figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fillstyle: {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’} gapcolor: :mpltype:`color` or None gid: str in_layout: bool label: object linestyle: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth: float marker: marker style string, ~.path.Path or ~.markers.MarkerStyle markeredgecolor: :mpltype:`color` markeredgewidth: float markerfacecolor: :mpltype:`color` markerfacecoloralt: :mpltype:`color` markersize: float markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool] mouseover: bool path_effects: list of .AbstractPathEffect picker: float or callable[[Artist, Event], tuple[bool, dict]] pickradius: float rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} solid_joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} transform: unknown url: str visible: bool xdata: 1D array ydata: 1D array zorder: float

set_aa(b)

Alias for set_antialiased.

set_agg_filter(filter_func)

Set the agg filter.

Parameters:

filter_func (callable) –

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

set_alpha(alpha)

Set the alpha value used for blending - not supported on all backends.

Parameters:

alpha (float or None) – alpha must be within the 0-1 range, inclusive.

set_animated(b)

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 approach is used to speed up animations using blitting.

See also matplotlib.animation and blitting.

Parameters:

b (bool)

set_antialiased(b)[source]

Set whether to use antialiased rendering.

Parameters:

b (bool)

set_c(color)

Alias for set_color.

set_clip_box(clipbox)

Set the artist’s clip .Bbox.

Parameters:

clipbox (~matplotlib.transforms.BboxBase or None) – Will typically be created from a .TransformedBbox. For instance, TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes) is the default clipping for an artist added to an Axes.

set_clip_on(b)

Set whether the artist uses clipping.

When False, artists will be visible outside the Axes which can lead to unexpected results.

Parameters:

b (bool)

set_clip_path(path, transform=None)

Set the artist’s clip path.

Parameters:
  • path (~matplotlib.patches.Patch 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.

  • transform (~matplotlib.transforms.Transform, 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 ~.Artist.set), a tuple (path, transform) is also accepted as a single positional parameter.

set_color(color)[source]

Set the color of the line.

Parameters:

color (:mpltype:`color`)

set_dash_capstyle(s)[source]

How to draw the end caps if the line is ~Line2D.is_dashed.

The default capstyle is :rc:`lines.dash_capstyle`.

Parameters:

s (.CapStyle or {'butt', 'projecting', 'round'})

set_dash_joinstyle(s)[source]

How to join segments of the line if it ~Line2D.is_dashed.

The default joinstyle is :rc:`lines.dash_joinstyle`.

Parameters:

s (.JoinStyle or {'miter', 'round', 'bevel'})

set_dashes(seq)[source]

Set the dash sequence.

The dash sequence is a sequence of floats of even length describing the length of dashes and spaces in points.

For example, (5, 2, 1, 2) describes a sequence of 5 point and 1 point dashes separated by 2 point spaces.

See also ~.Line2D.set_gapcolor, which allows those spaces to be filled with a color.

Parameters:

seq (sequence of floats (on/off ink in points) or (None, None)) – If seq is empty or (None, None), the linestyle will be set to solid.

set_data(*args)[source]

Set the x and y data.

Parameters:

*args ((2, N) array or two 1D arrays)

See also

set_xdata, set_ydata

set_drawstyle(drawstyle)[source]

Set the drawstyle of the plot.

The drawstyle determines how the points are connected.

Parameters:

drawstyle ({'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default') –

For ‘default’, the points are connected with straight lines.

The steps variants connect the points with step-like lines, i.e. horizontal lines with vertical steps. They differ in the location of the step:

  • ’steps-pre’: The step is at the beginning of the line segment, i.e. the line will be at the y-value of point to the right.

  • ’steps-mid’: The step is halfway between the points.

  • ’steps-post: The step is at the end of the line segment, i.e. the line will be at the y-value of the point to the left.

  • ’steps’ is equal to ‘steps-pre’ and is maintained for backward-compatibility.

For examples see /gallery/lines_bars_and_markers/step_demo.

set_ds(drawstyle)

Alias for set_drawstyle.

set_figure(fig)

Set the .Figure or .SubFigure instance the artist belongs to.

Parameters:

fig (~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure)

set_fillstyle(fs)[source]

Set the marker fill style.

Parameters:

fs ({'full', 'left', 'right', 'bottom', 'top', 'none'}) –

Possible values:

  • ’full’: Fill the whole marker with the markerfacecolor.

  • ’left’, ‘right’, ‘bottom’, ‘top’: Fill the marker half at the given side with the markerfacecolor. The other half of the marker is filled with markerfacecoloralt.

  • ’none’: No filling.

For examples see marker_fill_styles.

set_gapcolor(gapcolor)[source]

Set a color to fill the gaps in the dashed line style.

Note

Striped lines are created by drawing two interleaved dashed lines. There can be overlaps between those two, which may result in artifacts when using transparency.

This functionality is experimental and may change.

Parameters:

gapcolor (:mpltype:`color` or None) – The color with which to fill the gaps. If None, the gaps are unfilled.

set_gid(gid)

Set the (group) id for the artist.

Parameters:

gid (str)

set_in_layout(in_layout)

Set if artist is to be included in layout calculations, E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

Parameters:

in_layout (bool)

set_label(s)

Set a label that will be displayed in the legend.

Parameters:

s (object) – s will be converted to a string by calling str.

set_linestyle(ls)[source]

Set the linestyle of the line.

Parameters:

ls ({'-', '--', '-.', ':', '', (offset, on-off-seq), ...}) –

Possible values:

  • A string:

    linestyle

    description

    '-' or 'solid'

    solid line

    '--' or 'dashed'

    dashed line

    '-.' or 'dashdot'

    dash-dotted line

    ':' or 'dotted'

    dotted line

    'none', 'None', ' ', or ''

    draw nothing

  • 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. See also set_dashes().

For examples see /gallery/lines_bars_and_markers/linestyles.

set_linewidth(w)[source]

Set the line width in points.

Parameters:

w (float) – Line width, in points.

set_ls(ls)

Alias for set_linestyle.

set_lw(w)

Alias for set_linewidth.

set_marker(marker)[source]

Set the line marker.

Parameters:

marker (marker style string, ~.path.Path or ~.markers.MarkerStyle) – See ~matplotlib.markers for full description of possible arguments.

set_markeredgecolor(ec)[source]

Set the marker edge color.

Parameters:

ec (:mpltype:`color`)

set_markeredgewidth(ew)[source]

Set the marker edge width in points.

Parameters:

ew (float) – Marker edge width, in points.

set_markerfacecolor(fc)[source]

Set the marker face color.

Parameters:

fc (:mpltype:`color`)

set_markerfacecoloralt(fc)[source]

Set the alternate marker face color.

Parameters:

fc (:mpltype:`color`)

set_markersize(sz)[source]

Set the marker size in points.

Parameters:

sz (float) – Marker size, in points.

set_markevery(every)[source]

Set the markevery property to subsample the plot when using markers.

e.g., if every=5, every 5-th marker will be plotted.

Parameters:

every (None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]) –

Which markers to plot.

  • every=None: every point will be plotted.

  • every=N: every N-th marker will be plotted starting with marker 0.

  • every=(start, N): every N-th marker, starting at index start, will be plotted.

  • every=slice(start, end, N): every N-th marker, starting at index start, up to but not including index end, will be plotted.

  • every=[i, j, m, ...]: only markers at the given indices will be plotted.

  • every=[True, False, True, ...]: only positions that are True will be plotted. The list must have the same length as the data points.

  • every=0.1, (i.e. a float): markers will be spaced at approximately equal visual distances along the line; the distance along the line between markers is determined by multiplying the display-coordinate distance of the Axes bounding-box diagonal by the value of every.

  • every=(0.5, 0.1) (i.e. a length-2 tuple of float): similar to every=0.1 but the first marker will be offset along the line by 0.5 multiplied by the display-coordinate-diagonal-distance along the line.

For examples see /gallery/lines_bars_and_markers/markevery_demo.

Notes

Setting markevery will still only draw markers at actual data points. While the float argument form aims for uniform visual spacing, it has to coerce from the ideal spacing to the nearest available data point. Depending on the number and distribution of data points, the result may still not look evenly spaced.

When using a start offset to specify the first marker, the offset will be from the first data point which may be different from the first the visible data point if the plot is zoomed in.

If zooming in on a plot when using float arguments then the actual data points that have markers will change because the distance between markers is always determined from the display-coordinates axes-bounding-box-diagonal regardless of the actual axes data limits.

set_mec(ec)

Alias for set_markeredgecolor.

set_mew(ew)

Alias for set_markeredgewidth.

set_mfc(fc)

Alias for set_markerfacecolor.

set_mfcalt(fc)

Alias for set_markerfacecoloralt.

set_mouseover(mouseover)

Set whether this artist is queried for custom context information when the mouse cursor moves over it.

Parameters:

mouseover (bool)

See also

get_cursor_data, ToolCursorPosition, NavigationToolbar2

set_ms(sz)

Alias for set_markersize.

set_path_effects(path_effects)

Set the path effects.

Parameters:

path_effects (list of .AbstractPathEffect)

set_picker(p)[source]

Set the event picker details for the line.

Parameters:

p (float or callable[[Artist, Event], tuple[bool, dict]]) – If a float, it is used as the pick radius in points.

set_pickradius(pickradius)[source]

Set the pick radius used for containment tests.

See .contains for more details.

Parameters:

pickradius (float) – Pick radius, in points.

set_rasterized(rasterized)

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 /gallery/misc/rasterization_demo.

Parameters:

rasterized (bool)

set_sketch_params(scale=None, length=None, randomness=None)

Set the sketch parameters.

Parameters:
  • scale (float, 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.

  • length (float, optional) – The length of the wiggle along the line, in pixels (default 128.0)

  • randomness (float, 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)

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:

snap (bool 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_solid_capstyle(s)[source]

How to draw the end caps if the line is solid (not ~Line2D.is_dashed)

The default capstyle is :rc:`lines.solid_capstyle`.

Parameters:

s (.CapStyle or {'butt', 'projecting', 'round'})

set_solid_joinstyle(s)[source]

How to join segments if the line is solid (not ~Line2D.is_dashed).

The default joinstyle is :rc:`lines.solid_joinstyle`.

Parameters:

s (.JoinStyle or {'miter', 'round', 'bevel'})

set_transform(t)[source]

Set the artist transform.

Parameters:

t (~matplotlib.transforms.Transform)

set_url(url)

Set the url for the artist.

Parameters:

url (str)

set_visible(b)

Set the artist’s visibility.

Parameters:

b (bool)

set_xdata(x)[source]

Set the data array for x.

Parameters:

x (1D array)

See also

set_data, set_ydata

set_ydata(y)[source]

Set the data array for y.

Parameters:

y (1D array)

See also

set_data, set_xdata

set_zorder(level)

Set the zorder for the artist. Artists with lower zorder values are drawn first.

Parameters:

level (float)

property stale

Whether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.

property sticky_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)
update(props)

Update this artist’s properties from the dict props.

Parameters:

props (dict)

update_from(other)[source]

Copy properties from other to self.

zorder = 2
class pyorps.utils.plotting.Path(source, target, algorithm, graph_api, path_indices, path_coords, path_geometry, euclidean_distance, runtimes, path_id, search_space_buffer_m, neighborhood, total_length=None, total_cost=None, length_by_category=None, length_by_category_percent=None)[source]

Bases: object

Dataclass representing a path in a raster graph. Used as container for all path metrics and information.

Parameters:
__eq__(other)[source]

Check for equality between two paths.

Return type:

bool

Parameters:

other (Any)

__init__(source, target, algorithm, graph_api, path_indices, path_coords, path_geometry, euclidean_distance, runtimes, path_id, search_space_buffer_m, neighborhood, total_length=None, total_cost=None, length_by_category=None, length_by_category_percent=None)
Parameters:
Return type:

None

__repr__()[source]

Return a detailed string representation of the path.

Return type:

str

__str__()[source]

Return a string representation of the path including the path_id, source and target, as well as the path’s total length and total cost.

Return type:

str

Returns:

A string representation of the path.

algorithm: str
euclidean_distance: float
graph_api: str
length_by_category: Optional[dict[float, float]] = None
length_by_category_percent: Optional[dict[float, float]] = None
neighborhood: str
path_coords: list[Union[tuple[float, float], list[float]]]
path_geometry: LineString
path_id: int
path_indices: Union[list[Union[int, int32, int64, uint32, uint64]], ndarray[int]]
runtimes: dict[str, float]
search_space_buffer_m: float
source: Union[tuple[float, float], list[float]]
target: Union[tuple[float, float], list[float]]
to_geodataframe_dict()[source]

Convert Path object to a dictionary suitable for GeoDataFrame creation.

Return type:

dict

Returns:

dictionary with path data formatted for GeoDataFrame

total_cost: Optional[float] = None
total_length: Optional[float] = None
class pyorps.utils.plotting.PathCollection[source]

Bases: object

Container for Path objects with O(1) retrieval by path ID and O(n) lookup for source and target information. Paths can be added with new id by replacing a Path object with the same ID already existing in th PathCollection.

__eq__(other)[source]

Check if PathCollections are equal. They do not have to be in the same order to be equal!

Return type:

bool

__getitem__(path_id)[source]

Get path by path_id of the Path object from the PathCollection.

__init__()[source]

Create an empty PathCollection for collecting Paths with their IDs in a dictionary.

__iter__()[source]

Iterate through all paths in the PathCollection.

__len__()[source]

Return the number of paths in the PathCollection.

__repr__()[source]

Return a detailed string representation of the path collection.

Return type:

str

__str__()[source]

Return a string representation of the path collection.

Return type:

str

add(path, replace=False)[source]

Add a path to the PathCollection. If the Path’s path_id is None or if replace is False, the path_id of the Path object will set to self._next_id and self._next_id will be incremented. If the Path’s path_id is not None and replace is True, a Path with the same path_id (if present) will be replaced with the new Path object.

Parameters:
  • path (Path) – A Path object which should be added to the PathCollection.

  • replace (bool) – Whether to replace an existing Path object with the same path_id (if present) or not.

Return type:

None

property all

Return all Path objects from the values of the PathCollection’s _paths dictionary as a list.

Returns:

A list of all Path objects in the PathCollection.

get(path_id=None, source=None, target=None)[source]

Retrieve a stored path by ID, or by source AND target.

Parameters:
  • path_id (int) – The ID of the Path object to retrieve (must be None if path should be found by source and target)

  • source (Any) – The source Path object to retrieve (only used if path_id is None and target os set too; neglected otherwise)

  • target (Any) – The target Path object to retrieve (only used if path_id is None and target os set too; neglected otherwise)

Return type:

Optional[Path]

Returns:

The Path object with the specified ID or source/target pair. None if no such path exists.

to_geodataframe_records()[source]

Convert all paths to a list of dictionaries suitable for a GeoDataFrame.

Return type:

list

Returns:

List of dictionaries with path data formatted for a GeoDataFrame

class pyorps.utils.plotting.PathPlotter(paths, raster_handler)[source]

Bases: object

A class for visualizing paths from a PathCollection.

This class provides functionality to plot paths with options to: - Display all paths or individual paths - Show or hide the raster data as background - Customize markers, colors, and other visual elements - Create individual subplots for each path or combine them

Parameters:
__init__(paths, raster_handler)[source]

Initialize the PathPlotter with a path collection and raster handler.

Parameters:
  • paths (PathCollection) – Collection of Path objects to plot

  • raster_handler (RasterHandler) – RasterHandler object containing the raster data

Return type:

None

plot_paths(plot_all=True, subplots=True, subplotsize=(10, 8), source_color='green', target_color='red', path_colors=None, source_marker='o', target_marker='x', path_linewidth=2, show_raster=True, title=None, suptitle=None, path_id=None, reverse_colors=True)[source]

Plot paths with options to display all paths or individual paths.

Parameters:
  • plot_all (bool) – If True, plot all paths. If False, plot only the path with path_id.

  • subplots (bool) – If True and plot_all is True, create subplots for each path.

  • subplotsize (Tuple[int, int]) – Size of each individual subplot in inches. Defaults to (10, 8).

  • source_color (str) – Color for source marker. Defaults to ‘green’.

  • target_color (str) – Color for target marker. Defaults to ‘red’.

  • path_colors (Union[str, List[str], None]) – Colors for paths. If None, uses default colors.

  • source_marker (str) – Marker style for source. Defaults to ‘o’.

  • target_marker (str) – Marker style for target. Defaults to ‘x’.

  • path_linewidth (int) – Line width for paths. Defaults to 2.

  • show_raster (bool) – Whether to show raster data as background. Defaults to True.

  • title (Union[str, List[str], None]) – Subplot title(s). If None, default titles are created.

  • suptitle (Optional[str]) – The subtitle of the entire figure. Defaults to None.

  • path_id (Union[list[int], int, None]) – ID of specific path to plot when plot_all is False.

  • reverse_colors (bool) – Whether to reverse the color scheme (low=dark, high=bright)

Return type:

Union[Axes, List[Axes]]

Returns:

The axes object(s) with the plot. If multiple subplots are created, returns a list.

class pyorps.utils.plotting.RasterHandler(raster_source, source_coords, target_coords, search_space_buffer_m=None, input_crs=None, apply_mask=True, outside_value=None, bands=None)[source]

Bases: object

Class for efficiently working with raster data while preserving geographic transformation information. Can be initialized with either a file path or directly with raster data, CRS, and transform.

Parameters:
__init__(raster_source, source_coords, target_coords, search_space_buffer_m=None, input_crs=None, apply_mask=True, outside_value=None, bands=None)[source]

Initialize a RasterHandler for working with raster data and coordinate transformations.

Creates a window and buffer geometry based on source and target coordinates: - If source and target are single coordinates: creates a line buffer - If source and/or target are lists of coordinates: creates a polygon buffer

Parameters:
  • raster_source (RasterDataset) – Either: - Path to the raster file (str), or - Tuple of (data_array, crs, transform)

  • source_coords (Union[Tuple[float, float], List[Tuple[float, float]]]) – Source point(s) as (x, y) tuple or list of tuples

  • target_coords (Union[Tuple[float, float], List[Tuple[float, float]]]) – Target point(s) as (x, y) tuple or list of tuples

  • search_space_buffer_m (Optional[float]) – Buffer distance in map units (typically meters)

  • input_crs (Optional[str]) – CRS of the input coordinates (e.g., ‘EPSG:4326’). If None, assumes same as raster

  • apply_mask (bool) – If True, apply the buffer mask after loading data

  • outside_value (Optional[Any]) – Value to set for pixels outside the buffer (defaults to max value of the data type)

  • bands (Optional[List[int]]) – List of bands to modify if apply_mask is True (1-based). If None, all bands are modified

apply_geometry_mask(geometry, outside_value=None, bands=None)[source]

Set pixel values outside the given geometry to the specified value.

Parameters:
  • geometry (Polygon) – A shapely geometry object (Polygon)

  • outside_value (Optional[int]) – Value to set for pixels outside the geometry

  • bands (Union[list[int], int, None]) – List of bands to modify (1-based). If None, all bands are modified.

buffer_geometry: Polygon
coords_to_indices(coords)[source]

Convert geographic coordinates to pixel row/column indices within this raster section.

Parameters:

coords (Union[tuple[float, float], list[float], list[Union[tuple[float, float], list[float]]]]) – List of (x, y) coordinate tuples or a single coordinate tuple

Returns:

Array of (row, col) pixel indices

Return type:

numpy.ndarray

data: ndarray
estimate_buffer_width(source_coords, target_coords, min_buffer=200, max_buffer=4000, sample_radius=50)[source]

Estimate an appropriate buffer width for path finding based on terrain characteristics.

Parameters:
Returns:

Estimated optimal buffer width in meters

indices_to_coords(indices)[source]

Convert pixel indices to geographic coordinates.

Parameters:

indices (List[Tuple[int, int]]) – List of (row, col) pixel indices

Returns:

Array of (x, y) coordinates

Return type:

numpy.ndarray

static max_distance_pair(coords1, coords2)[source]

Find the pair of coordinates (one from coords1, one from coords2) with the highest Euclidean distance.

Parameters:
Returns:

A tuple containing the two points with the maximum distance (point1, point2)

raster_dataset: RasterDataset
save_section_as_raster(output_path)[source]

Save the section as a new raster file with proper geo referencing.

Parameters:

output_path (str) – Path for the output raster file

search_space_buffer_m: float
window: Window
window_transform: Affine
class pyorps.utils.plotting.RasterVizData[source]

Bases: object

Container for raster visualization data used for plotting.

__init__()[source]

Initialize empty visualization data containers.

Return type:

None

class pyorps.utils.plotting.Rectangle(xy, width, height, *, angle=0.0, rotation_point='xy', **kwargs)[source]

Bases: Patch

A rectangle defined via an anchor point xy and its width and height.

The rectangle extends from xy[0] to xy[0] + width in x-direction and from xy[1] to xy[1] + height in y-direction.

:                +------------------+
:                |                  |
:              height               |
:                |                  |
:               (xy)---- width -----+

One may picture xy as the bottom left corner, but which corner xy is actually depends on the direction of the axis and the sign of width and height; e.g. xy would be the bottom right corner if the x-axis was inverted or if width was negative.

__init__(xy, width, height, *, angle=0.0, rotation_point='xy', **kwargs)[source]
Parameters:
  • xy ((float, float)) – The anchor point.

  • width (float) – Rectangle width.

  • height (float) – Rectangle height.

  • angle (float, default: 0) – Rotation in degrees anti-clockwise about the rotation point.

  • rotation_point ({'xy', 'center', (number, number)}, default: 'xy') – If 'xy', rotate around the anchor point. If 'center' rotate around the center. If 2-tuple of number, rotate around this coordinate.

  • **kwargs (~matplotlib.patches.Patch properties) – Properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: unknown animated: bool antialiased or aa: bool or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float

add_callback(func)

Add a callback function that will be called whenever one of the .Artist’s properties changes.

Parameters:

func (callable) –

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:

The observer id associated with the callback. This id can be used for removing the callback with .remove_callback later.

Return type:

int

See also

remove_callback

property axes

The ~.axes.Axes instance the artist resides in, or None.

contains(mouseevent, radius=None)

Test whether the mouse event occurred in the patch.

Parameters:
  • mouseevent (~matplotlib.backend_bases.MouseEvent) – Where the user clicked.

  • radius (float, optional) –

    Additional margin on the patch in target coordinates of .Patch.get_transform. See .Path.contains_point for further details.

    If None, the default value depends on the state of the object:

    • If .Artist.get_picker is a number, the default is that value. This is so that picking works as expected.

    • Otherwise if the edge color has a non-zero alpha, the default is half of the linewidth. This is so that all the colored pixels are “in” the patch.

    • Finally, if the edge has 0 alpha, the default is 0. This is so that patches without a stroked edge do not have points outside of the filled region report as “in” due to an invisible edge.

Return type:

(bool, empty dict)

contains_point(point, radius=None)

Return whether the given point is inside the patch.

Parameters:
  • point ((float, float)) – The point (x, y) to check, in target coordinates of .Patch.get_transform(). These are display coordinates for patches that are added to a figure or Axes.

  • radius (float, optional) –

    Additional margin on the patch in target coordinates of .Patch.get_transform. See .Path.contains_point for further details.

    If None, the default value depends on the state of the object:

    • If .Artist.get_picker is a number, the default is that value. This is so that picking works as expected.

    • Otherwise if the edge color has a non-zero alpha, the default is half of the linewidth. This is so that all the colored pixels are “in” the patch.

    • Finally, if the edge has 0 alpha, the default is 0. This is so that patches without a stroked edge do not have points outside of the filled region report as “in” due to an invisible edge.

Return type:

bool

Notes

The proper use of this method depends on the transform of the patch. Isolated patches do not have a transform. In this case, the patch creation coordinates and the point coordinates match. The following example checks that the center of a circle is within the circle

>>> center = 0, 0
>>> c = Circle(center, radius=1)
>>> c.contains_point(center)
True

The convention of checking against the transformed patch stems from the fact that this method is predominantly used to check if display coordinates (e.g. from mouse events) are within the patch. If you want to do the above check with data coordinates, you have to properly transform them first:

>>> center = 0, 0
>>> c = Circle(center, radius=3)
>>> plt.gca().add_patch(c)
>>> transformed_interior_point = c.get_data_transform().transform((0, 2))
>>> c.contains_point(transformed_interior_point)
True
contains_points(points, radius=None)

Return whether the given points are inside the patch.

Parameters:
  • points ((N, 2) array) – The points to check, in target coordinates of self.get_transform(). These are display coordinates for patches that are added to a figure or Axes. Columns contain x and y values.

  • radius (float, optional) –

    Additional margin on the patch in target coordinates of .Patch.get_transform. See .Path.contains_point for further details.

    If None, the default value depends on the state of the object:

    • If .Artist.get_picker is a number, the default is that value. This is so that picking works as expected.

    • Otherwise if the edge color has a non-zero alpha, the default is half of the linewidth. This is so that all the colored pixels are “in” the patch.

    • Finally, if the edge has 0 alpha, the default is 0. This is so that patches without a stroked edge do not have points outside of the filled region report as “in” due to an invisible edge.

Return type:

length-N bool array

Notes

The proper use of this method depends on the transform of the patch. See the notes on .Patch.contains_point.

convert_xunits(x)

Convert x using the unit type of the xaxis.

If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.

convert_yunits(y)

Convert y using the unit type of the yaxis.

If the artist is not contained in an Axes or if the yaxis does not have units, y itself is returned.

draw(renderer)

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:

renderer (~matplotlib.backend_bases.RendererBase subclass.)

Notes

This method is overridden in the Artist subclasses.

property figure

The (Sub)Figure that the artist is on. For more control, use the get_figure method.

property fill

Return whether the patch is filled.

findobj(match=None, include_self=True)

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_self (bool) – Include self in the list to be checked for a match.

Return type:

list of .Artist

format_cursor_data(data)

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_aa()

Alias for get_antialiased.

get_agg_filter()

Return filter function to be used for agg filter.

get_alpha()

Return the alpha value used for blending - not supported on all backends.

get_angle()[source]

Get the rotation angle in degrees.

get_animated()

Return whether the artist is animated.

get_antialiased()

Return whether antialiasing is used for drawing.

get_bbox()[source]

Return the .Bbox.

get_capstyle()

Return the capstyle.

get_center()[source]

Return the centre of the rectangle.

get_children()

Return a list of the child .Artists of this .Artist.

get_clip_box()

Return the clipbox.

get_clip_on()

Return whether the artist uses clipping.

get_clip_path()

Return the clip path.

get_corners()[source]

Return the corners of the rectangle, moving anti-clockwise from (x0, y0).

get_cursor_data(event)

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:

event (~matplotlib.backend_bases.MouseEvent)

get_data_transform()

Return the ~.transforms.Transform mapping data coordinates to physical coordinates.

get_ec()

Alias for get_edgecolor.

get_edgecolor()

Return the edge color.

get_extents()

Return the Patch’s axis-aligned extents as a ~.transforms.Bbox.

get_facecolor()

Return the face color.

get_fc()

Alias for get_facecolor.

get_figure(root=False)

Return the .Figure or .SubFigure instance the artist belongs to.

Parameters:

root (bool, default False) – If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.

get_fill()

Return whether the patch is filled.

get_gid()

Return the group id.

get_hatch()

Return the hatching pattern.

get_hatch_linewidth()

Return the hatch linewidth.

get_height()[source]

Return the height of the rectangle.

get_in_layout()

Return boolean flag, True if artist is included in layout calculations.

E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

get_joinstyle()

Return the joinstyle.

get_label()

Return the label used for this artist in the legend.

get_linestyle()

Return the linestyle.

get_linewidth()

Return the line width in points.

get_ls()

Alias for get_linestyle.

get_lw()

Alias for get_linewidth.

get_mouseover()

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

get_patch_transform()[source]

Return the ~.transforms.Transform instance mapping patch coordinates to data coordinates.

For example, one may define a patch of a circle which represents a radius of 5 by providing coordinates for a unit circle, and a transform which scales the coordinates (the patch coordinate) by 5.

get_path()[source]

Return the vertices of the rectangle.

get_path_effects()
get_picker()

Return the picking behavior of the artist.

The possible values are described in .Artist.set_picker.

See also

Artist.set_picker, Artist.pickable, Artist.pick

get_rasterized()

Return whether the artist is to be rasterized.

get_sketch_params()

Return the sketch parameters for the artist.

Returns:

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.

Return type:

tuple or None

get_snap()

Return the snap setting.

See .set_snap for details.

get_tightbbox(renderer=None)

Like .Artist.get_window_extent, but includes any clipping.

Parameters:

renderer (~matplotlib.backend_bases.RendererBase subclass, optional) – renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())

Returns:

The enclosing bounding box (in figure pixel coordinates). Returns None if clipping results in no intersection.

Return type:

.Bbox or None

get_transform()

Return the ~.transforms.Transform applied to the Patch.

get_transformed_clip_path_and_affine()

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

get_url()

Return the url.

get_verts()

Return a copy of the vertices used in this patch.

If the patch contains Bézier curves, the curves will be interpolated by line segments. To access the curves as curves, use get_path.

get_visible()

Return the visibility.

get_width()[source]

Return the width of the rectangle.

get_window_extent(renderer=None)

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_x()[source]

Return the left coordinate of the rectangle.

get_xy()[source]

Return the left and bottom coords of the rectangle as a tuple.

get_y()[source]

Return the bottom coordinate of the rectangle.

get_zorder()

Return the artist’s zorder.

have_units()

Return whether units are set on any axis.

is_transform_set()

Return whether the Artist has an explicitly set transform.

This is True after .set_transform has been called.

property mouseover

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

pchanged()

Call all of the registered callbacks.

This function is triggered internally when a property is changed.

pick(mouseevent)

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

Artist.set_picker, Artist.get_picker, Artist.pickable

pickable()

Return whether the artist is pickable.

See also

Artist.set_picker, Artist.get_picker, Artist.pick

properties()

Return a dictionary of all the properties of the artist.

remove()

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 ~.axes.Axes.relim to update the Axes limits if desired.

Note: ~.axes.Axes.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)

Remove a callback based on its observer id.

See also

add_callback

property rotation_point

The rotation point of the patch.

set(*, agg_filter=<UNSET>, alpha=<UNSET>, angle=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, bounds=<UNSET>, capstyle=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, fill=<UNSET>, gid=<UNSET>, hatch=<UNSET>, hatch_linewidth=<UNSET>, height=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, x=<UNSET>, xy=<UNSET>, y=<UNSET>, zorder=<UNSET>)

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None angle: unknown animated: bool antialiased or aa: bool or None bounds: (left, bottom, width, height) capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown height: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool width: unknown x: unknown xy: (float, float) y: unknown zorder: float

set_aa(aa)

Alias for set_antialiased.

set_agg_filter(filter_func)

Set the agg filter.

Parameters:

filter_func (callable) –

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

set_alpha(alpha)

Set the alpha value used for blending - not supported on all backends.

Parameters:

alpha (float or None) – alpha must be within the 0-1 range, inclusive.

set_angle(angle)[source]

Set the rotation angle in degrees.

The rotation is performed anti-clockwise around xy.

set_animated(b)

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 approach is used to speed up animations using blitting.

See also matplotlib.animation and blitting.

Parameters:

b (bool)

set_antialiased(aa)

Set whether to use antialiased rendering.

Parameters:

aa (bool or None)

set_bounds(*args)[source]

Set the bounds of the rectangle as left, bottom, width, height.

The values may be passed as separate parameters or as a tuple:

set_bounds(left, bottom, width, height)
set_bounds((left, bottom, width, height))
set_capstyle(s)

Set the .CapStyle.

The default capstyle is ‘round’ for .FancyArrowPatch and ‘butt’ for all other patches.

Parameters:

s (.CapStyle or {'butt', 'projecting', 'round'})

set_clip_box(clipbox)

Set the artist’s clip .Bbox.

Parameters:

clipbox (~matplotlib.transforms.BboxBase or None) – Will typically be created from a .TransformedBbox. For instance, TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes) is the default clipping for an artist added to an Axes.

set_clip_on(b)

Set whether the artist uses clipping.

When False, artists will be visible outside the Axes which can lead to unexpected results.

Parameters:

b (bool)

set_clip_path(path, transform=None)

Set the artist’s clip path.

Parameters:
  • path (~matplotlib.patches.Patch 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.

  • transform (~matplotlib.transforms.Transform, 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 ~.Artist.set), a tuple (path, transform) is also accepted as a single positional parameter.

set_color(c)

Set both the edgecolor and the facecolor.

Parameters:

c (:mpltype:`color`)

See also

Patch.set_facecolor, Patch.set_edgecolor

set_ec(color)

Alias for set_edgecolor.

set_edgecolor(color)

Set the patch edge color.

Parameters:

color (:mpltype:`color` or None)

set_facecolor(color)

Set the patch face color.

Parameters:

color (:mpltype:`color` or None)

set_fc(color)

Alias for set_facecolor.

set_figure(fig)

Set the .Figure or .SubFigure instance the artist belongs to.

Parameters:

fig (~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure)

set_fill(b)

Set whether to fill the patch.

Parameters:

b (bool)

set_gid(gid)

Set the (group) id for the artist.

Parameters:

gid (str)

set_hatch(hatch)

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.

Parameters:

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

set_hatch_linewidth(lw)

Set the hatch linewidth.

set_height(h)[source]

Set the height of the rectangle.

set_in_layout(in_layout)

Set if artist is to be included in layout calculations, E.g. constrainedlayout_guide, .Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

Parameters:

in_layout (bool)

set_joinstyle(s)

Set the .JoinStyle.

The default joinstyle is ‘round’ for .FancyArrowPatch and ‘miter’ for all other patches.

Parameters:

s (.JoinStyle or {'miter', 'round', 'bevel'})

set_label(s)

Set a label that will be displayed in the legend.

Parameters:

s (object) – s will be converted to a string by calling str.

set_linestyle(ls)

Set the patch linestyle.

linestyle

description

'-' or 'solid'

solid line

'--' or 'dashed'

dashed line

'-.' or 'dashdot'

dash-dotted line

':' or 'dotted'

dotted line

'none', 'None', ' ', or ''

draw nothing

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:

ls ({'-', '--', '-.', ':', '', (offset, on-off-seq), ...}) – The line style.

set_linewidth(w)

Set the patch linewidth in points.

Parameters:

w (float or None)

set_ls(ls)

Alias for set_linestyle.

set_lw(w)

Alias for set_linewidth.

set_mouseover(mouseover)

Set whether this artist is queried for custom context information when the mouse cursor moves over it.

Parameters:

mouseover (bool)

See also

get_cursor_data, ToolCursorPosition, NavigationToolbar2

set_path_effects(path_effects)

Set the path effects.

Parameters:

path_effects (list of .AbstractPathEffect)

set_picker(picker)

Define the picking behavior of the artist.

Parameters:

picker (None 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_rasterized(rasterized)

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 /gallery/misc/rasterization_demo.

Parameters:

rasterized (bool)

set_sketch_params(scale=None, length=None, randomness=None)

Set the sketch parameters.

Parameters:
  • scale (float, 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.

  • length (float, optional) – The length of the wiggle along the line, in pixels (default 128.0)

  • randomness (float, 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)

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:

snap (bool 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)

Set the artist transform.

Parameters:

t (~matplotlib.transforms.Transform)

set_url(url)

Set the url for the artist.

Parameters:

url (str)

set_visible(b)

Set the artist’s visibility.

Parameters:

b (bool)

set_width(w)[source]

Set the width of the rectangle.

set_x(x)[source]

Set the left coordinate of the rectangle.

set_xy(xy)[source]

Set the left and bottom coordinates of the rectangle.

Parameters:

xy ((float, float))

set_y(y)[source]

Set the bottom coordinate of the rectangle.

set_zorder(level)

Set the zorder for the artist. Artists with lower zorder values are drawn first.

Parameters:

level (float)

property stale

Whether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.

property sticky_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)
update(props)

Update this artist’s properties from the dict props.

Parameters:

props (dict)

update_from(other)

Copy properties from other to self.

property xy

Return the left and bottom coords of the rectangle as a tuple.

zorder = 1
pyorps.utils.plotting.window_bounds(window, transform, height=0, width=0)

Get the spatial bounds of a window.

Parameters:
  • window (Window) – The input window.

  • transform (Affine) – an affine transform matrix.

Returns:

left, bottom, right, top – A tuple of spatial coordinate bounding values.

Return type:

float

pyorps.utils.traversal module

PYORPS: An Open-Source Tool for Automated Power Line Routing

Reference: [1] Hofmann, M., Stetz, T., Kammer, F., Repo, S.: ‘PYORPS: An Open-Source Tool for

Automated Power Line Routing’, CIRED 2025 - 28th Conference and Exhibition on Electricity Distribution, 16 - 19 June 2025, Geneva, Switzerland

pyorps.utils.traversal.calculate_path_metrics_numba(raster, path_indices)[source]

Calculate comprehensive metrics for a power line path.

This function analyzes an optimal path found by the routing algorithm to provide detailed statistics about path length, terrain traversed, and cost distribution. This information is essential for power line planning and cost estimation.

Parameters:
  • raster (np.ndarray) – 2D cost raster representing terrain/construction costs

  • path_indices (np.ndarray) – Array of linear indices representing the path

Returns:

Total length, categories, lengths

Return type:

Tuple[float, np.ndarray, np.ndarray]

References

[1]

pyorps.utils.traversal.calculate_region_bounds(dr, dc, rows, cols)[source]

Calculate valid region bounds for source and target areas in graph construction.

This function determines the valid coordinate ranges for source and target nodes when creating edges with the given step direction, ensuring all coordinates remain within grid boundaries.

Parameters:
  • dr (int) – Row step direction

  • dc (int) – Column step direction

  • rows (int) – Total number of rows in the grid

  • cols (int) – Total number of columns in the grid

Returns:

Array containing bounds for source and target regions

Return type:

np.ndarray

References

[1]

pyorps.utils.traversal.calculate_segment_length(abs_dr, abs_dc)[source]

Calculate the geometric length of a path segment between grid cells.

This function provides optimized calculations for common step patterns and falls back to the Pythagorean theorem for arbitrary steps.

Parameters:
  • abs_dr (int) – Absolute row difference

  • abs_dc (int) – Absolute column difference

Returns:

Euclidean length of the segment

Return type:

float

pyorps.utils.traversal.construct_edges(raster, steps, ignore_max=True)[source]

Construct graph edges from rasterized geodata using specified neighborhood steps.

This is the main function for converting rasterized cost data into a weighted graph representation suitable for least-cost path analysis. It processes each step direction in the neighborhood to create edges between valid grid cells.

Parameters:
  • raster (np.ndarray) – 2D cost raster representing terrain/construction costs

  • steps (np.ndarray) – Array of neighborhood step directions (Rk neighborhood)

  • ignore_max (bool) – If True, treats maximum cost values as forbidden areas

Returns:

Complete edge list for graph

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray]

References

[1]

pyorps.utils.traversal.euclidean_distances_numba(raster, target_point)[source]

Calculate Euclidean distances from all points to a target point.

This function is optimized for spatial analysis and can be used for various distance-based calculations in power line routing applications.

Parameters:
  • raster (np.ndarray) – Array of coordinate points

  • target_point (np.ndarray) – Target point coordinates

Returns:

Array of distances from each point to the target

Return type:

np.ndarray

pyorps.utils.traversal.find_valid_nodes(dr, dc, s_rows_start, s_rows_end, s_cols_start, s_cols_end, exclude_mask, raster, intermediates, rows, cols, cost_factor, max_nodes)[source]

Find all valid node transitions for a given step direction within bounds.

This function systematically searches through a defined region to identify all valid edges (node transitions) for a specific step direction, calculating their costs and storing them for graph construction.

Parameters:
  • dr (int) – Row step direction

  • dc (int) – Column step direction

  • s_rows_start (int) – Starting row for source region search

  • s_rows_end (int) – Ending row for source region search

  • s_cols_start (int) – Starting column for source region search

  • s_cols_end (int) – Ending column for source region search

  • exclude_mask (np.ndarray) – Binary mask indicating forbidden areas

  • raster (np.ndarray) – Cost raster with terrain/construction costs

  • intermediates (np.ndarray) – Array of intermediate step coordinates

  • rows (int) – Total number of rows in the grid

  • cols (int) – Total number of columns in the grid

  • cost_factor (float) – Cost normalization factor for this step direction

  • max_nodes (int) – Maximum number of valid nodes to find

Returns:

Edge data and count

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray, int]

References

[1]

pyorps.utils.traversal.get_cost_factor_numba(dr, dc, intermediates_count)[source]

Calculate the cost factor for an edge based on its geometric length.

The cost factor normalizes edge weights by distributing the Euclidean distance over all cells involved in the traversal (source, target, and intermediates).

Parameters:
  • dr (int) – Row difference between source and target

  • dc (int) – Column difference between source and target

  • intermediates_count (int) – Number of intermediate cells traversed

Returns:

Cost factor for edge weight calculation

Return type:

float

References

[1]

pyorps.utils.traversal.get_max_number_of_edges(n, m, steps)[source]

Calculate the maximum number of edges for a given raster shape and neighborhood.

This function estimates the upper bound on the number of edges that will be created when converting a raster into a graph using the specified neighborhood steps. This is used for memory pre-allocation optimization.

Parameters:
  • n (int) – Number of rows in the raster

  • m (int) – Number of columns in the raster

  • steps (np.ndarray) – Array of neighborhood step directions

Returns:

Maximum possible number of edges

Return type:

int

References

[1]

pyorps.utils.traversal.get_outgoing_edges(node_idx, raster, steps, rows, cols, exclude_mask=None)[source]

Get outgoing edges from a specific node for dynamic graph traversal.

This function calculates outgoing edges on-demand rather than pre-computing the entire graph, which can be memory-efficient for large rasters or specialized pathfinding algorithms.

Parameters:
  • node_idx (int) – Linear index of the source node

  • raster (np.ndarray) – 2D cost raster

  • steps (np.ndarray) – Array of neighborhood step directions

  • rows (int) – Number of rows in the raster

  • cols (int) – Number of columns in the raster

  • exclude_mask (Union[np.ndarray, None]) – Optional exclusion mask

Returns:

Target nodes and edge costs

Return type:

Tuple[np.ndarray, np.ndarray]

References

[1]

pyorps.utils.traversal.intermediate_steps_numba(dr, dc)[source]

Calculate intermediate steps for line traversal using Bresenham-like algorithm.

This function determines all intermediate grid cells that a line segment passes through when moving from one grid cell to another. It’s essential for calculating edge weights in the graph representation of rasterized geodata.

Parameters:
  • dr (int) – Row difference (delta row) between source and target

  • dc (int) – Column difference (delta column) between source and target

Returns:

Array of intermediate step coordinates as (row, col) pairs

Return type:

np.ndarray

References

[1]

pyorps.utils.traversal.is_valid_node(sr, sc, tr, tc, exclude_mask, intermediates, raster, rows, cols, out_cost)[source]

Check if a node transition is valid and calculate its traversal cost.

This function validates that a path from source to target coordinates is feasible by checking boundary conditions, exclusion masks, and intermediate cell validity. It also calculates the total cost for traversing this path.

Parameters:
  • sr (int) – Source row coordinate

  • sc (int) – Source column coordinate

  • tr (int) – Target row coordinate

  • tc (int) – Target column coordinate

  • exclude_mask (np.ndarray) – Binary mask indicating forbidden areas

  • intermediates (np.ndarray) – Array of intermediate step coordinates

  • raster (np.ndarray) – Cost raster with terrain/construction costs

  • rows (int) – Total number of rows in the grid

  • cols (int) – Total number of columns in the grid

  • out_cost (np.ndarray) – Output array to store calculated cost

Returns:

True if the node transition is valid, False otherwise

Return type:

bool

References

[1]

pyorps.utils.traversal.ravel_index(row, col, cols)[source]

Convert 2D grid coordinates to 1D linear index.

This is a high-performance replacement for np.ravel_multi_index optimized for regular grid indexing operations in graph construction.

Parameters:
  • row (int) – Row coordinate in the grid

  • col (int) – Column coordinate in the grid

  • cols (int) – Total number of columns in the grid

Returns:

Linear index corresponding to the 2D coordinates

Return type:

int

Module contents

Utility functions for geospatial data processing and visualization.

This module provides: 1. Numba-accelerated traversal functions for path calculation and metrics 2. Helper functions for spatial calculations and operations 3. Utilities for working with raster indices and graph construction 4. Cython-optimized pathfinding algorithms (Dijkstra and Delta-stepping)

pyorps.utils.calculate_path_metrics_numba(raster, path_indices)[source]

Calculate comprehensive metrics for a power line path.

This function analyzes an optimal path found by the routing algorithm to provide detailed statistics about path length, terrain traversed, and cost distribution. This information is essential for power line planning and cost estimation.

Parameters:
  • raster (np.ndarray) – 2D cost raster representing terrain/construction costs

  • path_indices (np.ndarray) – Array of linear indices representing the path

Returns:

Total length, categories, lengths

Return type:

Tuple[float, np.ndarray, np.ndarray]

References

[1]

pyorps.utils.calculate_region_bounds(dr, dc, rows, cols)[source]

Calculate valid region bounds for source and target areas in graph construction.

This function determines the valid coordinate ranges for source and target nodes when creating edges with the given step direction, ensuring all coordinates remain within grid boundaries.

Parameters:
  • dr (int) – Row step direction

  • dc (int) – Column step direction

  • rows (int) – Total number of rows in the grid

  • cols (int) – Total number of columns in the grid

Returns:

Array containing bounds for source and target regions

Return type:

np.ndarray

References

[1]

pyorps.utils.calculate_segment_length(abs_dr, abs_dc)[source]

Calculate the geometric length of a path segment between grid cells.

This function provides optimized calculations for common step patterns and falls back to the Pythagorean theorem for arbitrary steps.

Parameters:
  • abs_dr (int) – Absolute row difference

  • abs_dc (int) – Absolute column difference

Returns:

Euclidean length of the segment

Return type:

float

pyorps.utils.construct_edges(raster, steps, ignore_max=True)[source]

Construct graph edges from rasterized geodata using specified neighborhood steps.

This is the main function for converting rasterized cost data into a weighted graph representation suitable for least-cost path analysis. It processes each step direction in the neighborhood to create edges between valid grid cells.

Parameters:
  • raster (np.ndarray) – 2D cost raster representing terrain/construction costs

  • steps (np.ndarray) – Array of neighborhood step directions (Rk neighborhood)

  • ignore_max (bool) – If True, treats maximum cost values as forbidden areas

Returns:

Complete edge list for graph

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray]

References

[1]

pyorps.utils.create_exclude_mask(*args, **kwargs)
pyorps.utils.delta_stepping_2d(*args, **kwargs)
pyorps.utils.delta_stepping_multiple_sources_multiple_targets(*args, **kwargs)
pyorps.utils.delta_stepping_single_source_multiple_targets(*args, **kwargs)
pyorps.utils.delta_stepping_some_pairs_shortest_paths(*args, **kwargs)
pyorps.utils.dijkstra_2d_cython(*args, **kwargs)
pyorps.utils.dijkstra_multiple_sources_multiple_targets(*args, **kwargs)
pyorps.utils.dijkstra_single_source_multiple_targets(*args, **kwargs)
pyorps.utils.dijkstra_some_pairs_shortest_paths(*args, **kwargs)
pyorps.utils.euclidean_distances_numba(raster, target_point)[source]

Calculate Euclidean distances from all points to a target point.

This function is optimized for spatial analysis and can be used for various distance-based calculations in power line routing applications.

Parameters:
  • raster (np.ndarray) – Array of coordinate points

  • target_point (np.ndarray) – Target point coordinates

Returns:

Array of distances from each point to the target

Return type:

np.ndarray

pyorps.utils.find_valid_nodes(dr, dc, s_rows_start, s_rows_end, s_cols_start, s_cols_end, exclude_mask, raster, intermediates, rows, cols, cost_factor, max_nodes)[source]

Find all valid node transitions for a given step direction within bounds.

This function systematically searches through a defined region to identify all valid edges (node transitions) for a specific step direction, calculating their costs and storing them for graph construction.

Parameters:
  • dr (int) – Row step direction

  • dc (int) – Column step direction

  • s_rows_start (int) – Starting row for source region search

  • s_rows_end (int) – Ending row for source region search

  • s_cols_start (int) – Starting column for source region search

  • s_cols_end (int) – Ending column for source region search

  • exclude_mask (np.ndarray) – Binary mask indicating forbidden areas

  • raster (np.ndarray) – Cost raster with terrain/construction costs

  • intermediates (np.ndarray) – Array of intermediate step coordinates

  • rows (int) – Total number of rows in the grid

  • cols (int) – Total number of columns in the grid

  • cost_factor (float) – Cost normalization factor for this step direction

  • max_nodes (int) – Maximum number of valid nodes to find

Returns:

Edge data and count

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray, int]

References

[1]

pyorps.utils.get_cost_factor_numba(dr, dc, intermediates_count)[source]

Calculate the cost factor for an edge based on its geometric length.

The cost factor normalizes edge weights by distributing the Euclidean distance over all cells involved in the traversal (source, target, and intermediates).

Parameters:
  • dr (int) – Row difference between source and target

  • dc (int) – Column difference between source and target

  • intermediates_count (int) – Number of intermediate cells traversed

Returns:

Cost factor for edge weight calculation

Return type:

float

References

[1]

pyorps.utils.get_max_number_of_edges(n, m, steps)[source]

Calculate the maximum number of edges for a given raster shape and neighborhood.

This function estimates the upper bound on the number of edges that will be created when converting a raster into a graph using the specified neighborhood steps. This is used for memory pre-allocation optimization.

Parameters:
  • n (int) – Number of rows in the raster

  • m (int) – Number of columns in the raster

  • steps (np.ndarray) – Array of neighborhood step directions

Returns:

Maximum possible number of edges

Return type:

int

References

[1]

pyorps.utils.get_outgoing_edges(node_idx, raster, steps, rows, cols, exclude_mask=None)[source]

Get outgoing edges from a specific node for dynamic graph traversal.

This function calculates outgoing edges on-demand rather than pre-computing the entire graph, which can be memory-efficient for large rasters or specialized pathfinding algorithms.

Parameters:
  • node_idx (int) – Linear index of the source node

  • raster (np.ndarray) – 2D cost raster

  • steps (np.ndarray) – Array of neighborhood step directions

  • rows (int) – Number of rows in the raster

  • cols (int) – Number of columns in the raster

  • exclude_mask (Union[np.ndarray, None]) – Optional exclusion mask

Returns:

Target nodes and edge costs

Return type:

Tuple[np.ndarray, np.ndarray]

References

[1]

pyorps.utils.group_by_proximity(*args, **kwargs)
pyorps.utils.intermediate_steps_numba(dr, dc)[source]

Calculate intermediate steps for line traversal using Bresenham-like algorithm.

This function determines all intermediate grid cells that a line segment passes through when moving from one grid cell to another. It’s essential for calculating edge weights in the graph representation of rasterized geodata.

Parameters:
  • dr (int) – Row difference (delta row) between source and target

  • dc (int) – Column difference (delta column) between source and target

Returns:

Array of intermediate step coordinates as (row, col) pairs

Return type:

np.ndarray

References

[1]

pyorps.utils.is_valid_node(sr, sc, tr, tc, exclude_mask, intermediates, raster, rows, cols, out_cost)[source]

Check if a node transition is valid and calculate its traversal cost.

This function validates that a path from source to target coordinates is feasible by checking boundary conditions, exclusion masks, and intermediate cell validity. It also calculates the total cost for traversing this path.

Parameters:
  • sr (int) – Source row coordinate

  • sc (int) – Source column coordinate

  • tr (int) – Target row coordinate

  • tc (int) – Target column coordinate

  • exclude_mask (np.ndarray) – Binary mask indicating forbidden areas

  • intermediates (np.ndarray) – Array of intermediate step coordinates

  • raster (np.ndarray) – Cost raster with terrain/construction costs

  • rows (int) – Total number of rows in the grid

  • cols (int) – Total number of columns in the grid

  • out_cost (np.ndarray) – Output array to store calculated cost

Returns:

True if the node transition is valid, False otherwise

Return type:

bool

References

[1]

pyorps.utils.path_cost(*args, **kwargs)
pyorps.utils.path_cost_f32(*args, **kwargs)
pyorps.utils.ravel_index(row, col, cols)[source]

Convert 2D grid coordinates to 1D linear index.

This is a high-performance replacement for np.ravel_multi_index optimized for regular grid indexing operations in graph construction.

Parameters:
  • row (int) – Row coordinate in the grid

  • col (int) – Column coordinate in the grid

  • cols (int) – Total number of columns in the grid

Returns:

Linear index corresponding to the 2D coordinates

Return type:

int