Python pandas/matplotlib 在条形图列上方注释标签 [英] Python pandas / matplotlib annotating labels above bar chart columns

查看:45
本文介绍了Python pandas/matplotlib 在条形图列上方注释标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此处添加值的标签以显示在条形图中的条形上方:

How do I add the label for the value to display above the bars in the bargraph here:

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'Users': [ 'Bob', 'Jim', 'Ted', 'Jesus', 'James'],
                 'Score': [10,2,5,6,7],})

df = df.set_index('Users')
df.plot(kind='bar',  title='Scores')

plt.show()

推荐答案

不访问 DataFrame 的解决方案是使用 patch 属性:

A solution without accessing the DataFrame is to use the patches attribute:

ax = df.plot.bar(title="Scores")
for p in ax.patches:
    ax.annotate(str(p.get_height()), xy=(p.get_x(), p.get_height()))

请注意,您必须使用 xy kwarg(第二个参数)才能获得所需的标签位置.

Note you have to play around with the xy kwarg (2nd arg) to get the label position you desire.

我发现这种格式总体来说是最好的:

I found this formatting to be the best in general:

ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

单杠

我发现以下格式适用于水平条:

Horizontal Bars

I found the following format to work well with horizontal bars:

ax.annotate("%.2f" % p.get_width(), (p.get_x() + p.get_width(), p.get_y()), xytext=(5, 10), textcoords='offset points')

这篇关于Python pandas/matplotlib 在条形图列上方注释标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆