Python pandas / matplotlib 在条形图列上方注释标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23591254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:02:14  来源:igfitidea点击:

Python pandas / matplotlib annotating labels above bar chart columns

pythonmatplotlibpandas

提问by ccsv

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

回答by Kamil Sindi

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

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

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

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

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

Vertical Bars

竖条

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

回答by joemar.ct

Capture the axis where the plot is drawn into, then manipulate it as a usual matplotlibobject. Putting the value above the bar will be something like this:

捕获绘图所在的轴,然后将其作为通常的matplotlib对象进行操作。将值放在栏上方将是这样的:

ax = df.plot(kind='bar',  title='Scores')
ax.set_ylim(0, 12)
for i, label in enumerate(list(df.index)):
    score = df.ix[label]['Score']
    ax.annotate(str(score), (i, score + 0.2))