使用Matplotlib绘制热方程曲线出现色块异常,请求排查问题
问题分析与解决
你的代码生成色块而非正常曲线,核心原因及解决方法如下:
1. 采样点过度密集
函数中用np.linspace(0, total_time, total_time)生成时间数组,当total_time=232920时,会生成23万+个数据点。过多的点在绘图时因密度太高,视觉上呈现为色块而非清晰曲线。
2. 变量命名混淆(非致命但易误导)
函数返回的是时间数组和温度数组,但你用x, y接收,而x原本是函数里的位置参数,这种命名混淆会增加调试难度。
修改后的代码
import numpy as np import matplotlib.pyplot as plt def thermal_equation(t0, tm, pos, delta, w, total_time): # 调整采样点数,用10000个点平衡曲线细节与绘制性能 t = np.linspace(0, total_time, 10000) temp = t0 + tm * np.exp(-pos/delta) * np.cos(w*t - (pos/delta)) return t, temp # 用清晰的变量名接收返回值 time, temp = thermal_equation(28, 38, 4e-2, 9.1e-1, 9.7e-2, 232920) plt.plot(time, temp, label='temperature fluctuation') plt.xlabel('time (s)') plt.ylabel('temperature (°C)') plt.legend(loc='lower right') plt.show()
额外优化建议
- 若需观察局部细节,可通过
plt.xlim(0, 1000)限定时间范围,聚焦前1000秒的曲线变化; - 检查参数合理性:你的位置参数
pos=0.04m,热扩散长度delta=0.91m,pos/delta值很小,导致衰减项exp(-pos/delta)接近1,温度波动几乎无衰减,若不符合你的物理场景需核对参数单位与数值; - 若要保留全时间范围曲线,可添加
linewidth=0.5减小线宽,缓解密集感:plt.plot(time, temp, linewidth=0.5, label='temperature fluctuation')
内容的提问来源于stack exchange,提问作者Elisa909
相关产品推荐
相关产品推荐

