如何在 matplotlib 中的直方图栏顶部添加百分比值?
How do I add percent values on top of histogram bar in matplotlib?
我只想将百分比值添加到我的 matplotlib 直方图中条形的顶部。这是我到目前为止所拥有的。关于如何做到这一点的任何想法?我知道有类似的帖子,但我只在单杠或 seaborn 地块上看到了东西。谢谢!
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()
恐怕 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()
这将是输出:
供参考
我只想将百分比值添加到我的 matplotlib 直方图中条形的顶部。这是我到目前为止所拥有的。关于如何做到这一点的任何想法?我知道有类似的帖子,但我只在单杠或 seaborn 地块上看到了东西。谢谢!
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()
恐怕 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()
这将是输出:
供参考