plotlp.StyledAxes module

class plotlp.StyledAxes(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: Axes

bar(*args, **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.

equiscale()[source]
grid_major = {'alpha': 1, 'linestyle': '-'}
grid_minor = {'alpha': 0.5, 'linestyle': '--'}
grids()[source]
implot(img, x, y, w, h, zorder=3, **kwargs)[source]
imscale()[source]
imshow(X, *args, barname=None, coordinates=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.

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: [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

name = 'styled'
noborders()[source]
pcolormesh(*args, cmap=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.

polish()[source]
polish_axis = True
property polish_equiscale
property polish_grids
property polish_imscale
property polish_noborders
scalebar(*args, **kwargs)[source]
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: unknown 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_facecolor(*args, **kwargs)[source]

Set the facecolor of the Axes.

Parameters:

color (:mpltype:`color`)

property style