16.9 C
London
Sunday, June 30, 2024
HomePythonMatplotlib in PythonHow to Adjust Bin Size in Matplotlib Histograms

How to Adjust Bin Size in Matplotlib Histograms

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories