You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib水平条形图末端添加产品到期日期?

在Matplotlib水平条形图的条形末端添加到期日期

直接修改你的代码,通过plt.text()函数可以在每个条形的末端添加到期日期文本,以下是完整的可运行代码:

from datetime import date, timedelta
import matplotlib.pyplot as plt

days_prod = [292, 268, 273, 249, 191, 251]
prods = ['milk', 'butter', 'curd', 'panner', 'cheese', 'yogurt']

eo_inv = [
    str(date.today() + timedelta(days=x-1))
    for x in days_prod
]

# 绘制水平条形图,并获取条形对象
bars = plt.barh(prods, days_prod)

# 遍历每个条形,添加到期日期文本
for bar, date_text in zip(bars, eo_inv):
    # 获取条形的宽度(即剩余天数)和Y轴位置
    width = bar.get_width()
    y_pos = bar.get_y() + bar.get_height() / 2
    # 在条形右侧添加文本,稍微偏移一点避免重叠
    plt.text(width + 2, y_pos, date_text, va='center')

plt.title('Inventory')
plt.xlabel('Days Left')
plt.ylabel('Products')

# 调整X轴范围,确保日期文本不会超出图表
plt.xlim(0, max(days_prod) + 30)

plt.show()

关键步骤说明:

  • 调用plt.barh()时保存返回的条形对象bars,以此获取每个条形的位置和尺寸信息
  • 使用zip()同时遍历条形对象和对应的到期日期列表eo_inv
  • bar.get_width()获取条形的长度(对应X轴的剩余天数),bar.get_y() + bar.get_height()/2计算条形的垂直中心位置,确保文本垂直居中
  • plt.text()的第一个参数是X轴位置,给宽度加2是为了让文本和条形之间留一点空隙,避免重叠
  • 最后调整plt.xlim()扩展X轴的右侧范围,防止日期文本被截断

内容的提问来源于stack exchange,提问作者Jerardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 12:55:27