# Histograms in Matplotlib

While drawing a histogram, you will rely on the Axes.hist method. In its simplest use, it takes a single argument x, which is a list / array of values to draw the histogram from. The hist then automatically calculates the bin sizes.
Follow the step-by-step instruction here as well as in your Jupyter Notebook.

### Step 1

Let us start by importing NumPy and generating some normally distributed random numbers to use as a data set.

Code:

import numpy as npnp.random.seed(3982434)x = np.random.randn(500)

### Step 2

Then, plot it with the hist method (do not worry, we’ll investigate the return values soon) after creating the required figure and axes.

Code:

fig, ax = plt.subplots()fig.set_size_inches(7, 9)

Output:

Code:

n, bins, patches = ax.hist(x)fig

Output:

### Step 3

bins is the second argument to the hist method, which is the number of bins to use. Let’s draw the histogram with 20 bins:

Code:

n, bins, patches = ax.hist(x, bins=20)

Output:

### Step 4

Alternatively, we can pass in a list which is the range of each bin instead of passing in a number of bins. For example, we could pass in a list like this.

Code:

n, bins, patches = ax.hist(x, bins=[-3, -2, -1, 0, 2, 3])

Output:

The code created an output with six bins, the first with edges at (-3, -2), the next at (-2, -1), and so on.

### Step 5

Now let’s look at the return values. n is an array containing the number of elements in each bin. In this example, it is:

Output:
array([ 8., 78., 159., 246., 8.])

You can match these numbers to the heights on the chart.

### Step 6

The second element in the tuple is the bins edges, which just matches the bins list that we passed in to the method call.

Output:

array([-3, -2, -1, 0, 2, 3])

However, if you’ve let Matplotlib generate the bins for you, then this is useful to see what it can generate.

### Step 7

Finally, the third element, patches, contains references to the bars that were drawn and allows you to customise them. Try setting a different colour now.

Code:

patches[3].set_facecolor(”orange”)fig

Output:

This gives us an orange fourth bar. Isn’t that fun? Try adding more colours to your histogram!

Histograms also support the standard methods for setting axes labels and titles. Read the full API documentation in the link below to improve your understanding of histograms:

Refer to: API documentation [1]

## References

1. matplotlib.axes.Axes.hist [Document]. Matplotlib; [date unknown]. Available from: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.hist.html