我生成了一个条形图,如何在每个条形上显示条形的值?
当前剧情:
我想得到什么:
我的代码:
import os
import numpy as np
import matplotlib.pyplot as plt
x = [u'INFO', u'CUISINE', u'TYPE_OF_PLACE', u'DRINK', u'PLACE', u'MEAL_TIME', u'DISH', u'NEIGHBOURHOOD']
y = [160, 167, 137, 18, 120, 36, 155, 130]
fig, ax = plt.subplots()
width = 0.75 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')
#plt.show()
plt.savefig(os.path.join('test.png'), dpi=300, format='png', bbox_inches='tight') # use format='svg' or 'pdf' for vectorial pictures
最佳答案
更新:现在有一个内置方法!向下滚动几个“matplotlib 3.4.0 中的新功能”的答案。
如果您不能升级那么远,则不需要太多代码。添加:
for i, v in enumerate(y):
ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
结果:
y 值 v
是 ax.text
的 x 位置和字符串值,方便地,条形图的每个条的度量为 1,所以枚举 i
是 y 位置。
关于python - 如何使用 pyplot.barh() 在每个条上显示条的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30228069/