使用plt.quiver绘图时遭遇ufunc 'isfinite' TypeError问题求助
解决plt.quiver绘制矢量图的TypeError问题
问题代码
import matplotlib.pyplot as plt x=[0.5, 0.09113826200606436, 0.09090926587458355, 0.09090909053329622, 0.09090909090689524, 0.09090909090901886] y=[-0.5, -0.09113826200606436, -0.09090926587458355, -0.09090909053329618, -0.09090909090689503, -0.09090909090901889] u=[0.9, 0.0005041764133415783, 3.84924083801641e-07, -8.267483364576833e-10, -4.830719158022134e-12, -1.584843367652411e-13] v=[-0.9, -0.0005041764133415783, -3.84924083801641e-07, 8.267483364576833e-10, 4.830691402446519e-12, 1.584843367652411e-13] colour=['red', 'red', 'red', 'red', 'red', 'red'] plt.quiver(x,y,u,v, colour)
报错信息
TypeError Traceback (most recent call last) <ipython-input-12-2e445afc7e85> in <module> 138 print(colour) 139 plt.rcParams["figure.figsize"] = (30,30) --> 140 plt.quiver(x,y,u,v, colour) 141 plt.scatter(stable_point_xaxis, stable_point_yaxis, color='blue') 142 #plt.scatter(uNew, vNew, color='red') 5 frames /usr/local/lib/python3.7/dist-packages/numpy/ma/core.py in masked_invalid(a, copy) 2367 cls = type(a) 2368 else: -> 2369 condition = ~(np.isfinite(a)) 2370 cls = MaskedArray 2371 result = a.view(cls) TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
问题原因
plt.quiver函数的参数顺序中,前四个参数是x, y, u, v,第五个位置参数是scale(用于缩放矢量的数值参数),而非颜色。直接传入字符串列表colour会导致numpy尝试对字符串执行np.isfinite(检查数值是否有限)操作,而字符串不支持该函数,因此抛出类型错误。
解决方案
需要通过**关键字参数color**来指定矢量颜色,而非位置参数传递。
修改后的代码(方式一:指定颜色列表)
import matplotlib.pyplot as plt x=[0.5, 0.09113826200606436, 0.09090926587458355, 0.09090909053329622, 0.09090909090689524, 0.09090909090901886] y=[-0.5, -0.09113826200606436, -0.09090926587458355, -0.09090909053329618, -0.09090909090689503, -0.09090909090901889] u=[0.9, 0.0005041764133415783, 3.84924083801641e-07, -8.267483364576833e-10, -4.830719158022134e-12, -1.584843367652411e-13] v=[-0.9, -0.0005041764133415783, -3.84924083801641e-07, 8.267483364576833e-10, 4.830691402446519e-12, 1.584843367652411e-13] colour=['red', 'red', 'red', 'red', 'red', 'red'] plt.rcParams["figure.figsize"] = (30,30) plt.quiver(x, y, u, v, color=colour) plt.show()
简化方式(所有矢量颜色一致)
因为所有矢量颜色都是红色,可直接传入单个颜色字符串,无需列表:
plt.quiver(x, y, u, v, color='red')
内容的提问来源于stack exchange,提问作者CSProgrammer
相关产品推荐
相关产品推荐

