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

使用Matplotlib绘图遇TypeError:无法将数值解析为数据类型

错误原因分析与修复方案

核心问题

你在创建NumPy数组y时犯了语法错误:

y = np.array([gp[0], gp[1]], gp23)

np.array()的第二个参数是用来指定数组数据类型(dtype)的,你把2023年预测价格gp23直接作为第二个参数传入,NumPy会尝试把这个数值解析成合法的数据类型,自然触发TypeError。这个错误和gp23的类型(int/float)无关,所以转int也解决不了问题。

修复代码

把三个价格值放在同一个列表里,作为np.array()的第一个参数传入即可:

# 修正后的y数组创建代码
y = np.array([gp[0], gp[1], gp23])

额外优化建议

  • 预测价格的计算逻辑有误:当前代码gp[1] * userInf + gp[1]会导致价格被放大数倍(比如输入5的话,价格会变成2.13*5+2.13=12.78,不符合实际通胀逻辑),应该改成基于百分比的计算:
    gp23 = gp[1] * (1 + userInf / 100)
    
  • 可以给预测价格的柱子设置不同颜色,方便区分历史数据和预测数据:
    plt.bar(x[:2], y[:2], align='edge', width=-0.4, label='历史价格')
    plt.bar(x[2], y[2], align='edge', width=-0.4, label='2023预测价格', color='orange')
    plt.legend()
    

完整修正后的代码

#Comparing Gas Prices in Ireland From 2021 & 2022

import time
import matplotlib.pyplot as plt
import numpy as np
#The first number is the gas price in July of 2021 and the second number is the gas price in July of 2022
gp = [1.75, 2.13] 
diff = round(gp[1] - gp[0], 2)
diff1 = '€' + str(diff)
percInc = round(((gp[1] - gp[0]) / gp[0]) * 100, 2) 
percInc1 = str(percInc) + '%'

print('Today we will be comparing the Gas Prices in Ireland from 2021 & 2022')
time.sleep(4)
print('Gas Prices in July 2021 were €1.75 per litre and in July 2022 were €2.13 per litre.')
time.sleep(2)
print('The difference in price between 2021 and 2022 is', diff1)
time.sleep(2)
print('The percentage increase in price was',percInc1)
time.sleep(2)

print('')
print('Now it is your turn to predict the gas prices in 2023')
userInf = int(input('Enter the inflation rate for the next year (whole number between -10 and 10: '))
# 修正通胀计算逻辑
gp23 = gp[1] * (1 + userInf / 100)
print('The predicted price for 2023 is', round(gp23, 2))

x = np.array(['2021', '2022', '2023'])
# 修正数组创建方式
y = np.array([gp[0], gp[1], gp23])
plt.title('Comparing Gas Prices in Ireland')
plt.xlabel('Years')
plt.ylabel('Prices')
# 区分历史和预测数据的颜色
plt.bar(x[:2], y[:2], align='edge', width=-0.4, label='历史价格')
plt.bar(x[2], y[2], align='edge', width=-0.4, label='2023预测价格', color='orange')
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:01:09