20

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.

user
  • 5,370
  • 8
  • 47
  • 75
MANA624
  • 986
  • 4
  • 10
  • 34

2 Answers2

30

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)

enter image description here

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')
user
  • 5,370
  • 8
  • 47
  • 75
  • 2
    It's better to use `lambdify` to create a numpy friendly expression from the sympy expression than to use subs. – asmeurer Feb 15 '16 at 01:44
  • 1
    It will be even faster if you do `lambdify(t, x, modules=['numpy'])` and `y_vals = lam_x(x_vals)` – MaxNoe Feb 15 '16 at 10:36
  • @asmeurer Indeed, `lambdify()` instead of my inefficient list comprehension with `subs()`, makes it 4 times faster. – user Feb 15 '16 at 10:53
  • @MaxNoe My tests show about 1-10% increase in speed which feels rather small. I ll include it though, since I guess it might have a more significant effect in other cases. – user Feb 15 '16 at 10:59
  • 1
    For simple functions and few points the increase might be small, but not for more complex stuff and more points. – MaxNoe Feb 15 '16 at 11:27
9

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)

enter image description here

Most of the time it uses matplotlib as a backend.

G M
  • 20,759
  • 10
  • 81
  • 84
  • how to extend this to a function of two variables? f(x,y) instead of f(x)? – baxx Oct 13 '19 at 17:31
  • 1
    @baxx that's another question you should ask in another thread, however you can use plot implicit https://docs.sympy.org/latest/modules/plotting.html – G M Oct 14 '19 at 07:15