plot_serializer.matplotlib.axesproxy.AxesProxy#

class plot_serializer.matplotlib.axesproxy.AxesProxy(delegate: Axes, figure: Figure, serializer: Serializer)[source]#

Bases: Proxy[Axes]

Methods

bar

Make a bar plot.

boxplot

Serialized parameters: x, notch, whis, bootstrap, usermedians, conf_intervals, tick_labels.

errorbar

Serialized parameters: x, y, xerr, yerr, color, ecolor, marker, label.

hist

Serialized parameters: x, bins, range, cumulative, color, label.

pie

Plot y versus x as lines and/or markers.

plot

Serialized parameters: x, y, linewidth, linestyle, marker, color, label.

scatter

Serialized parameters: x, y, s, c, marker, cmap, norm.

Attributes

delegate

Property that allows access to the delegate object which was given in the constructor.

bar(x: Any, height: Any, **kwargs: Any) BarContainer[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.

Serialized parameters: x, height, color.

boxplot(x: Any, *args: Any, **kwargs: Any) dict[Any, Any][source]#

Serialized parameters: x, notch, whis, bootstrap, usermedians, conf_intervals, tick_labels.

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, default: :rc:`boxplot.vertical`) – If True, draws vertical boxes. If False, draw horizontal boxes.

  • 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.

    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) – DATA_PARAMETER_PLACEHOLDER

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.

property delegate: T#

Property that allows access to the delegate object which was given in the constructor. This is useful when wanting to perform actions or access state from the underlying object.

Returns:

The delegate object

Return type:

T

errorbar(x: Any, y: Any, *args: Any, **kwargs: Any) ErrorbarContainer[source]#

Serialized parameters: x, y, xerr, yerr, color, ecolor, marker, label.

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.

  • 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.

  • 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 (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) – DATA_PARAMETER_PLACEHOLDER

  • **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:

    %(Line2D:kwdoc)s

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

hist(x: Any, *args: Any, **kwargs: Any) Any[source]#

Serialized parameters: x, bins, range, cumulative, color, label.

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, scalar, or None, default: None) – 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 (color or list of 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) – DATA_PARAMETER_PLACEHOLDER

  • **kwargs~matplotlib.patches.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’.

pie(x: Any, **kwargs: Any) Any[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').

Serialized parameters: x, y, color, marker, label.

plot(*args: Any, **kwargs: Any) list[Line2D][source]#

Serialized parameters: x, y, linewidth, linestyle, marker, color, label.

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 scalar) –

    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 scalar) –

    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:

    %(Line2D:kwdoc)s

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').

scatter(x: Any, y: Any, *args: Any, **kwargs: Any) PathCollection[source]#

Serialized parameters: x, y, s, c, marker, cmap, norm.

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 color or 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_doc)s – This parameter is ignored if c is RGB(A).

  • %(norm_doc)s – This parameter is ignored if c is RGB(A).

  • %(vmin_vmax_doc)s – 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 color or list of 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.

  • 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) – DATA_PARAMETER_PLACEHOLDER

  • **kwargs (~matplotlib.collections.Collection properties)

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.