使用matplotlib axes.fill_between()时浮点数组触发isfinite类型错误
填充Matplotlib曲线与X轴区域的类型错误解决
问题描述
尝试用以下代码填充x轴与函数曲线之间的区域时触发TypeError:
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np s1_norm_x = np.array([0, l-b, l-b, l]) s1_norm_y = np.array([G_x, G_x, 0, 0]) figure, axs = plt.subplots(3, 1, sharex=True) ax_norm, ax_quer, ax_bieg = axs ax_norm.set_xticks([0, l-b, l]) ax_norm.set_xlabel('x') ax_norm.set_ylabel("Normalkraft - N(x) [kN]") ax_norm.plot(s1_norm_x, s1_norm_y, color='blue') ax_norm.fill_between(s1_norm_x, s1_norm_y, facecolor = 'red', alpha = 0.3) plt.show()
变量取值:l=1.1, b=0.8, G_x=-3.2031250000
改用长度为4的整数数组替换s1_norm_x和s1_norm_y时,填充显示正常但无法与曲线对齐。
完整错误信息:
TypeError Traceback (most recent call last) Cell In[24], line 11 9 ax_norm.set_ylabel("Normalkraft - N(x) [kN]") 10 ax_norm.plot(s1_norm_x, s1_norm_y, color='blue') ---> 11 ax_norm.fill_between(s1_norm_x, s1_norm_y, facecolor = 'red', alpha = 0.3) 13 plt.show() File ~\anaconda3\lib\site-packages\matplotlib\__init__.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs) 1439 @functools.wraps(func) 1440 def inner(ax, *args, data=None, **kwargs): 1441 if data is None: -> 1442 return func(ax, *map(sanitize_sequence, args), **kwargs) 1444 bound = new_sig.bind(ax, *args, **kwargs) 1445 auto_label = (bound.arguments.get(label_namer) 1446 or bound.kwargs.get(label_namer)) File ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py:5431, in Axes.fill_between(self, x, y1, y2, where, interpolate, step, **kwargs) 5429 def fill_between(self, x, y1, y2=0, where=None, interpolate=False, 5430 step=None, **kwargs): -> 5431 return self._fill_between_x_or_y( 5432 "x", x, y1, y2, 5433 where=where, interpolate=interpolate, step=step, **kwargs) File ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py:5336, in Axes._fill_between_x_or_y(self, ind_dir, ind, dep1, dep2, where, interpolate, step, **kwargs) 5332 kwargs["facecolor"] = \ 5333 self._get_patches_for_fill.get_next_color() 5335 # Handle united data, such as dates -> 5336 ind, dep1, dep2 = map( 5337 ma.masked_invalid, self._process_unit_info( 5338 [(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs)) 5340 for name, array in [ 5341 (ind_dir, ind), (f"{dep_dir}1", dep1), (f"{dep_dir}2", dep2)]: 5342 if array.ndim > 1: File ~\anaconda3\lib\site-packages\numpy\ma\core.py:2366, in masked_invalid(a, copy) 2364 cls = type(a) 2365 else: -> 2366 condition = ~(np.isfinite(a)) 2367 cls = MaskedArray 2368 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''
解决方法
错误核心是数组中存在非数值类型元素,或变量l、b、G_x未被正确定义为数值类型。
修复步骤
- 明确变量类型:在创建数组前,将
l、b、G_x定义为浮点数:l = 1.1 b = 0.8 G_x = -3.2031250000 - 强制数组数值类型:创建数组时指定
dtype=np.float64,确保所有元素为数值:s1_norm_x = np.array([0, l-b, l-b, l], dtype=np.float64) s1_norm_y = np.array([G_x, G_x, 0, 0], dtype=np.float64) - 验证数组内容:打印数组确认元素类型:
print(s1_norm_x) print(s1_norm_y)
完整修复代码
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np # 定义数值变量 l = 1.1 b = 0.8 G_x = -3.2031250000 # 创建数值类型数组 s1_norm_x = np.array([0, l-b, l-b, l], dtype=np.float64) s1_norm_y = np.array([G_x, G_x, 0, 0], dtype=np.float64) figure, axs = plt.subplots(3, 1, sharex=True) ax_norm, ax_quer, ax_bieg = axs ax_norm.set_xticks([0, l-b, l]) ax_norm.set_xlabel('x') ax_norm.set_ylabel("Normalkraft - N(x) [kN]") ax_norm.plot(s1_norm_x, s1_norm_y, color='blue') ax_norm.fill_between(s1_norm_x, s1_norm_y, facecolor='red', alpha=0.3) plt.show()
修改后,fill_between可正确识别数组数值,填充区域将与曲线完美对齐,且不会触发类型错误。
内容的提问来源于stack exchange,提问作者danbuza
相关产品推荐
相关产品推荐

