【问题标题】:Adding data labels to a horizontal bar chart in matplotlib [duplicate]在matplotlib中向水平条形图添加数据标签[重复]
【发布时间】:2022-01-16 09:58:45
【问题描述】:

我正在尝试将数据标签添加到水平条形图。数据看起来像这样,

Category = ['Communication',
 'Entertainment',
 'Family Support',
 'Food',
 'Healthcare',
 'House Rent',
 'Lending',
 'Transportation']

Cost = [-3100, -1299, -15000, -9127, -5000, -12000, -1000, -2100]

plt.barh(df['Category'], df['Cost'])

我想在上图中每个条的末尾添加数据标签。请帮忙!

【问题讨论】:

标签: python matplotlib


【解决方案1】:

添加 xlabel 和 ylabel 应该可以解决,

plt.xlabel("Cost")
plt.ylabel("Category")

您可能还想创建数据框:

import pandas as pd
df = {}
df["Category"] = Category
df["Cost"] = Cost
df = pd.DataFrame.from_dict(df)

要添加每个条的数据值,您可以修改代码如下:

# First make a subplot, so that axes is available containing the function bar_label.
fig, ax = plt.subplots()
g=ax.barh(df['Category'], df['Cost'])
ax.set_xlabel("Cost")
ax.set_ylabel("Category")
ax.bar_label(g, label_type="center") # This provides the labelling, this only available at higher version. You can do pip install -U matplotlib
plt.show()

参考:

  1. Axis Label
  2. matplotlib 3.4.2 and above has this

输出:

【讨论】:

  • 您好!谢谢您的答复。但是,我希望将数据标签添加到条形而不是 x 和 y 标签。
  • 您好,我已经更新了答案,因为您现在可以在每个栏中看到数据值。它们还有更多操作,例如填充,您可以从原始文档中参考。
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 2019-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多