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

预算饼图生成失败:ValueError非负值错误求助

排查Matplotlib饼图ValueError的原因与解决方法

错误原因

  1. 输入未转数值,字符串拼接导致计算错误:input()函数返回的是字符串类型,直接用+拼接各支出项不是数值相加,而是字符串拼接。比如输入 groceries=100、gas=50,inputted_groceries + inputted_gas会得到"10050",转成float后数值远大于收入,导致total_left变成负数,触发Matplotlib饼图要求所有扇区数值非负的检查。
  2. 饼图数据类型混合:构建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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:48:12