预算饼图生成失败:ValueError非负值错误求助
排查Matplotlib饼图ValueError的原因与解决方法
错误原因
- 输入未转数值,字符串拼接导致计算错误:
input()函数返回的是字符串类型,直接用+拼接各支出项不是数值相加,而是字符串拼接。比如输入 groceries=100、gas=50,inputted_groceries + inputted_gas会得到"10050",转成float后数值远大于收入,导致total_left变成负数,触发Matplotlib饼图要求所有扇区数值非负的检查。 - 饼图数据类型混合:构建
y数组时,前几个元素还是字符串类型,和后面的total_left(float)混合,numpy数组会统一成字符串类型,饼图无法正确解析,同时负数的存在直接抛出错误。
解决方法
步骤1:将所有输入转为数值类型
把每个input()的结果直接转成float,确保后续计算都是数值运算。
步骤2:修正总支出的计算逻辑
用数值相加替代字符串拼接,得到正确的总支出。
步骤3:添加超支检查(可选)
如果总支出超过收入,total_left会是负数,此时可以提示用户超支,避免饼图报错。
修正后的完整代码
import matplotlib.pyplot as plt import numpy as np # 所有输入直接转为float类型 inputted_payment = float(input("Type in how much money you made this month. Don't type any letters or symbols. Type decimals if needed. ")) inputted_groceries = float(input("Type in how much money you spent on groceries this month. Don't type any letters or symbols. Type decimals if needed. ")) inputted_gas = float(input("Type in how much money you spent on gas this month. Don't type any letters or symbols. Type decimals if needed. ")) inputted_bills = float(input("Type in how much money you spent on bills. Don't type any letters or symbols. Type decimals if needed. ")) inputted_restaurants = float(input("Type in how much money you spent on restaurants. Don't type any letters or symbols, Type decimals if needed. ")) inputted_other_things = float(input("Type in how much money you spent on other things. Don't type any letters or symbols. Type decimals if needed. ")) # 数值相加计算总支出 total_spent = inputted_bills + inputted_other_things + inputted_gas + inputted_groceries + inputted_restaurants total_left = inputted_payment - total_spent # 检查是否超支,避免负数 if total_left < 0: print("Warning: You spent more than you earned this month!") total_left = 0 # 构建全数值类型的饼图数据 y = np.array([inputted_groceries, inputted_gas, inputted_bills, inputted_restaurants, inputted_other_things, total_left]) mylabels = ["Groceries", "Gas", "Bills", "Restaurants", "Other Things", "Money Left"] print('\nTotal Spendings') plt.pie(y, labels=mylabels, autopct='%1.1f%%') # 可选:添加百分比显示 plt.title("Monthly Budget Breakdown") plt.show()
关键修改点说明
- 每个输入都用
float()转换,确保后续计算是数值运算。 - 总支出计算改为数值相加,得到正确的金额。
- 添加超支检查,避免
total_left为负数导致饼图报错。 - 可选添加
autopct参数显示扇区百分比,让饼图更直观。
内容的提问来源于stack exchange,提问作者MiniSkoot32
相关产品推荐
相关产品推荐

