## Adjust the bins in a Matplotlib histogram

Python

Matplotlib

Histogram

Change bins

Luc B.

Python

Matplotlib

Histogram

When creating a histogram, the bin widths often need to be tweaked to suit a particular dataset. Sometimes this is as simple as changing the number of uniformly sized bins. Other times, users need to manually specify the bin delineations, either because the bins need to be non-uniform or because the auto-generated bins aren't quite right.

### Code Example

Use the `bins` parameter to `plt.hist()` to change the bin sizes. If `bins` is a scaler, it specifies the number of uniformly sized bins. If it is a list, it specifies the bin edges.

``````import matplotlib.pyplot as plt

values = [1, 1, 2, 3, 8, 7, 5, 4, 1, 3, 2, 4, 5, 8, 9]

# Adjust the number of bins here
plt.hist(values, bins=2, edgecolor="black")

plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()``````

By specifying `plt.hist()` use two uniform bins, the above plot effectively shows the number of values that are greater and less than the mean.

### More Examples

#### Custom Bin Delineations

As mentioned above, the `bins` parameter can also be a list that specifies the bin edges, where the first value is the left edge of the leftmost bin, and the last value is the right edge of the rightmost bin.

``````# Manually specify the bins here
plt.hist(values, bins=[1, 3, 4, 6, 10], edgecolor="black")

plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()``````

This bins in the above plot are `[1, 3), [3, 4), [4, 6), [6, 10)`, where the brackets represent inclusion and the parentheses represent exclusion.