I have an histogram like this:
Where my data are stored with an append in that way:
(while parsing the file)
{
[...]
a.append(int(number))
#a = [1,1,2,1,1, ]...
}
plt.hist(a, 180)
But as you can see from the image, there are lot of blank areas, so I would like to build a barchart from this data, how can I reorganize them like:
#a = [ 1: 4023, 2: 3043, 3:...]
Where 1 is the "number" and 4023 is an example on how many "hit" of the number 1? From what I have seen in this way I can call:
plt.bar(...)
and creating it, so that I can show only the relevant numbers, with more readability. If there is a simple way to cut white area in the Histo is also welcome.
I would like also to show the top counter of each columns, but I have no idea how to do it.
Assuming you have some numpy array a
full of integers then the code below will produce the bar chart you desire.
It uses np.bincount
to count the number of values, note that it only works for non-negative integers.
Also note that I have adjusted the indices so that the plot centrally rather than to the left (using ind-width/2.
).
import matplotlib.pyplot as plt
import numpy as np
# Generate some random data.
N=300
a = np.random.random_integers(low=0, high=20, size=N)
# Use bincount and nonzero to generate your data in the correct format.
b = np.bincount(a)
ind = np.nonzero(b)[0]
width=0.8
fig, ax = plt.subplots()
ax.bar(ind-width/2., b)
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.