python 如何绘制有症状的点?

wgmfuz8q  于 2022-11-27  发布在  Python
关注(0)|答案(4)|浏览(100)

我需要计算并绘制一个函数及其前两个导数。然后,我需要在图形上绘制原始函数的最小值点和最大值点。我已经计算了这些,但不知道如何绘制数据。最小值/最大值点的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)

9ceoxa92

9ceoxa921#

一种不同的方法与其他答案,以获得图形和轴从绘图。然后添加额外的绘图,如点。
使用matplotlib.figure(仅)将绘图保存为图像(不显示)。

import sympy as sp
from sympy.plotting.plot import MatplotlibBackend, Plot

def get_sympy_subplots(plot:Plot):
    backend = MatplotlibBackend(plot)

    backend.process_series()
    backend.fig.tight_layout()
    return backend.fig, backend.ax[0]

# plot from sympy
x = sp.symbols('x')
p = sp.plot(x, x**2, show=False)

# plot from backend
fig, axe = get_sympy_subplots(p)
# add additional plots
axe.plot([1,2,3], [1,2,3], "o")
fig.savefig("plot_from_figure")

在后端使用plt显示图

def get_sympy_subplots(plot:Plot):
    backend = MatplotlibBackend(plot)

    backend.process_series()
    backend.fig.tight_layout()
    return backend.plt

# plot from sympy
x = sp.symbols('x')
p = sp.plot(x, x**2, show=False)

# plot from backend
plt = get_sympy_subplots(p)
plt.plot([1,2,3], [1,2,3], "o")

plt.show()

idfiyjo8

idfiyjo82#

SymPy绘图可以与p.extend结合使用。但是SymPy绘图类型不包括点绘图,这是您想要的临界点。在这种情况下,您应该直接使用matplotlib,SymPy会在幕后执行此操作。
下面是一个基于你的代码的例子,但是没有分号,使用列表解析,并且matplotlib用于所有绘图。注意lambdify提供了一种在一组点上高效地计算一组SymPy表达式的方法。

from sympy import *
import numpy as np
import matplotlib.pyplot as plt

x = symbols('x')
equation = x*exp(-x**2/10)
firstDeriv = equation.diff(x)
secondDeriv = firstDeriv.diff(x)
criticalPoints = list(solveset(firstDeriv, x))
criticalPointsY = [equation.subs(x, a) for a in criticalPoints]
xx = np.linspace(-10, 10, 1000)
yy = lambdify(x, [equation, firstDeriv, secondDeriv])(xx)
plt.plot(xx, np.transpose(yy))
plt.plot(criticalPoints, criticalPointsY, 'k*')
plt.show()

7ivaypg9

7ivaypg93#

我已经解决了这个问题。这个两难的问题是由于方程的导数要么不存在,要么是一条水平线。

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()
fcg9iug3

fcg9iug34#

为了在这种情况下使用症状来定义临界点,并在matplotlib.pyplot中绘制结果,可以使用sympy.utilities.lambdify方法来生成要在mathplotlib中绘制的点列表(用户6655984的后续帖子)。
数组已构建,但如果绘制的是在numpy.transpose步骤中有问题的常量值,则数组的长度可能不相同。因此,在第一个matplotlib.pyplot之前传递了一个条件。

from sympy import *
import numpy as np
import matplotlib.pyplot as plt

x = symbols('x')
equation = x**2 + 2 #OK = x*exp(-x**2/10) OR x**2 + 2
firstDeriv = equation.diff(x)
secondDeriv = firstDeriv.diff(x)
criticalPoints = list(solveset(firstDeriv, x))
criticalPointsY = [equation.subs(x, a) for a in criticalPoints]
xx = np.linspace(-10, 10, 100)
lam_f= lambdify(x, [equation, firstDeriv, secondDeriv])
yy=[elem if  type(elem) == np.ndarray else np.full(len(xx), elem) for elem in lam_f(xx)]
plt.plot(xx, np.transpose(yy))
plt.plot(criticalPoints, criticalPointsY, 'k*')
plt.show()

相关问题