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

如何使用两个数组调用plt.fill_between绘图并解决AttributeError报错

错误原因

.where()是Pandas Series、DataFrame对象的专属方法,你的valores是Numpy ndarray类型,没有该内置方法,因此触发AttributeError。

解决方案

优先使用plt.fill_between自带的where参数实现条件着色,无需额外处理数组,代码更简洁高效:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(14, 8))

# 填充数值高于0.5的区域
plt.fill_between(tiempos, valores, 0.5,
                 where=valores >= 0.5,
                 color='red', alpha=0.8)
# 填充数值低于-0.5的区域
plt.fill_between(tiempos, valores, -0.5,
                 where=valores <= -0.5,
                 color='blue', alpha=0.3)

plt.plot(tiempos, valores, color='black')
plt.show()

如果你需要提前处理数组得到遮盖后的结果,可以用Numpy顶层的np.where方法实现和Pandas .where()等价的效果:

# 不满足条件的位置设为NaN,fill_between会自动跳过
valores_above = np.where(valores >= 0.5, valores, np.nan)
valores_below = np.where(valores <= -0.5, valores, np.nan)

plt.fill_between(tiempos, valores_above, 0.5, color='red', alpha=0.8)
plt.fill_between(tiempos, valores_below, -0.5, color='blue', alpha=0.3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:15:08