Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib hist() Function

Matplotlib hist() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

hist() Used to draw histograms, dividing data into several intervals (bins) and counting the frequency of data in each interval.

Histograms are a fundamental tool for exploring data distribution (central tendency, dispersion, skewness, etc.).

Function definition

pyplot interface

matplotlib.pyplot.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, **kwargs)

Axes interface

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, **kwargs)

Parameter Description

Parameters Type Description
x array or sequence of arrays Input data; multiple datasets can be passed
bins int or sequence Number of intervals or a sequence of interval boundaries. By default, the 'auto' method is used to select automatically
range tuple Data range (lower, upper); data outside the range is ignored
density bool If True, draw a probability density histogram (the sum of areas is 1) instead of frequencies
weights array-like Weight of each data point
cumulative bool or -1 If True, draw a cumulative histogram; -1 means accumulate from large to small
histtype str Histogram type: 'bar' (default), 'barstacked' (stacked), 'step' (step line), 'stepfilled' (filled step)
align str Bar alignment: 'mid' (centered, default), 'left' (left-aligned), 'right' (right-aligned)
orientation str 'vertical' (vertical, default) or 'horizontal' (horizontal)
rwidth float Relative width of bars, 1.0 means no gaps
log bool If True, the y-axis uses a logarithmic scale
color color or list Bar color
label str or list Legend label
stacked bool Whether to display multiple datasets stacked

hist() returns a tuple of three values:(n, bins, patches). n is the frequency/density of each interval, bins are the interval boundaries, and patches are the drawn bar objects.


Usage examples

Example 1: Basic histogram

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Generate normally distributed random data

np.

random

.

seed

(

42

)

data

=

np.

random

.

randn

(

1000

)

fig

,

ax

=

plt.

subplots

(

layout

=

'constrained'

)

Draw a histogram

n

,

bins

,

patches

=

ax.

hist

(

data

,

bins

=

30

,

                           color

=

'steelblue'

,

edgecolor

=

'white'

)

Highlight the interval containing the maximum value

max_idx

=

np.

argmax

(

n

)

patches

[

max_idx

]

.

set_facecolor

(

'#e74c3c'

)

ax.

set_title

(

'Histogram of Normal Distribution'

)

ax.

set_xlabel

(

'Value'

)

ax.

set_ylabel

(

'Frequency'

)

ax.

axvline

(

x

=

0

,

color

=

'red'

,

linestyle

=

'--'

,

alpha

=

0.7

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

Example 2: Histogram comparing multiple datasets

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

np.

random

.

seed

(

42

)

Three sets of data with different distributions

data1

=

np.

random

.

normal

(

0

,

1

,

1000

)

   

Standard normal

data2

=

np.

random

.

normal

(

2

,

1.5

,

800

)

   

mean=2, standard deviation=1.5

data3

=

np.

random

.

normal

(

1

,

0.5

,

600

)

 

mean=-1, standard deviation=0.5

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

5

)

,

layout

=

'constrained'

)

Compare multiple datasets using transparency and different colors

ax.

hist

(

data1

,

bins

=

30

,

alpha

=

0.6

,

color

=

'steelblue'

,

        label

=

'N(0, 1)'

,

edgecolor

=

'white'

)

ax.

hist

(

data2

,

bins

=

30

,

alpha

=

0.6

,

color

=

'coral'

,

        label

=

'N(2, 1.5)'

,

edgecolor

=

'white'

)

ax.

hist

(

data3

,

bins

=

30

,

alpha

=

0.6

,

color

=

'mediumseagreen'

,

        label

=

'N(-1, 0.5)'

,

edgecolor

=

'white'

)

ax.

set_title

(

'Comparing Multiple Distributions'

)

ax.

set_xlabel

(

'Value'

)

ax.

set_ylabel

(

'Frequency'

)

ax.

legend

(

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

Example 3: Density histogram + fitted curve

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

np.

random

.

seed

(

42

)

data

=

np.

random

.

randn

(

1000

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

5

)

,

layout

=

'constrained'

)

density=True draws probability density (instead of frequency)

ax.

hist

(

data

,

bins

=

30

,

density

=

True

,

alpha

=

0.7

,

        color

=

'steelblue'

,

edgecolor

=

'white'

,

label

=

'Data Histogram'

)

Overlay the theoretical normal distribution curve

from

scipy

import

stats

x

=

np.

linspace

(

4

,

4

,

200

)

pdf

=

stats.

norm

.

pdf

(

x

,

loc

=

0

,

scale

=

1

)

ax.

plot

(

x

,

pdf

,

'r-'

,

linewidth

=

2

,

label

=

'Theoretical N(0,1) PDF'

)

ax.

set_title

(

'Density Histogram with PDF Curve'

)

ax.

set_xlabel

(

'Value'

)

ax.

set_ylabel

(

'Probability Density'

)

ax.

legend

(

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

Example 4: Cumulative histogram

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

np.

random

.

seed

(

42

)

data

=

np.

random

.

randn

(

500

)

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

1

,

2

,

figsize

=

(

10

,

4

)

,

                                layout

=

'constrained'

)

Left: ordinary histogram

ax1.

hist

(

data

,

bins

=

30

,

color

=

'steelblue'

,

edgecolor

=

'white'

)

ax1.

set_title

(

'Standard Histogram'

)

ax1.

set_xlabel

(

'Value'

)

ax1.

set_ylabel

(

'Frequency'

)

Right: cumulative histogram

ax2.

hist

(

data

,

bins

=

30

,

cumulative

=

True

,

color

=

'coral'

,

         edgecolor

=

'white'

)

ax2.

set_title

(

'Cumulative Histogram'

)

ax2.

set_xlabel

(

'Value'

)

ax2.

set_ylabel

(

'Cumulative Frequency'

)

plt.

show

(

)

Example 5: Step histogram

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

np.

random

.

seed

(

42

)

data

=

np.

random

.

exponential

(

scale

=

2

,

size

=

500

)

fig

,

ax

=

plt.

subplots

(

layout

=

'constrained'

)

histtype='stepfilled' draws a filled step histogram

ax.

hist

(

data

,

bins

=

30

,

histtype

=

'stepfilled'

,

        color

=

'#3498db'

,

alpha

=

0.6

,

edgecolor

=

'black'

,

        linewidth

=

1

,

label

=

'Stepfilled'

)

Overlay the step line

ax.

hist

(

data

,

bins

=

30

,

histtype

=

'step'

,

        color

=

'black'

,

linewidth

=

2

,

label

=

'Step outline'

)

ax.

set_title

(

'Step Histogram (histtype)'

)

ax.

set_xlabel

(

'Value'

)

ax.

set_ylabel

(

'Frequency'

)

ax.

legend

(

)

ax.

grid

(

axis

=

'y'

,

alpha

=

0.3

)

plt.

show

(

)

print

(

"runoob: step histogram displayed"

)


Common questions

How to choose the bins parameter?

Too few lose data features, too many introduce noise.

Rule of thumb:sqrt(n)(square root rule),log2(n)+1(Sturges' rule), or directly use the default 'auto' to select automatically.

What does density=True mean?

Instead of returning frequencies (count), it makes the total area of the histogram equal to 1, forming an estimate of the probability density. Suitable for comparison with a probability density function (PDF).

Matplotlib Reference Documentation Matplotlib Reference Documentation