How to Adjust Bin Size in Matplotlib Histograms

In Matplotlib, the bin size of a histogram can be adjusted by changing the “bins” argument within the plt.hist() function. This argument takes an integer or a sequence of integers that represent the number of bins or bin edges in the histogram. The default value is 10, but the bin size can be increased or decreased depending on the data. Additionally, the “range” argument can be used to specify the range of the data to be included in the histogram.


You can use one of the following methods to adjust the bin size of histograms in Matplotlib:

Method 1: Specify Number of Bins

plt.hist(data, bins=6)

Method 2: Specify Bin Boundaries

plt.hist(data, bins=[0, 4, 8, 12, 16, 20])

Method 3: Specify Bin Width

w=2
plt.hist(data, bins=np.arange(min(data), max(data) + w, w))

The following examples show how to use each of these methods in practice.

Example 1: Specify Number of Bins

The following code shows how to specify the number of bins to use in a histogram:

import matplotlib.pyplot as plt

#define data
data = [1, 2, 2, 4, 5, 5, 6, 8, 9, 12, 14, 15, 15, 15, 16, 17, 19]

#create histogram with specific number of bins
plt.hist(data, edgecolor='black', bins=6) 

matplotlib histogram with specific number of bins

Keep in mind that the more bins you specify, the more narrow the bins will be.

Example 2: Specify Bin Boundaries

The following code shows how to specify the actual bin boundaries in a histogram:

import matplotlib.pyplot as plt

#define data
data = [1, 2, 2, 4, 5, 5, 6, 8, 9, 12, 14, 15, 15, 15, 16, 17, 19]

#create histogram with specific bin boundaries
plt.hist(data, edgecolor='black', bins=[0, 4, 8, 12, 16, 20])

Example 3: Specify Bin Width

The following code shows how to specify the bin width in a histogram:

import matplotlib.pyplot as plt
import numpy as np

#define data
data = [1, 2, 2, 4, 5, 5, 6, 8, 9, 12, 14, 15, 15, 15, 16, 17, 19]

#specify bin width to use
w=2

#create histogram with specified bin width
plt.hist(data, edgecolor='black', bins=np.arange(min(data), max(data) + w, w)) 

Keep in mind that the smaller the bin width you specify, the more narrow the bins will be.

The following tutorials explain how to perform other common functions in Matplotlib:

x