0

I have a histogram that I am plotting from a single array.

SLT=[ 10.6,  10.5,  10.3,   5.3,   5.3,   5. ,   5. ,   9.3,   3. ,
     8.5,   1.1,   6.4,  23.2,   4.4,  21.2,   2.4,   2.3,   2.3,
     2.2,   2.2,   2.1,   2. ,   2. ,   1.9,  13.9,  13.8,  13.8,
    13.7,  13.7,  13.6,  13.6,  13.6,  13.6,  18.8,  11.5,  11.5,
    11.4,  11.4,  11.4,  11.3,  11.2,  11.1,  11. ,  10.9,  10.7,
    10.5,  10.4,  10.4,  10.3,  10.2,  10.1,  22.1,  22. ,  22. ,
    22. ,  21.9,  21.9,  21.8,  21.8,  21.7,  21.7,  21.6,  17. ,
    17. ,  16.9,  17. ,  21.1,  16.1,  16.1,  16.1,  16.1,  16. ,
    15.8,  20.6,  14.2,  19.8,  12.2,  17.5,  12.9,  18.6,  12.6,
    18.4,  13.7,  13.7,  13.6]

I plot a histogram using the following:

fig=plt.figure()
ax=fig.add_subplot(111)
numBins=24
ax.hist(SLT,numBins,color='k',alpha=0.8)
remove_border(left=False,bottom=True)
plt.xlabel('Saturn Local Time')
plt.ylabel('Frequency')
plt.title('Cassini Titan Flybys between 2004 - 2014, Distribution of SLT Frequency')
plt.ylim([0,13])
plt.xlim([1,24])
plt.minorticks_on()
plt.grid(b=True,which='major',color='k',alpha=0.2,linestyle='dotted')
plt.grid(b=False,which='minor',color='k',alpha=0.2,linestyle='dotted')
plt.show()

This yields: https://i.stack.imgur.com/VVdsn.jpg

How can I put a label at the top of each bin which shows the count of that bin? Is there a built in function/workaround or would i need to manually work it out and plot as a textbook for instance?

Many thanks!


Answer involved both suggestions in comments:

Overall code:

fig=plt.figure()
ax=fig.add_subplot(111)
numBins=24
counts,bins,patches=ax.hist(SLT,numBins,color='k',alpha=0.8)
remove_border(left=False,bottom=True)
plt.xlabel('Saturn Local Time')
plt.ylabel('Frequency')
plt.title('Cassini Titan Flybys between 2004 - 2014, Distribution of SLT Frequency')
plt.ylim([0,13])
plt.xlim([1,24])
plt.minorticks_on()
plt.grid(b=True,which='major',color='k',alpha=0.2,linestyle='dotted')
plt.grid(b=False,which='minor',color='k',alpha=0.2,linestyle='dotted')

bin_centers = 0.5 * diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
    # Label the raw counts
    ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -18), textcoords='offset points', va='top', ha='center')


def autolabel(rects):
# attach some text labels
    for ii,rect in enumerate(rects):
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, counts[ii],
                ha='center', va='bottom')

autolabel(patches)
plt.show()
Chuck
  • 3,664
  • 7
  • 42
  • 76

0 Answers0