And*_*ndy 4 python graphing matplotlib sympy
我需要计算并绘制一个函数及其前两个导数。然后,我需要在图上绘制原始函数的最小值和最大值点。我已经计算了这些,但不知道如何绘制数据图表。最小/最大点的 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();
Run Code Online (Sandbox Code Playgroud)
当我运行该程序时,我收到此错误。`
Traceback (most recent call last):
File "--------", line 58, in <module>
xval=criticalPoints[a];
TypeError: 'FiniteSet' object does not support indexing
Run Code Online (Sandbox Code Playgroud)
我尝试在 p 上绘制点并得到不同的错误
p.plot(criticalPoints,criticalPointsY);
AttributeError: 'Plot' object has no attribute 'plot'
Run Code Online (Sandbox Code Playgroud)
有没有办法在这个图上绘制点?(页)
使用其他答案的不同方法从图中获取图形和轴。然后添加额外的图,例如点。
用于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")
Run Code Online (Sandbox Code Playgroud)
在后端使用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()
Run Code Online (Sandbox Code Playgroud)
小智 5
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()
Run Code Online (Sandbox Code Playgroud)