Divs
Divs

Reputation: 137

How do I add percent values on top of histogram bar in matplotlib?

i just want to add the percent values to the tops of the bars in my matplotlib histogram. This is what I have so far. Any ideas on how to do this? I know there are similar posts, but I only saw stuff on horizontal bars or seaborn plots. Thanks!

x = [2.5, 10.4, 0.5, 1.2, 4.6, 3.6, 0.8, 2.5, 2.9, 1.6, 9.4, 4.9, 2.6, 4.2, 3.9]
myplot = plt.hist(x, bins = [0,1,2,3,10],weights=np.ones(len(x)) / len(x))
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
total = float(len(x))
plt.show()

enter image description here

Upvotes: 1

Views: 3126

Answers (1)

Yoel Nisanov
Yoel Nisanov

Reputation: 1054

I'm afraid it's not possible for plt.hist but I'll try to still provide something that is as close as can be to what you need-

Using plt.text() to put text inside the plot.

Example:

x = [2.5, 10.4, 0.5, 1.2, 4.6, 3.6, 0.8, 2.5, 2.9, 1.6, 9.4, 4.9, 2.6, 4.2, 3.9]
N = len(x)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,x,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(x):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

This will be the output:

enter image description here

and for reference How to display the value of the bar on each bar with pyplot.barh()?

Upvotes: 2

Related Questions