ColleenB
ColleenB

Reputation: 175

How can I use a float for the bin size in a histogram plot?

I have a list and I want to make a histogram plot in Python using a bin size of 0.01:

plt.hist(list, bins = 0.01)

I keep getting a type error saying bins can only be an integer, string or an array. Is there anyway to plot a histogram in Python using a float for the binsize?

Upvotes: 2

Views: 5787

Answers (1)

JohanC
JohanC

Reputation: 80509

First off, try not to name your variables with words with a special meaning. A variable with name list prevents using the list command further in the code.

The bins= parameter can be a single number, in which case it is interpreted as the number of bins. So, it needs to be a strictly positive integer. If you want to set a specific bin size, you need to give a complete list of the desired bin edges. The easiest way uses np.arange(start, stop, step).

import matplotlib.pyplot as plt
import numpy as np

mylist = np.random.randn(1000) / 10
plt.hist(mylist, bins=np.arange(min(mylist), max(mylist)+0.01, step=0.01), color='turquoise')

example plot

If the minimum isn't a nice round number, np.arange will follow that pattern. To get "nice" values for the bin edges, you could round the start of np.arange. E.g.:

import matplotlib.pyplot as plt
import numpy as np

mylist = np.random.randn(10, 1000).cumsum(axis=1).ravel() / 500
step = 0.01
start = np.floor(min(mylist) / step) * step
stop = max(mylist) + step
bin_edges = np.arange(start, stop, step=step)
plt.hist(mylist, bins=bin_edges, color='crimson', ec='white')
plt.xticks(bin_edges, rotation=90)
plt.tight_layout()
plt.show()

rounded bin edges

PS: Note that seaborn's sns.histplot supports many more parameters than just matplotlib's plt.hist. sns.histplot has the possibility to choose a binwidth and/or a binrange, but also different types of statistics.

Upvotes: 4

Related Questions