如何用Sympy绘制图形点?

2022-04-06 00:00:00 python matplotlib sympy graphing

问题描述

我需要计算并绘制一个函数及其前两个导数。然后,我需要在图上画出原始函数的最小点和最大点。我已经计算了这些数据,但不知道如何将数据绘制成图表。 最小/最大点的x值为 criticalPoints[]

y值为

criticalPointsY[]

以下是出现错误的代码段。

equation=CreateFunction();
    firstDeriv=equation.diff(x);
    secondDeriv=firstDeriv.diff(x);
    print(equation);
criticalPoints=solveset(firstDeriv,x);
criticalPointsY=[];
for a in criticalPoints:
    criticalPointsY.append(equation.subs(x,a));

p=plot(equation,firstDeriv,secondDeriv,(x,-10,10));
# Need to add the critical points to the graph. We have them, and the
# y values, but need to put them on the graphs.
print(criticalPoints)
print(criticalPointsY);
for a in range(0, len(criticalPoints)):
    xval=criticalPoints[a];
    yval=criticalPointsY[a];
    plt.plot(xval, yval, 'ro')
p.show();
plt.show();

当我运行该程序时,我收到以下错误。 `

Traceback (most recent call last):
  File "--------", line 58, in <module>
    xval=criticalPoints[a];
TypeError: 'FiniteSet' object does not support indexing

我已尝试绘制p上的点,但遇到不同的错误

    p.plot(criticalPoints,criticalPointsY);
AttributeError: 'Plot' object has no attribute 'plot'

有没有办法在这张图上绘制点?(P)


解决方案

我已修复该问题。这种两难境地是由于方程的导数要么不存在,要么是一条水平线。

x = symbols('x')
UserInput()
equation = CreateFunction()
firstDeriv = equation.diff(x)
secondDeriv = firstDeriv.diff(x)
workingEquations=[]
hasEquations=False
我在这一段中所做的是通过将等式转换为字符串并查看是否存在x值来进行测试。如果存在,我会将等式附加到后面要访问的数组中,否则,我会绘制水平线。我还翻转了一个布尔值,以便稍后告诉我们是否有一个变量为变量的等式。

if(not str(equation).find("x")==-1):
    workingEquations.append(equation)
    hasEquations=True
    print("True")
else:
    plt.axhline(y=equation)
if(not str(firstDeriv).find("x")==-1):
    workingEquations.append(firstDeriv)
else:
    plt.axhline(y=firstDeriv)
if(not str(secondDeriv).find("x")==-1):
    workingEquations.append(secondDeriv)
else:
    plt.axhline(y=secondDeriv)
try:
    criticalPoints = list(solveset(firstDeriv, x))
    criticalPointsY = [equation.subs(x, a) for a in criticalPoints]
    plt.plot(criticalPoints, criticalPointsY, 'k*')
except:
    print("No critical points")

如果我们有方程式,我们将从我们附加所有非水平方程式数组中为它们绘制图形。

if(hasEquations):
    xx = np.linspace(-10, 10, 1000)
    yy = lambdify(x, workingEquations)(xx)
    plt.plot(xx, np.transpose(yy))
plt.show()

相关文章