如何在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
相关产品推荐
相关产品推荐

