如何用 Sympy 绘制点?
How To Graph Points With Sympy?
我需要计算和绘制函数及其前两个导数。然后,我需要在图上绘制原始函数的最小值和最大值。我已经计算了这些,但不知道如何绘制数据图表。
minimum/maximum 点的 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)
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()
我已经解决了这个问题。由于方程式的导数要么不存在,要么一条水平线,就会出现两难境地。
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()
为了在这种情况下使用 Sympy 定义临界点,并在 matplotlib.pyplot
中绘制结果,可以使用 sympy.utilities.lambdify
方法生成要在 [= 中绘制的点列表13=](由 user6655984 关注 post)。
数组已构建,但如果绘制的是常量值,则数组的长度可能不同,这在 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()
其他答案的不同方法
从 Plot 中获取图形和坐标轴。
然后添加其他图,例如点
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]
p = plot(x, x**2, show=False)
fig, axe = get_sympy_subplots(p)
# add additional plots
axe.plot([1,2,3], [1,2,3], "o")
fig.show()
我需要计算和绘制函数及其前两个导数。然后,我需要在图上绘制原始函数的最小值和最大值。我已经计算了这些,但不知道如何绘制数据图表。
minimum/maximum 点的 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)
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()
我已经解决了这个问题。由于方程式的导数要么不存在,要么一条水平线,就会出现两难境地。
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()
为了在这种情况下使用 Sympy 定义临界点,并在 matplotlib.pyplot
中绘制结果,可以使用 sympy.utilities.lambdify
方法生成要在 [= 中绘制的点列表13=](由 user6655984 关注 post)。
数组已构建,但如果绘制的是常量值,则数组的长度可能不同,这在 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()
其他答案的不同方法
从 Plot 中获取图形和坐标轴。
然后添加其他图,例如点
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]
p = plot(x, x**2, show=False)
fig, axe = get_sympy_subplots(p)
# add additional plots
axe.plot([1,2,3], [1,2,3], "o")
fig.show()