+1 vote
in Programming Languages by (12.4k points)

I am generating a histogram using a set of probabilities, but hist() is giving the following error.

How can I fix it?

>>> probability
{0.3609, 0.4975, 0.3686, 0.3708, 0.3251, 0.4163, 0.4124, 0.3993, 0.4162, 0.34, 0.3941, 0.31308, 0.35575}
>>> plt.hist(probability)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/labs/.local/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2605, in hist
    return gca().hist(
  File "/home/labs/.local/lib/python3.8/site-packages/matplotlib/__init__.py", line 1565, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "/home/labs/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 6619, in hist
    xmin = min(xmin, np.nanmin(xi))
TypeError: '<' not supported between instances of 'set' and 'float'

1 Answer

0 votes
by (22k points)

Your code is giving error because the variable 'probability' is a set. You need to use a list as a parameter to the hist() function. So, just type cast 'set' to 'list' and it will work.

>> import matplotlib.pyplot as plt
>>> probability = {0.3609, 0.4975, 0.3686, 0.3708, 0.3251, 0.4163, 0.4124, 0.3993, 0.4162, 0.34, 0.3941, 0.31308, 0.35575}
>>> plt.hist(list(probability))
(array([2., 1., 2., 2., 2., 3., 0., 0., 0., 1.]), array([0.31308 , 0.331522, 0.349964, 0.368406, 0.386848, 0.40529 ,
       0.423732, 0.442174, 0.460616, 0.479058, 0.4975  ]), <a list of 10 Patch objects>)
>>> plt.show()

The histogram using the above code is as follows:

Histogram example

...