python - 如何使用 pyplot.barh() 在每个条上显示条的值

标签 python matplotlib bar-chart

我生成了一个条形图,如何在每个条形上显示条形的值?

当前剧情:

enter image description here

我想得到什么:

enter image description here

我的代码:

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

结果:

enter image description here

y 值 vax.text 的 x 位置和字符串值,方便地,条形图的每个条的度量为 1,所以枚举 i 是 y 位置。

关于python - 如何使用 pyplot.barh() 在每个条上显示条的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30228069/

相关文章:

python - CSV python sort() 仅输出从最低到最高的数字,而不是相反

python,努力绘制 CSV 文件

python-2.7 - 如何使用 matplotlib 颜色条中的偏移表示法更改尾数的位数

wolfram-mathematica - 为什么从 Mathematica 导出的 BarChart 图形有像素化文本?有解决方法吗?

r - 为什么 R 中的 ggplot 条形图上的 y 轴在 0 和 1 之间?

python - 通过 Picasa API 上传图片时如何防止 JPEG 压缩?

python - Anaconda ImportError : libSM. so.6: 无法打开共享对象文件: 没有那个文件或目录

python - 来自 Django 缓存的 TypeError

python-3.x - 我的 matplot 的网格偏离了 -0.5

python - 使用对数轴时如何显示 0 长度条的标签