Matplotlib fill_between的where参数使用报错,求正确用法
解决Matplotlib fill_between中where参数的TypeError问题
Hey there! I totally get the frustration when a tutorial code doesn't run as expected—let's break this down and fix it.
为什么会触发这个错误?
你遇到的TypeError: '>' not supported between instances of 'list' and 'int',核心原因是Python原生的列表(list)不支持和单个整数直接进行元素级的比较。教程里的代码能正常运行,大概率是因为a和b在教程中是numpy数组,而不是普通列表。numpy数组支持「广播」操作,可以直接和单个数值做比较,返回一个布尔数组,这正是fill_between的where参数需要的格式。
两种可行的解决方案
方案1:将列表转换为numpy数组(推荐)
这是最贴合教程逻辑的方式,只需要导入numpy并把你的a、b列表转成numpy数组即可:
import matplotlib.pyplot as plt import numpy as np # 假设你的原始a和b是普通列表 a = [1,2,3,4,5] b = [30,35,32,36,31] # 转换为numpy数组 a_np = np.array(a) b_np = np.array(b) axis = plt.subplot2grid((1,1),(0,0)) axis.plot(a_np, b_np) axis.fill_between(a_np, b_np, 34, where=(b_np>34), facecolor='r', alpha=.5) plt.show()
方案2:手动生成布尔列表
如果你不想用numpy,可以通过列表推导式生成一个和b长度相同的布尔列表,作为where参数的值:
import matplotlib.pyplot as plt a = [1,2,3,4,5] b = [30,35,32,36,31] # 生成布尔列表:每个元素表示b对应位置是否大于34 where_condition = [val > 34 for val in b] axis = plt.subplot2grid((1,1),(0,0)) axis.plot(a, b) axis.fill_between(a, b, 34, where=where_condition, facecolor='r', alpha=.5) plt.show()
补充说明
fill_between的where参数需要的是一个布尔序列(数组或列表),长度要和x轴数据一致,用来标记哪些区域需要填充。当你用numpy数组时,b_np > 34会自动生成对应的布尔数组;而普通列表必须手动逐个判断生成布尔列表,才能被where参数正确识别。
内容的提问来源于stack exchange,提问作者Nikhil Rathore
相关产品推荐
相关产品推荐

