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

Matplotlib绘图报错:unsupported operand type(s) for -: 'str' and 'float'如何解决?

解决Matplotlib中"unsupported operand type(s) for -: 'str' and 'float'"错误

Hey,我之前也踩过这个坑!这个错误的核心原因是:Matplotlib的不同绘图函数对分类字符串数据的支持程度不一样——plt.bar()可以自动识别并处理字符串类型的x轴分类,但plt.scatter()和plt.plot()底层需要基于数值计算坐标位置,直接传入字符串就会触发类型不匹配的报错。

给你两种靠谱的解决办法:

方法一:用数值索引替代字符串x轴,手动设置刻度标签

这是最直观的方案,适合快速修复:

import matplotlib.pyplot as plt
import numpy as np

names = ["a", "b", "c"]
values = [1, 10, 100]
# 生成对应分类的数值索引
x_indices = np.arange(len(names))

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(x_indices, values)
plt.xticks(x_indices, names)  # 将数值索引替换为原字符串标签

plt.subplot(132)
plt.scatter(x_indices, values)
plt.xticks(x_indices, names)

plt.subplot(133)
plt.plot(x_indices, values)
plt.xticks(x_indices, names)

plt.suptitle('Categorical Plotting')
plt.show()

方法二:使用Matplotlib官方分类数据API(推荐)

如果后续要处理更复杂的分类场景(比如排序、新增分类),用官方的分类数据类型更稳妥:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import categories

names = ["a", "b", "c"]
values = [1, 10, 100]
# 将字符串列表转换为Matplotlib可识别的分类类型
categorical_names = categories.Categorical(names)

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(categorical_names, values)

plt.subplot(132)
plt.scatter(categorical_names, values)

plt.subplot(133)
plt.plot(categorical_names, values)

plt.suptitle('Categorical Plotting')
plt.show()

两种方法都能完美解决你的报错,选哪种看你后续的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 17:02:51