使用Matplotlib绘图时触发错误:'Add' object is not callable
问题:Sympy符号表达式无法直接调用绘制Matplotlib图形
问题场景
我想用Matplotlib绘制函数图形,但在Intern Operation类的makeGraphic方法里遇到错误,报错提示TypeError: 'Add' object is not callable,具体出现在Y = [f(x) for x in X]这一行。
相关代码
makeGraphic方法代码
def makeGraphic(self, f, root): plt.rcParams['axes.unicode_minus'] = False fig = plt.figure(figsize=(6, 4)) # 新画布 # 使用axisartist.Subplot创建绘图区域对象ax ax = axisartist.Subplot(fig, 111) fig.add_axes(ax) X = np.linspace(-5, 10, 100) Y = [f(x) for x in X] # 报错位置 ax.plot(X, Y) ax.scatter(root, 0, color='red') #plt.legend([r'$a>1$'], loc ='lower right') print(max(X), max(Y)) ax.axis[:].set_visible(False) ax.axis["x"] = ax.new_floating_axis(0, 0, axis_direction="bottom") ax.axis["y"] = ax.new_floating_axis(1, 0, axis_direction="bottom") ax.axis["x"].set_axisline_style("->", size=1.0) ax.axis["y"].set_axisline_style("->", size=1.0) ax.annotate('x', xy=(5, 0), xytext=(4+1, 0.3)) ax.annotate('y', xy=(0, 1.0), xytext=(-0.2, 5)) plt.xlim(-5, 5) plt.ylim(-5, 5) X_lim = np.arange(-4, 4+1, 1) ax.set_xticks(X_lim) Y_lim = np.arange(-10,10+1, 1) ax.set_yticks(Y_lim) fstr = str(f) ax.annotate(rf'$y = {fstr}$', xy=(8, -3), xytext=(8, -3)) #plt.legend() plt.show()
导入语句
import numpy as np from sympy import diff import matplotlib.pyplot as plt import mpl_toolkits.axisartist as axisartist #CONSTANTS from operaciones.utils.constants import x
报错回溯信息
Traceback (most recent call last): File "c:\Users\user\Desktop\MetodosNumericConsola\main.py", line 13, in <module> hal.pointsToGraphic() File "c:\Users\user\Desktop\MetodosNumericConsola\operaciones\First\Halley.py", line 49, in pointsToGraphic super().makeGraphic(self.equation, self.root) File "c:\Users\emily\Desktop\MetodosNumericConsola\operaciones\ListOp\InternOperation.py", line 49, in makeGraphic Y = [f(x) for x in X] ^^^^^^^^^^^^^^^^^ File "c:\Users\emily\Desktop\MetodosNumericConsola\operaciones\ListOp\InternOperation.py", line 49, in <listcomp> Y = [f(x) for x in X] ^^^^ TypeError: 'Add' object is not callable
问题原因及解决办法
原因
传入的f是Sympy的符号表达式(比如Add类型,代表加法表达式),这类对象不能像普通Python函数那样直接用f(x)调用求值。
解决办法
用Sympy的lambdify函数把符号表达式转换成支持NumPy数组的可调用函数:
- 先导入
lambdify:
from sympy import lambdify
- 修改生成Y值的代码,替换原来的
Y = [f(x) for x in X]:
# 将符号表达式转为NumPy兼容函数 f_np = lambdify(x, f, 'numpy') # 直接对整个数组X求值,效率比列表推导更高 Y = f_np(X)
这样就能正确生成函数的Y值,解决'Add' object is not callable的错误,同时lambdify生成的函数支持批量处理数组,比逐个元素遍历更高效。
内容的提问来源于stack exchange,提问作者Wimmy
相关产品推荐
相关产品推荐

