【问题标题】:Python pandas / matplotlib annotating labels above bar chart columns [duplicate]Python pandas / matplotlib在条形图列上方注释标签[重复]
【发布时间】:2014-06-28 18:23:23
【问题描述】:

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

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

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    不访问 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()))
    

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

    垂直条

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

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

    水平条

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

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

    【讨论】:

    • 嘿卡米尔。我尝试了这个解决方案,并且可以获得图表上的注释。但是,对于我的堆叠条形图,它们的顺序相反。它是一个带有三个堆栈的单条 [10%,30%,60%]。注释为 [60%,30%,10%]。我不明白为什么。你能推荐点什么吗?
    • 关于折线图?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 2014-10-16
      • 2016-10-13
      • 2016-03-10
      相关资源
      最近更新 更多