I have a list objects
which contains numbers. I tried to plot a histogram with this list as shown below.
plt.hist(objects, bins=50, range=[1, 25])
plt.ylabel('Probability')
plt.xlabel('Data')
and this results in the below plot. Why does this plot shuffle numbers on x-axis? (there are 1 numbers between 1 and 2 and the goes between 2 and 3 on x-axis)
Any help would be appreciated! Thanks in advance!
You should check the type
of the elements within objects
: they could be str
and you want them to be int
of float
.
If I use a random generated list of strings with:
objects = [str(n) for n in np.random.randint(0, 50, 1000)]
# ['38', '28', '14', '42', '7', '20', '38', '18', ...
and I try to plot the histogram of this list through the code you provided, I get this plot:
where the x axis is not ordered because matplotlib sees your values as strings, not as numbers.
So you need to convert them to number before plotting, for example with:
objects = [float(n) for n in objects]
# [38.0, 28.0, 14.0, 42.0, 7.0, 20.0, 38.0, 18.0, ...
After the conversion to number type, the histogram looks like this: