如何在matplotlib中的直方图栏顶部添加百分比值?

2024-09-24 22:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想将百分比值添加到matplotlib直方图中的条形图顶部。这就是我目前所拥有的。有什么办法吗?我知道也有类似的帖子,但我只看到了单杠或海生图上的东西。谢谢

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


Tags: lenmatplotlibnpplt直方图hist帖子百分比
1条回答
网友
1楼 · 发布于 2024-09-24 22:23:19

恐怕plt.hist不可能,但我会尽力提供尽可能接近您需要的东西-

使用plt.text()将文本放入绘图中

例如:

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()

这将是输出:

enter image description here

及供参考How to display the value of the bar on each bar with pyplot.barh()?

相关问题 更多 >