How to Adjust Bin Size in Matplotlib Histograms


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])

In this example we specified that each bin should be the same width, but you can specify boundaries in such a way that each bin is a different size.

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.

Additional Resources

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

How to Increase Plot Size in Matplotlib
How to Create a Density Plot in Matplotlib
How to Plot a Time Series in Matplotlib

Leave a Reply

Your email address will not be published.