Using Sympy Equations for Plotting

时光毁灭记忆、已成空白 提交于 2019-12-17 18:29:31

问题


What is the best way to create a Sympy equation, do something like take the derivative, and then plot the results of that equation?

I have my symbolic equation, but can't figure out how to make an array of values for plotting. Here's my code:

from sympy import symbols
import matplotlib.pyplot as mpl

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)

nums = []
for i in range(1000):
    nums.append(t)
    t += 0.02

plotted = [x for t in nums]

mpl.plot(plotted)
mpl.ylabel("Speed")
mpl.show()

In my case I just calculated the derivative of that equation, and now I want to plot the speed x, so this is fairly simplified.


回答1:


You can use numpy.linspace() to create the values of the x axis (x_vals in the code below) and lambdify().

from sympy import symbols
from numpy import linspace
from sympy import lambdify
import matplotlib.pyplot as mpl

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)
lam_x = lambdify(t, x, modules=['numpy'])

x_vals = linspace(0, 10, 100)
y_vals = lam_x(x_vals)

mpl.plot(x_vals, y_vals)
mpl.ylabel("Speed")
mpl.show()

(improvements suggested by asmeurer and MaxNoe)

Alternatively, you can use sympy's plot():

from sympy import symbols
from sympy import plot

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)

plot(x, (t, 0, 10), ylabel='Speed')



回答2:


Using SymPy

You can use directly the plotting functions of SymPy:

from sympy import symbols
from sympy.plotting import plot as symplot

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)
symplot(x)

Most of the time it uses matplotlib as a backend.



来源:https://stackoverflow.com/questions/35390187/using-sympy-equations-for-plotting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!