matplotlib.axes.Axes.hist#

Axes.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 usesnumpy.histogram to bin the data inx and count thenumber of values in each bin, then draws the distribution either as aBarContainer orPolygon. Thebins,range,density, andweights parameters are forwarded tonumpy.histogram.

If the data has already been binned and counted, usebar orstairs to plot the distribution:

counts,bins=np.histogram(x)plt.stairs(counts,bins)

Alternatively, plot pre-computed bins and counts usinghist() bytreating each bin as a single point with a weight equal to its count:

plt.hist(bins[:-1],bins,weights=counts)

The data inputx can be a singular array, a list of datasets ofpotentially different lengths ([x0,x1, ...]), or a 2D ndarray inwhich each column is a dataset. Note that the ndarray form istransposed relative to the list form. If the input is an array, thenthe return value is a tuple (n,bins,patches); if the input is asequence 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 ofarrays which are not required to be of the same length.

binsint or sequence or str, default:rcParams["hist.bins"] (default:10)

Ifbins is an integer, it defines the number of equal-width binsin the range.

Ifbins is a sequence, it defines the bin edges, including theleft 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, ifbins is:

[1,2,3,4]

then the first bin is[1,2) (including 1, but excluding 2) andthe second[2,3). The last bin, however, is[3,4], whichincludes 4.

Ifbins is a string, it is one of the binning strategiessupported bynumpy.histogram_bin_edges: 'auto', 'fd', 'doane','scott', 'stone', 'rice', 'sturges', or 'sqrt'.

rangetuple or None, default: None

The lower and upper range of the bins. Lower and upper outliersare ignored. If not provided,range is(x.min(),x.max()).Range has no effect ifbins is a sequence.

Ifbins is a sequence orrange is specified, autoscalingis based on the specified bin range instead of therange of x.

densitybool, default: False

IfTrue, draw and return a probability density: each binwill display the bin's raw count divided by the total number ofcountsand 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).

Ifstacked is alsoTrue, the sum of the histograms isnormalized to 1.

weights(n,) array-like or None, default: None

An array of weights, of the same shape asx. Each value inx only contributes its associated weight towards the bin count(instead of 1). Ifdensity isTrue, the weights arenormalized, so that the integral of the density over the rangeremains 1.

cumulativebool or -1, default: False

IfTrue, then a histogram is computed where each bin gives thecounts in that bin plus all bins for smaller values. The last bingives the total number of datapoints.

Ifdensity is alsoTrue then the histogram is normalized suchthat the last bin equals 1.

Ifcumulative is a number less than 0 (e.g., -1), the directionof accumulation is reversed. In this case, ifdensity is alsoTrue, then the histogram is normalized such that the first binequals 1.

bottomarray-like or float, default: 0

Location of the bottom of each bin, i.e. bins are drawn frombottom tobottom+hist(x,bins) If a scalar, the bottomof each bin is shifted by the same amount. If an array, each binis shifted independently and the length of bottom must match thenumber 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 dataare given the bars are arranged side by side.

  • 'barstacked' is a bar-type histogram where multipledata 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',barh will be used for bar-type histogramsand thebottom kwarg will be the left edges.

rwidthfloat or None, default: None

The relative width of the bars as a fraction of the bin width. IfNone, automatically compute the width.

Ignored ifhisttype is 'step' or 'stepfilled'.

logbool, default: False

IfTrue, the histogram axis will be set to a log scale.

colorcolor or list ofcolor or None, default: None

Color or sequence of colors, one per dataset. Default (None)uses the standard line color sequence.

labelstr or list of str, optional

String, or sequence of strings to match multiple datasets. Barcharts yield multiple patches per dataset, but only the first getsthe label, so thatlegend will work as expected.

stackedbool, default: False

IfTrue, multiple data are stacked on top of each other IfFalse multiple data are arranged side by side if histtype is'bar' or on top of each other if histtype is 'step'

Returns:
narray or list of arrays

The values of the histogram bins. Seedensity andweights for adescription of the possible semantics. If inputx is an array,then this is an array of lengthnbins. If input is a sequence ofarrays[data1,data2,...], then this is a list of arrays withthe values of the histograms for each of the arrays in the sameorder. The dtype of the arrayn (or of its element arrays) willalways be float even if no weighting or normalization is used.

binsarray

The edges of the bins. Length nbins + 1 (nbins left edges and rightedge of last bin). Always a single array even when multiple datasets are passed in.

patchesBarContainer or list of a singlePolygon or list of such objects

Container of individual artists used to create the histogramor list of such containers if there are multiple input datasets.

Other Parameters:
dataindexable object, optional

If given, the following parameters also accept a strings, which isinterpreted asdata[s] ifs is a key indata:

x,weights

**kwargs

Patch properties. The following propertiesadditionally accept a sequence of values corresponding to thedatasets inx:edgecolor,facecolor,linewidth,linestyle,hatch.

Added in version 3.10:Allowing sequences of values in above listed Patch properties.

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 significantlyaccelerated by usingstairs to plot a pre-computed histogram(plt.stairs(*np.histogram(data))), or by settinghisttype to'step' or 'stepfilled' rather than 'bar' or 'barstacked'.

Examples usingmatplotlib.axes.Axes.hist#

Animated histogram

Animated histogram

Align histogram to scatter plot using locatable Axes

Align histogram to scatter plot using locatable Axes

Scatter plot with histograms

Scatter plot with histograms

Building histograms using Rectangles and PolyCollections

Building histograms using Rectangles and PolyCollections

Histograms

Histograms

Bihistogram

Bihistogram

Cumulative distributions

Cumulative distributions

Demo of the histogram function's different histtype settings

Demo of the histogram function's different histtype settings

The histogram (hist) function with multiple data sets

The histogram (hist) function with multiple data sets

Histogram bins, density, and weight

Histogram bins, density, and weight

Bayesian Methods for Hackers style sheet

Bayesian Methods for Hackers style sheet

Axes Demo

Axes Demo

Placing text boxes

Placing text boxes

hist(x)

hist(x)

Artist tutorial

Artist tutorial

Path Tutorial

Path Tutorial

Transformations Tutorial

Transformations Tutorial

Quick start guide

Quick start guide