python - Matplotlib 水平条形图向条形添加值
问题描述
使用以下代码:
mixedgenres.sort_values(by = "rating").plot(kind = "barh", color = "steelblue", legend = False, grid = True)
for i, v in enumerate(mixedgenres.rating):
plt.text(v + 1, i - 0.25, str(round(v, 2)), color='steelblue')
如何在图形框架内包含值并左对齐,以便它们在一行中很好地放置在彼此下方?
以下是帮助弄清楚的示例数据:
sampledata = {'genre': ["Drama", "Western", "Horror", "Family", "Music", "Comedy", "Crime", "War"],
'rating': [7, 7.6, 8, 8.1, 7.8, 6.9, 7.5, 7.7]}
test = pd.DataFrame(sampledata, index = sampledata["genre"])
test
绘制样本数据
test.sort_values(by = "rating").plot(kind = "barh", color = "steelblue", legend = False, grid = True)
for i, v in enumerate(test.rating):
plt.text(v + 1, i - 0.25, str(round(v, 2)), color='steelblue')
结果
解决方案
这是完整的工作解决方案(跳过导入)。两件事情:
- 您使用未排序的评级值进行标记和
- 您在水平方向上添加了太多的偏移量/偏移量。
编辑:@ImportanceOfBeingErnest 建议的文本垂直对齐
fig = plt.figure()
ax = fig.add_subplot(111)
sampledata = {'genre': ["Drama", "Western", "Horror", "Family", "Music", "Comedy", "Crime", "War"],
'rating': [7, 7.6, 8, 8.1, 7.8, 6.9, 7.5, 7.7]}
test = pd.DataFrame(sampledata, index=sampledata['genre'])
test.sort_values(by = "rating").plot(kind = "barh", color = "steelblue", legend = False, grid = True, ax = ax)
plt.xlim(0, 8.9)
for i, v in enumerate(sorted(test.rating)):
plt.text(v+0.2, i, str(round(v, 2)), color='steelblue', va="center")
推荐阅读
- angular - RxJS switchMap 操作符不取消http请求
- c# - 将十进制格式化为长度为 9 的字符串,在 '.' 之前有 2 位数字(0 填充)和 6 之后
- git - 开发/主控的 git push 失败
- java - 等待任何完成的可调用返回值,只要它在可调用列表中完成
- reactjs - 元素类型无效,反应
- python - 使用熊猫数据框上的名称将图像从一个文件夹复制到另一个文件夹
- php - Doctrine JOIN ... ON ... 在注释中
- sql-server - 根据其他列的数据更新表别名的列数据
- subdomain - 为 virtuoso 安装创建子域
- javascript - Discord.JS v12 - 通过 ID 查找用户并踢他们