3

I have a set of numbers as integers and floating point, I want to plot a histogram from them. For doing so I am using the following code:

import matplotlib.pyplot as plt
from numpy import array
gn=array([1,2,3,728,625,0,736,5243,9.0])
plt.hist(gn)
plt.show()

However, I am ending up getting the following error:

    plt.hist(a)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2827, in hist
    stacked=stacked, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 8312, in hist
    xmin = min(xmin, xi.min())
  File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 21, in _amin
    out=out, keepdims=keepdims)
TypeError: cannot perform reduce with flexible type

I am not getting as to where am I going wrong, can someone please suggest as to how can I plot a histogram of floating point numbers and integers

Jannat Arora
  • 2,759
  • 8
  • 44
  • 70
  • 1
    That is very odd behaviour. As Amy said, if your input list contains a combination of floats and ints then it should be cast to all floats when you create the array. Can you confirm that the exact code above reproduces the error (in your traceback you seem to be using a different variable called `a`)? What version of numpy are you using? What is `gn.dtype`? – ali_m Aug 27 '15 at 21:53
  • One thing that would cause the error you're seeing is if your array actually contained non-numeric data ([see here](http://stackoverflow.com/q/21472243/1461210)) – ali_m Aug 27 '15 at 22:17
  • Now the code works as it is and doesn't show any error. I guess this problem is fixed. – user3503711 Sep 13 '22 at 17:28

1 Answers1

3

Interesting. When I run this, numpy automatically makes the integers floats. Must be a different version. You can change the array from flexible to a float dtype with the astype() method. Try this instead:

import matplotlib.pyplot as plt
from numpy import array
gn=array([1,2,3,728,625,0,736,5243,9.0])
plt.hist(gn.astype('float'))
plt.show()
Amy Teegarden
  • 3,842
  • 20
  • 23