【问题标题】:Matplotlib - Add value label on bar chart from column in dataframeMatplotlib - 从数据框中的列在条形图上添加值标签
【发布时间】:2021-05-11 11:54:19
【问题描述】:

我有以下 df (test2):

    Department                    Assignment Status     Overdue      Percentage
2   Business Services             Overdue               393          2.05
5   Operations                    Overdue               4651         3.67
8   Quality Assurance             Overdue               650          2.16
11  Quality Control               Overdue               1046         2.43
14  R&D Operations                Overdue               1645         2.53

我想创建一个条形图,X 轴为“部门”,Y 轴为“逾期”,每列上的标签为“百分比”。

我编写了下面的代码,生成了以下图表:

x=test2['Department']
y=test2['Overdue']
z=test2['Percentage']

my_colors = 'rgbkymc'

figx = plt.figure(figsize=(10,5))
plt.bar(x, y, color=my_colors)
figx.suptitle('Overdue Training Assignments by Department', fontsize=20)
plt.xlabel('Department', fontsize=14)
plt.ylabel('Overdue Count', fontsize=14)

for index, value in enumerate(z):
    plt.text(value, index, str(value));

如您所见,百分比值与每个条不对齐。请问有人可以告诉我哪里出错了吗?

提前致谢

【问题讨论】:

  • these answers帮忙?
  • 您好 Assile,感谢您的回复。我之前看过这篇文章并尝试了大约 30 分钟来适应我的示例,但无法使其工作。我收到消息“BarContainer”对象没有属性“文本”。
  • 啊,这是因为在示例中他们使用了不同的方式来生成情节。从documentation 看来,您已经颠倒了 x 和 y,也许这会有所帮助?

标签: python pandas matplotlib label


【解决方案1】:

啊,我想我现在明白了。正确的用法是:

plt.text(x, y, s)

您的x 是索引,y 是相应的“过期”值(加上偏移量以确保它显示在条形上方),然后您的s 已经正常。

所以结果会是这样的:

for index, value in enumerate(z):
    plt.text(index, y[index] + offset, str(value))

【讨论】:

  • 感谢它的工作!修改为:for index, value in enumerate(z): plt.text(index, 20, str(value));
猜你喜欢
  • 2015-05-09
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多