能否将Pandas DataFrame列值设为Matplotlib Y轴标签?报错求助
问题:用DataFrame列值作为Matplotlib Y轴标签触发ValueError
需求是将Pandas DataFrame中UoM (of GR)列的数值作为Matplotlib图表的Y轴标签(标签随计量单位如kg、袋数变化),但运行自定义绘图函数时触发错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
错误原因
报错核心在plt.ylabel(output_df['UoM (of GR)'])这一行:output_df['UoM (of GR)']返回的是Pandas Series对象,而plt.ylabel()要求传入单个字符串/数值。如果过滤后的output_df包含多行,这个Series会有多个值,Matplotlib无法确定用哪个值作为标签,因此抛出歧义错误。
解决方法
结合业务逻辑,同一工厂+物料的计量单位应保持一致,只需提取该列的单个值传入plt.ylabel(),可选方式:
- 取第一行的值:
output_df['UoM (of GR)'].iloc[0] - 取唯一值(确保列值无重复):
output_df['UoM (of GR)'].unique()[0]
同时拆分原函数的冗余返回写法,让代码逻辑更清晰。
修改后的完整代码
# 创建函数:根据工厂和物料筛选数据,绘制计划/实际产量累计图 def filter_df(df, plant: str = "", material: str = ""): # 筛选数据并重置索引(丢弃原索引列) output_df = df.loc[(df['Plant'] == plant) & (df['Material'].str.contains(material))].reset_index(drop=True) # 处理空数据场景,避免后续报错 if output_df.empty: print("未匹配到符合条件的记录") return # 获取统一的计量单位 uom_label = output_df['UoM (of GR)'].iloc[0] # 绘制图表 output_df['Planned_Qty_Cumsum'].plot.area(label='Planned Quantity') output_df['Goods_Receipted_Qty_Cumsum'].plot.line(label='Delivered Quantity') # 设置图表属性 plt.title('Planned and Delivered Quantities') plt.legend() plt.xlabel('Number of Process Orders') plt.ylabel(f'Quantity ({uom_label})') # 优化标签格式,提升可读性 plt.show() # 调用函数 filter_df(df_yield_data_formatted, '*plant*', '*material*')
额外优化说明
- 增加空数据判断,避免筛选不到数据时后续代码崩溃
- 用
drop=True重置索引,避免保留原索引列造成干扰 - Y轴标签优化为
Quantity (UoM)格式,更符合图表阅读习惯
内容的提问来源于stack exchange,提问作者DaveBooth
相关产品推荐
相关产品推荐

