python很坐标报错ufunc ‘isfinite‘ not supported for the input types

文章讲述了在使用Python中的matplotlib库进行绘图时遇到的TypeError,原因在于图中包含非数值类型的横坐标。解决方法是将横坐标数据转换为列表并传递给xticks函数,确保标签显示为指定的文字而非数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python使用plt画图的时候,出错。

出错全文如下:

Traceback (most recent call last):

    plt.show()
    return _get_backend_mod().show(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 __call__
    manager.show(**kwargs)
    self.canvas.show()
    FigureCanvasAgg.draw(self)
    self.figure.draw(self.renderer)
    result = draw(artist, renderer, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    return draw(artist, renderer)
           ^^^^^^^^^^^^^^^^^^^^^^
    mimage._draw_list_compositing_images(
    a.draw(renderer)
    return draw(artist, renderer)
           ^^^^^^^^^^^^^^^^^^^^^^
    mimage._draw_list_compositing_images(
    a.draw(renderer)
    return draw(artist, renderer)
           ^^^^^^^^^^^^^^^^^^^^^^
    ticks_to_draw = self._update_ticks()
      
    minor_locs = self.get_minorticklocs()
                 ^^^^^^^^^^^^^^^^^^^^^^^^
    mask = np.isclose(tr_minor_locs[:, None], tr_major_locs[None, :],
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    yfin = isfinite(y)
           ^^^^^^^^^^^
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''

Process finished with exit code 1

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默认横纵坐标都需要是数值型,中间的数据也需要是数值型。而你使用了其他类型。

比如:

python绘制对应的折线图或者柱状图的时候,我们有时候希望横坐标是一些固定的文字,而不是标准的数值坐标。

希望将横坐标的12345,改成下面的字符。

需要用到的程序:

labels = ['1K','10K','100K','1M','10M']
plt.xticks(selected_data.iloc[:,0], labels,fontsize= fontsize) 

以上代码就是报错。

需要将代码改成下面这样:

labels = ['1K','10K','100K','1M','10M']
positions = selected_data.iloc[:,0].tolist()
plt.xticks(positions , labels,fontsize= fontsize)  #使得标签现实的是给定的文字标签

OK

# 决策边界可视化 # 选择两个特征并重新训练模型,原来是四维没法可视化 feature1, feature2 = '有工作', '有自己的房子' X_sub = df[[feature1, feature2]] y_sub = df['类别'] X_train_sub, X_test_sub, y_train_sub, y_test_sub = train_test_split(X_sub, y_sub, test_size=0.2, random_state=42) clf_sub = DecisionTreeClassifier() clf_sub.fit(X_train_sub, y_train_sub) # 生成网格数据 x_min, x_max = X_sub[feature1].min() - 0.1, X_sub[feature1].max() + 0.1 y_min, y_max = X_sub[feature2].min() - 0.1, X_sub[feature2].max() + 0.1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01)) # 将网格点转换为带特征名的DataFrame grid_points = pd.DataFrame(np.c_[xx.ravel(), yy.ravel()], columns=X_train_sub.columns) # 自动匹配特征名称 Z = clf_sub.predict(grid_points).reshape(xx.shape) # ← 警告消除 # 绘图 plt.figure(figsize=(8, 6)) plt.contourf(xx, yy, Z, alpha=0.4, cmap='RdYlBu') scatter = plt.scatter(X_train_sub[feature1], X_train_sub[feature2], c=y_train_sub, edgecolors='k', cmap='RdYlBu', label='训练数据') plt.xlabel(feature1) plt.ylabel(feature2) plt.title('决策边界可视化(固定其他特征)') plt.legend(handles=scatter.legend_elements()[0], labels=['是', '否'], title="类别") plt.colorbar(scatter) plt.show()Traceback (most recent call last): File "D:\35433\Documents\机器学习\任务二\任务二.py", line 75, in <module> plt.contourf(xx, yy, Z, alpha=0.4, cmap='RdYlBu') File "D:\python\Lib\site-packages\matplotlib\pyplot.py", line 3181, in contourf __ret = gca().contourf( ^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\matplotlib\__init__.py", line 1521, in inner return func( ^^^^^ File "D:\python\Lib\site-packages\matplotlib\axes\_axes.py", line 6760, in contourf contours = mcontour.QuadContourSet(self, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\matplotlib\contour.py", line 708, in __init__ kwargs = self._process_args(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\matplotlib\contour.py", line 1326, in _process_args x, y, z = self._contour_args(args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\matplotlib\contour.py", line 1370, in _contour_args z = ma.masked_invalid(z, copy=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\numpy\ma\core.py", line 2426, in masked_invalid res = masked_where(~(np.isfinite(a)), a, copy=copy) ^^^^^^^^^^^^^^ 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''
最新发布
03-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值